Wednesday, May 23, 2012

String util services for String handling in java


public static boolean equalsIgnoreCase(String str1, String str2) {
        return ((str1 == null) ? (str2 == null) : str1.equalsIgnoreCase(str2));
    }
 public static boolean equals(String str1, String str2) {
        return ((str1 == null) ? (str2 == null) : str1.equals(str2));
    }

    public static String trim(String str) {
        return ((str == null) ? null : str.trim());
    }

   public static boolean isNotEmpty(String str) {
        return ((str != null) && (str.length() > 0));
    }

  public static boolean isEmpty(String str) {
        return ((str == null) || (str.length() == 0));
    }


    public static boolean isBlank(String str) {
        int strLen;

        if ((str == null) || ((strLen = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }

        return true;
    }

 public static boolean isNotBlank(String str) {
        int strLen;

        if ((str == null) || ((strLen = str.length()) == 0)) {
            return false;
        }

        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return true;
            }
        }

        return false;
    }
public static boolean equalNullOrTrimEmpty(String str1, String str2){
        return (str1 == null
                    ? (str2 == null
                            ? true
                            : (str2.trim().equals("")
                                ? true
                                : false))
                    : (str2 == null
                            ? (str1.trim().equals("")
                                ? true
                                : false)
                            : (str1.trim().equals(str2.trim()))
                        )
                );                        
    }

public static boolean equalNullOrTrimEmptyIgnoreCase(String str1, String str2){
        return (str1 == null ? (str2 == null ? true : (str2.trim().equals("") ? true : false)): (str2 == null? (str1.trim().equals("")? true: false): (str1.trim().equalsIgnoreCase(str2.trim()))));                        
    }


public static String getFormattedAmount(double param) {
        if(param == 0.0)
            return "$0.00";
        return NumberFormat.getCurrencyInstance().format(param);   
    }
   
    public static String getFormattedAmount(String param) {
        if(isEmpty(param))
            return "";
        if (param.startsWith("$")){
            return param;
        }
        try{
            double f1=Double.parseDouble(param);
            return NumberFormat.getCurrencyInstance().format(f1);   
        }catch(NumberFormatException e){
            return param;
        }
    }
   
    public static String getPercentage(double val){
        return NumberFormat.getPercentInstance().format(val);
    }
   
    public static String getPercentage(int actualVal, int totalVal){
        return getPercentage((1.0*actualVal)/(1.0*totalVal));
    }   



 public static String getAlpha(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if (Character.isLetter(str.charAt(i)) == true) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }


public static String getAlphaNumeric(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if (Character.isLetterOrDigit(str.charAt(i)) == true) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }

 public static String getAlphaNumericStar(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if ((Character.isLetterOrDigit(str.charAt(i)) == true) ||
                    (str.charAt(i) == '*')) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }

How to genarate Random values/Password in java



import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Random;

public class RandomTest {

    public static void main(String argv[]) throws IOException {
        System.out.println(" getRandomPassword :"+getRandomPassword(20));

  }
        public static String getRandomPassword(int maxLength)throws IOException {
            String[] array = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0"};
             Random generator = new Random();
            StringBuffer sbuff = new StringBuffer();
            int d = 0;
            for(int i = 0; i < maxLength ; i++){
                  d = generator.nextInt(array.length);
                  sbuff.append(array[d]);
            }
            return sbuff.toString();
      }

}

Monday, May 21, 2012

how to call a method from command prompt in java

package com.jnet.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException {
        Test t=new Test();
        Method m = t.getClass().getMethod(args[0], new Class[] {});
        Object ret = m.invoke(t, new Object[] {});
        System.out.println((String)ret);
            }

    public static String m1(){
        return "sudheer";
    }
}

Saturday, May 19, 2012

A pseudo attribute name is expected solution

A pseudo attribute name is expected

If you get the message "A pseudo attribute name is expected" when validating your xml file you have probably done a mistake typing your encoding declaration.
The culprit code should look like :

1.<?xml version="1.0" encoding="UTF-8">
instead of
1.<?xml version="1.0" encoding="UTF-8"?>
There is a very small difference and it has nothing to do with the description of the error message. You have forgotten a question mark at the end of your encoding declaration.

Friday, May 18, 2012

jboss server accessing from other machines with IP address

Start the server followed by the commnad

c:\programs files\JBOSS 5.0GA\bin>run.bat -b 0.0.0.0

Wednesday, May 16, 2012

How to parse String xml using jdom,dom

String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?> "+
"<principal>"+
  "<busCity>CITY</busCity>"+
  "<busCountry /> "+
  "<busState>CT</busState> "+
  "<busStr1>BUS ADDRESS</busStr1> "+
  "<busStr2 /> "+
  "<busStr3 /> "+
  "<busZip>11111</busZip> "+
  "<principalName>MICHEL</principalName> "+
  " <resCity>CITY</resCity> "+
  "  <resCountry /> "+
  "<resState>AL</resState> "+
  "<resStr1>RES ADDRESS</resStr1> "+
  "<resStr2 /> "+
 " <resStr3 /> "+
  "<resZip>23123</resZip> "+
  "<title>PRESIDENT</title> "+
  "</principal>";


 SAXBuilder builder = new SAXBuilder();
    
          try {
   
            Document document = (Document) builder.build(new StringReader(xml));
            Element node = document.getRootElement();
           
             System.out.println("busCity : " + node.getChildText("busCity"));
               System.out.println("busCountry: " + node.getChildText("busCountry"));
               System.out.println("busState : " + node.getChildText("busState"));
               System.out.println("busStr1 : " + node.getChildText("busStr1"));
              
               System.out.println("busStr2 : " + node.getChildText("busStr2"));
               System.out.println("busStr3: " + node.getChildText("busStr3"));
               System.out.println("busZip : " + node.getChildText("busZip"));
               System.out.println("principalName : " + node.getChildText("principalName"));
              
               System.out.println("resCity : " + node.getChildText("resCity"));
               System.out.println("resCountry: " + node.getChildText("resCountry"));
               System.out.println("resState : " + node.getChildText("resState"));
               System.out.println("resStr1 : " + node.getChildText("resStr1"));
              
               System.out.println("resStr2 : " + node.getChildText("resStr2"));
               System.out.println("resStr3: " + node.getChildText("resStr3"));
               System.out.println("resZip : " + node.getChildText("resZip"));
               System.out.println("title : " + node.getChildText("title"));

} catch (IOException io) {
            System.out.println(io.getMessage());
          } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
          }




dom.
..................................................

javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db = factory.newDocumentBuilder(); org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();   inStream.setCharacterStream(new java.io.StringReader(xmlString)); org.xml.sax.Document doc = db.parse(inStream);

Xml parsing using jdom in java

<?xml version="1.0"?>
<company>
 <staff>
  <firstname>yong</firstname>
  <lastname>mook kim</lastname>
  <nickname>mkyong</nickname>
  <salary>100000</salary>
 </staff>
 <staff>
  <firstname>low</firstname>
  <lastname>yin fong</lastname>
  <nickname>fong fong</nickname>
  <salary>200000</salary>
 </staff>
</company>

3. Java File

Use JDOM parser to parse above XML file.
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
 
public class ReadXMLFile {
 public static void main(String[] args) {
 
   SAXBuilder builder = new SAXBuilder();
   File xmlFile = new File("c:\\file.xml");
 
   try {
 
  Document document = (Document) builder.build(xmlFile);
  Element rootNode = document.getRootElement();
  List list = rootNode.getChildren("staff");
 
  for (int i = 0; i < list.size(); i++) {
 
     Element node = (Element) list.get(i);
 
     System.out.println("First Name : " + node.getChildText("firstname"));
     System.out.println("Last Name : " + node.getChildText("lastname"));
     System.out.println("Nick Name : " + node.getChildText("nickname"));
     System.out.println("Salary : " + node.getChildText("salary"));
 
  }
 
   } catch (IOException io) {
  System.out.println(io.getMessage());
   } catch (JDOMException jdomex) {
  System.out.println(jdomex.getMessage());
   }
 }
}
Output
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

Friday, May 11, 2012

Soundex in DB2

Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.

SOUNDEX converts an alphanumeric string to a four-character code to find similar-sounding words or names. The first character of the code is the first character of character_expression and the second through fourth characters of the code are numbers that represent the letters in the expression. Vowels in character_expression are ignored unless they are the first letter of the string. Zeroes are added at the end if necessary to produce a four-character code.
The following tables defines the numbers that represent the various letters.
Number
Represents the Letters
1
B, F, P, V
2
C, G, J, K, Q, S, X, Z
3
D, T
4
L
5
M, N
6
R
Ignored
A, E, I, O, U, H, W, and Y.
For example, the SOUNDEX code for the expression 'Washington' is W252. W, 2 for the S, 5 for the N, 2 for the G. The remaining letters are disregarded. For more information about the SOUNDEX code,


  1. Names With Double Letters If the surname has any double letters, they should be treated as one letter. For example:
    • Gutierrez is coded G-362 (G, 3 for the T, 6 for the first R, second R ignored, 2 for the Z).
  2. Names with Letters Side-by-Side that have the Same Soundex Code Number If the surname has different letters side-by-side that have the same number in the soundex coding guide, they should be treated as one letter. Examples:
    • Pfister is coded as P-236 (P, F ignored, 2 for the S, 3 for the T, 6 for the R).
    • Jackson is coded as J-250 (J, 2 for the C, K ignored, S ignored, 5 for the N, 0 added).
    • Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored, 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
  3. Names with Prefixes If a surname has a prefix, such as Van, Con, De, Di, La, or Le, code both with and without the prefix because the surname might be listed under either code. Note, however, that Mc and Mac are not considered prefixes.
    For example, VanDeusen might be coded two ways: V-532 (V, 5 for N, 3 for D, 2 for S)
    or
    D-250 (D, 2 for the S, 5 for the N, 0 added).
  4. Consonant Separators If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Example:
    Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.

    If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example:
    Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
SELECT * FROM CUSTOMER
WHERE SOUNDEX(NM_NAME) = SOUNDEX('POLLY')