Tuesday, 8 May 2012

Java String Tokenizer Example

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, ",;:" sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return.
The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not returned.
Delimiters are not returned as tokens by the first two forms. Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to be extracted. Since StringTokenizer implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.
Here is an example that creates a StringTokenizer to parse "key=value" pairs. Consecutive sets of "key=value" pairs are separated by a semicolon.
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java-Rainbows;" +
"author=Emiley J;" +
"publisher=Rainbow.com;" +
"copyright=2012;";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is shown here:
title Java-Rainbow
author Emiley J
publisher Rainbow.com
copyright 2012

Monday, 7 May 2012

Email Address Validation using Regular Expression

Email Regular Expression Pattern

^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$
Description
^   #start of the line
  [_A-Za-z0-9-]+ #  must start with string in the bracket [ ], must contains one or more (+)
  (   #  start of group #1
    \\.[_A-Za-z0-9-]+ #     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*   #  end of group #1, this group is optional (*)
    @   #     must contains a "@" symbol
     [A-Za-z0-9]+       #        follow by string in the bracket [ ], must contains one or more (+)
      (   #    start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #      follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*  #    end of group #2, this group is optional (*)
      (   #    start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #      follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )   #    end of group #3
$   #end of the line
 
 
 
 
Whole combination is means, email address must start with “_A-Za-z0-9-” ,
 optional follow by “.[_A-Za-z0-9-]“, and end with a “@” symbol. The 
email’s domain name must start with “A-Za-z0-9″, follow by first level 
Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level 
Tld (.com.au, .com.my) “\\.[A-Za-z]{2,}”, where second level Tld must 
start with a dot “.” and length must equal or more than 2 characters. 
 
 
 
 

Java Regular Expression Example

Here’s a Java example to show the use of regex to validate an email address.
 
 
package com.rainbow.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class EmailValidator{
 
   private Pattern pattern;
   private Matcher matcher;
 
   private static final String EMAIL_PATTERN = 
                   "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
                   [A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
 
   public EmailValidator(){
    pattern = Pattern.compile(EMAIL_PATTERN);
   }
 
   /**
    * Validate hex with regular expression
    * @param hex hex for validation
    * @return true valid hex, false invalid hex
    */
   public boolean validate(final String hex){
 
    matcher = pattern.matcher(hex);
    return matcher.matches();
 
   }
}
 
 
 
 
 
Here’s the unit test for above email validator.
package com.rainbow.regex;
 
import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Email validator Testing
 * 
 *
 */
public class EmailValidatorTest {
 
 private EmailValidator emailValidator;
 
 @BeforeClass
        public void initData(){
  emailValidator = new EmailValidator();
        }
 
 @DataProvider
 public Object[][] ValidEmailProvider() {
  return new Object[][]{
   {new String[] {
      "mkyong@yahoo.com", "mkyong-100@yahoo.com",
                           "mkyong.100@yahoo.com" ,"mkyong111@mkyong.com", 
      "mkyong-100@mkyong.net","mkyong.100@mkyong.com.au",
      "mkyong@1.com", "mkyong@gmail.com.com"
              }}
   };
 }
 
 @DataProvider
 public Object[][] InvalidEmailProvider() {
  return new Object[][]{
   {new String[] {
      "mkyong","mkyong@.com.my","mkyong123@gmail.a",
      "mkyong123@.com","mkyong123@.com.com",
                           ".mkyong@mkyong.com","mkyong()*@gmail.com",
       "mkyong@%*.com", "mkyong..2002@gmail.com",
      "mkyong.@gmail.com","mkyong@mkyong@gmail.com", 
                           "mkyong@gmail.com.1a"
          }}
  };
 }
 
 @Test(dataProvider = "ValidEmailProvider")
 public void ValidEmailTest(String[] Email) {
 
    for(String temp : Email){
  boolean valid = emailValidator.validate(temp);
  System.out.println("Email is valid : " + temp + " , " + valid);
  Assert.assertEquals(true, valid);
    }
 
 }
 
 @Test(dataProvider = "InvalidEmailProvider", 
        dependsOnMethods="ValidEmailTest")
 public void InValidEmailTest(String[] Email) {
 
    for(String temp : Email){
     boolean valid = emailValidator.validate(temp);
     System.out.println("Email is valid : " + temp + " , " + valid);
     Assert.assertEquals(false, valid);
    } 
 } 
}

Reference

  1. http://en.wikipedia.org/wiki/E-mail_address
  2. http://tools.ietf.org/html/rfc2822#section-3.4.1
  3. http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression
 
 



Sunday, 6 May 2012

Java Code - Listing files and Folders in a Directory

import java.io.*;

public class  DirListing{
  private static void dirlist(String fname){
  File dir = new File(fname);
    String[] chld = dir.list();
  if(chld == null){
  System.out.println("Specified directory does not exist or is not a directory.");
  System.exit(0);
    }else{
  for(int i = 0; i < chld.length; i++){
  String fileName = chld[i];
  System.out.println(fileName);
  }
  }
  }
  public static void main(String[] args){
  switch(args.length){
  case 0: System.out.println("Please Mention Directory.");
  System.exit(0);
  case 1: dirlist(args[0]);
  System.exit(0);
  default : System.out.println("Multiple files are not allow.");
    System.exit(0);
  }
  }

Friday, 27 April 2012

Java/J2EE Updates

Hi.....
Welcome to this page

U will get latest and usefull updates ,news and articles related to Java/J2ee technologies very soon....