Ultimate Java Regular Expression to validate any email address.

34 Comments

My post about Java regular expression gets a lot of hits daily. Someone commented that the regular expression I included in that post does not block certain invalid email addresses. So I updated the Java regular expression to validate email address. I am pretty sure that the following Java regular expression will validate any email address.

"^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";

More

article clipper vert  Ultimate Java Regular Expression to validate any email address.
 

How to read properties file in Spring.

13 Comments



If you need to read properties file in your Spring application all you need is to configure a PropertyPlaceholderConfigurer bean in your application context.
Following example shows how to read property values from a properties file named config.properties. This file needs to be in your classpath so Spring can find it.

Let’s begin by creating a simple Java class that will use the properties values from the file.

package com.zparacha.spring.examples.config;

public class CreateUser {
	//Spring will populate these fields through Dependency Injection.
        private String name;
	private String email;
	private String URL;

	public CreateUser(){}
	public String getName() {
	  return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getURL() {
		return URL;
	}

	public void setURL(String url) {
		URL = url;
	}
	public void displayUser() {
		System.out.println("Name=" + this.name);
		System.out.println("Email="+ this.email);
		System.out.println("URL=" + this.URL);
	}
}

More

article clipper vert How to read properties file in Spring.
 

How to configure multiple handlers in a Spring MVC web application

4 Comments


In Spring MVC, DispatcherServlet relies on handler mapping to determine which controller the request should be sent to. All handler mapping classes in Spring implement org.springframework.web.servlet.HandlerMapping interface. Spring distribution contains following four implementation of HandlerMapping interface.

  • BeanNameUrlHandlerMapping
  • SimpleUrlHandlerMapping
  • ControllerClassNameHandlerMappign
  • CommonsPathMapHandlerMapping

BeanNameUrlHandlerMapping is the simplest of all and DispatcherServlet looks for this mapping by default.

You can use any one of these handler mappings in your application by just configuring a bean in your application context file. For e.g; to use BeanNameUrlHandlerMapping you will have a bean declaration similar to



But can you use more than one handler mappings in an application? More

article clipper vert How to configure multiple handlers in a Spring MVC web application
 

Extract substring from end of a Java String

1 Comment

Today I’ll show you how to extract last few characters (a substring) from a string in Java. Here is the code to do this.

public class SubStringEx{
/**
 Method to get the substring of length n from the end of a string.
 @param   inputString - String from which substring to be extracted.
 @param   subStringLength- int Desired length of the substring.
 @return lastCharacters- String
 @author Zaheer Paracha

*/
public String getLastnCharacters(String inputString,
                                 int subStringLength){
    int length = inputString.length();
	if(length <= subStringLength){
	  return inputString;
	}
	int startIndex = length-subStringLength;
	return inputString.substring(startIndex);
  }
}

Let's say you want to get the last four digits from a Social Security number. Here is how you will do this by calling the method declared above.

 public static void main(String args[]){
  String ssn ="123456789";
  SubStringEx subEx = new SubStringEx();
   String last4Digits = subEx.getLastnCharacters(ssn,4);
   System.out.println("Last 4 digits are " + last4Digits); //will print 6789
 }

This method is useful in scenarios where you don't know the length of a string. For example a variable that holds credit card number may have variable length. If you want to extract the last four digits of the credit card this method will come in handy.

Enjoy.

article clipper vert Extract substring from end of a Java String
 

How to add external jar files to Maven project POM

5 Comments

Maven has made compiling Java projects almost an effortless job. You no longer need to worry about placing all the required class files in your classpath. All you have to do is to include dependencies in your POM file and Maven takes care of the rest. It automatically downloads the jar file that your project depends on and include them in your build classpath. But what if you want to include a jar file that is not available from Maven repositories? To include such jar files you will have to manually install the jar into your local maven repository. Let say you need Oracle driver which is included in ojdbc14.jar. Download the jar file from Oracle and then execute following command.

C:\>mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar

Then add this dependency to your project POM file.


      com.oracle
      ojdbc14
      10.2.0
      compile

	


Now when you build your project ojdb14.jar will be available.

You can follow the same steps for your own jar files. For example if you have created a jar file (e.g. utils.jar) of helper classes and need that jar file in some other project you will first install the jar to your repository and then add the dependency in your POM file.

C:\>mvn install:install-file -Dfile=utils.jar -DgroupId=com.zparacha.example -DartifactId=utils -Dversion=1.0 -Dpackaging=jar

And the dependency for your POM will be like


      com.zparacha.example
      utils
      1.0.0
      compile

And all the class files will become available to your project.
Enjoy.

article clipper vert How to add external jar files to Maven project POM
 

Import static elements for more readable Java code

4 Comments

One of the welcome additions to Java language in Java 5 release is the static import declaration. static import works in the same way as traditional import declaration but it imports only the static members of a class.
Traditional import declaration looks like this
import java.util.*;
The above statement will import all the classes under java.util package.

The format of static import declaration is similar with the addition of keyword static. E.g;

import static java.lang.Math.*;

This statement will import all the static members of java.lang.Math class.

Similar to import declaration the static import offers two options. You can import all static members of a class or import only the members that you need in your program.

import static java.lang.Math.PI;
will import only PI.
import static java.lang.Math.*;
will import all static elements from Math class.
More

article clipper vert Import static elements for more readable Java code
 

Test your Java skills.

7 Comments

Even with many years of experience with programming in Java one cannot claim that he or she has mastered the language. What I found out with experience is that unless your job offers you diverse problems to solve, you are more likely to work on similar projects and hence may end up using the exact features of the language. And this leads to being forgetful about the minute and basic aspects of the language. To stay up-to-date with the latest developments in any area it is vital that you regularly read relevant magazines, books, and/or subscribe to the blogs. It is also important that you test your knowledge of the subject by taking quizzes once in a while. A good quiz will make you think about the subject broadly and will also point out your weak points. This will not only help you think about what you have learned over the years but it will also tell you the aspects of the subject that you need to improve on. For Java developers who would like to check their knowledge of their beloved programming language More

article clipper vert Test your Java skills.
 

Three ways to find minimum and maximum values in a Java array.

48 Comments

minmax Three ways to find minimum and maximum values in a Java array.

In Java you can find maximum or minimum value in a numeric array by looping through the array. Here is the code to do that.

public static int getMaxValue(int[] numbers){
  int maxValue = numbers[0];
  for(int i=1;i < numbers.length;i++){
    if(numbers[i] > maxValue){
	  maxValue = numbers[i];
	}
  }
  return maxValue;
}

public static int getMinValue(int[] numbers){
  int minValue = numbers[0];
  for(int i=1;i<numbers.length;i++){
    if(numbers[i] < minValue){
	  minValue = numbers[i];
	}
  }
  return minValue;
}

These are very straight forward methods to get maximum or minimum value of an array but there is a more cleaner way to do this. More

article clipper vert Three ways to find minimum and maximum values in a Java array.
 

How to read properties file in Java.

15 Comments

Reading properties file in Java is much easier than you might have thought. Following example illustrates one simple way of reading properties from a properties file.

Let’s say we need to read from myConfig.properties file.




The properties file has following entries.

Directory = C:/prodFiles/
NumberOfFiles = 25
Extension = java

Here is the java code to read the values of these keys.

import java.util.Properties;
import java.io.*;
public class ReadValues{
   private static final String PROP_FILE="myConfig.properties";
   public void readPropertiesFile(){
       try{
  	     InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
	     Properties prop = new Properties();
             prop.load(is);
	     String directory = prop.getProperty("Directory");
             String numberOfFiles = prop.getProperty("NumberOfFiles");
	     String  fileExtension = prop.getProperty("Extension");
             is.close();
	  /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }
  }

The code is quite simple and self explanatory. Let me know if you have any questions.

article clipper vert How to read properties file in Java.
 

How to validate email, SSN, phone number in Java using Regular expressions.

46 Comments


email 300x225 How to validate email, SSN, phone number in Java using Regular expressions.

Email

Regular Expressions offer a concise and powerful search-and-replace mechanism.
They are patterns of characters used to perform search, extract or replace operations on the given text. Regular expressions can also be used to validate that the input conforms to a given format.

For example, we can use Regular Expression to check whether the user input is a valid Social Security number, a valid phone number or a valid email number, etc.
More

article clipper vert How to validate email, SSN, phone number in Java using Regular expressions.
 

Older Entries Newer Entries