Java Pattern Regex Matcher. Look for string inside text

the code bellow help you to auto detect if the input text contains pattern like “Purchase Order number, customer number…”

...
	// pattern can be something like "[A-Z]{2}-\\w{3}-\\w{5}" so this;
	public static List<String> getResultList(String srcText, String regexStr) {
		List<String> result = new ArrayList<String>();
		try {
			final Pattern myPattern = Pattern.compile(regexStr);
			Matcher m = myPattern.matcher(srcText);
			while (m.find()) {
				result.add(m.group());
			}
		} catch (Exception e) {
			// DO SOMETHING HERE
			return null;
		}

		if (result.isEmpty()) {
			return null;
		}
		return result;
	}

	public static void main(String[] args) {
		String text1 = "Purchase Order N° [CU-USA-B0052]";
		String text2 = " Please Confirm the Purchase Order N° QT-YAZ-A1983 and Cancel Purchase Order Number [QT-USA-A0001]";
		List<String> poNumbers = getResultList(text2, "QT-\\w{3}-\\w{5}");
		if (poNumbers != null) {
			for (String po : poNumbers) {
				System.out.println("Purchase Order Num. Found = " + po);
			}
		}
	}
...
Tagged with: , ,
Posted in Java_corner

Adam’s apple, Newton’s apple and Steve Apple

Dear Steve,
I write this letter even if  it’s late but i know well that your soul will read it.
I know that you still alive and your are everywhere in everyone, that now you’re so happy by seeing how much people from every part in this earth are crying you . But me I’m not, I’m happy too, because I know well that you left a thousands of genius behind you in the Apple Inc, and they will give their best to honorate your memory. 
I don’t know if you will need an iPhone in the other world, may be you can talk to each other by telepathy take photos by eyes, or may be the humain body is useless and you got a new body format. I hope the Siri  (iPhone 4 S) voice’s will be yours to talk to you every day. 
Be happy Mr. Steve because you reinvented the machine by giving it life and sens, you faced challenges throughout your career without giving up.  

Someone wrote in a forum : humanity was marked by three apples: Adam’s apple, Newton’s apple & Steve’s Apple. That’s true, you marked the humanity

I will never forget your speech Mr Steve at Stanford, a speech of Hope and faith, which let’s us to believe on our capablities and  how can we reach our aims.

Peace on you & Have a nice heaven

In memory of Steve Jobs
Posted in Java_corner

support spring in your presentation layer

Some Time we work on project that use spring wih a MVC Framework(home made, it does not support spring integration) , some times we need to write extra servlet that do what others classes can not do.

For each time, to use a spring service inside your controller, you do this in general:

ApplicationContext context =
                    WebApplicationContextUtils
                     .getWebApplicationContext(getServletContext());
Object myDao = context.getBean("daoBeanName");

The great difficulty here is that developers can sometimes forget to instantiate beans, or instantiate them in different places, making the code complex

The idea then is to factor the instantiation in one place by a single class.This idea is verysimple, let’s take a look:

1/create an annotation “@SpringServiceController” to be associated with attributes representatives your spring beans in your servlets or other mvc controller.

2/create a SpringBeanFactory class witch contains 2 statics methods

public static final void initBeans(Object obj,ServletContext scxt){...}//to init beans for your mvc controller that it doesnot extends HttpServlet
public static final void initBeans(HttpServlet servlet) {...}//to init beans inside servlet

3/ For Servlets, if you want to factorise code , create a master HttpServlet Class, overide init() and do this

public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();

SpringBeanFactory.initBeans(this);
}

So each servlet has to extend your master servlet class, or simply overide init() method for each servlet and call initBeans(this);

For your magic MVC Controller, inside constructor or intilizer methods call

SpringBeanFactory.initBeans(this,context);

Then for each call your services will be setted by Spring

For example you can write this servlet code example:

public class ServletName extends HttpServlet{
@SpringServiceController
private MySpringService  mySpringService=null;
init(){
public void init() throws ServletException {	
		super.init();
		SpringBeanFactory.initBeans(this);
	}  
public MySpringService getMySpringService(){
           return this.mySpringService;
}
public void setMySpringService(MySpringService mySpringService){
           this.mySpringService=mySpringService;
}
}

Here is the code:

Annotation Code

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Younss AZZAYANI
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface SpringServiceController{}

SpringBeanFactory class code

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringBeanFactory {
public static final void initBeans(Object obj,ServletContext scxt){
ApplicationContext beanContext = WebApplicationContextUtils
.getWebApplicationContext(scxt);
Class classInstance = obj.getClass();
Field[] clazzFields = classInstance.getDeclaredFields();
for (Field field : clazzFields) {

if (field.isAnnotationPresent(SpringServiceController.class)) {
String fieldName = field.getName();
String fieldType = field.getType().getSimpleName();
String setterMethodOfField = "set"
+ String.valueOf(fieldName.charAt(0)).toUpperCase()
+ fieldName.substring(1);
try {
Method setterMethod = classInstance.getMethod(
setterMethodOfField, field.getType());
setterMethod.invoke(obj, Class.forName(
field.getType().getCanonicalName()).cast(
beanContext.getBean(String.valueOf(
fieldType.charAt(0)).toLowerCase()
+ fieldType.substring(1))));
} catch (SecurityException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e.getMessage());
} catch (BeansException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalArgumentException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage());
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getMessage());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
}
}
}
public static final void initBeans(HttpServlet servlet) {
initBeans(servlet, servlet.getServletContext());
}
Tagged with: , ,
Posted in Java_corner

real database paginiation for hibernate spring …

Since I start working on java web application , every time I found that people don’t care if we really do a database pagination or only an ajax pagination (some JavaScript code).

both methods are good, but it depends on the context and how many lines we have to handle.

My post is not about the choice (advantage and disadvantage ) but it will be talking about an approach ( a home-made java code) that looks like Value List Handler design pattern. this code helps me every time I’ve to show an html table with thousands of lines with filters, number of line per page….

So lets see what i did, and please if you have any comment or remarks or any advice that will make the code better, you will be welcome.

here is a javacode and uml diagram of the pagination handler, i didn’t give the presentation code, because i think that any one can implement this code as he likes(js or taglibs…) .

The class diagram:

class diagram
Real Pagination Diagram home-made

the Java Code:


package org.pagination.realpagination;
import java.io.Serializable;
import java.util.List;
import java.util.Map;/**
* this interface must be implemented by your service and or dao. it will be
* injected in the PaginationHandler to get data from your database, web service
* or any.
*
* @author Younss AZZAYANI
*
*/
public interface IPagination {
/**
* get List of T instance.
*
* @param <T>
*            Object Class
* @param clazz
*            object Class to select
* @param firstResult
*            the first result number
* @param maxResult
*            number of lines
* @param orderBy
*            order by
* @param order
*            order ASC or DESC
* @param filter
*            java.util.Map<String,Object> what will you adding inside
*            WHERE Clause
* @param clazzes
*            sub classes of <T> if you have an heritance and you wish get
*            some subclasses not all.
* @return List<T>
*/
public <T> List<T> getPaggedObjectList(Class<T> clazz, int firstResult,
int maxResult, String orderBy, String order,
Map<String, Object> filter, Class<? extends T>… clazzes);

/**
* count the number of lines returned by the dao query.
*
* @param <T>
*            Object Class
*
* @param clazz
*            Object Class
* @param filter
*            java.util.Map<String,Object> what will you adding inside
*            WHERE Clause
* @param clazzes
*            sub classes of <T> if you have an heritance and you wish get
*            some subclasses not all.
* @return int count of lines.
*/
public <T> int countNumberOfObject(Class<T> clazz,
Map<String, Object> filter, Class<? extends T>… clazzes);

/**
* get element of T from database
*
* @param <T>
*            object class
* @param clazz
*            object class
* @param id
*            serializable identifier
* @return instance of <T> if found null if not.
*/
public <T> T findElement(Class<T> clazz, Serializable id);
}

————————————————————-
package org.pagination.realpagination;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* Page is the main object that contain all information about pagination, it
* contains, the current page list, number of line, filters,internal actions,
* number of line per page, sort by, sort desc or asc
*
* @author Younss AZZAYANI
*
*/

public class Page<T> implements Serializable {

private static final long serialVersionUID = 1L;

public final static String PAGE_ACTION = “PAGE_ACTION”;

public static final String NEXT_PAGE = “NEXT_PAGE”;

public static final String PREVIOUS_PAGE = “PREVIOUS_PAGE”;

public static final String FIRST_PAGE = “FIRST_PAGE”;

public static final String LAST_PAGE = “LAST_PAGE”;

public static final String SIZE_PAGE = “SIZE_PAGE”;

public static final String PARAM_SIZE_PAGE = “PARAM_SIZE_PAGE”;

public static final String SORT_TABLE = “SORT”;

public static final String FILTER = “FILTER”;

public static final String PARAM_ORDER_BY = “orderBy”;

public static final String PARAM_ORDER_TYPE = “orderType”;

public static final String PARAM_OBJECT_ID = “objectId”;

public enum Order {
DESC(“DESC”), ASC(“ASC”);
private String value;

Order(String value) {
this.value = value;
}

public String getValue() {
return this.value;
}
}

public enum RowNum {
FIVE(5), TEN(10), TWENTY(20), THIRTY(30), FORTY(40), FIFTY(50);
private int value;

RowNum(int value) {
this.value = value;
}

public int getValue() {
return this.value;
}

public static RowNum valueOf(int value) {
switch (value) {
case 5:
return FIVE;
case 10:
return TEN;
case 20:
return TWENTY;
case 30:
return THIRTY;
case 40:
return FORTY;
case 50:
return FIFTY;

default:
return TEN;
}

}
}

/**
* user selected number of lines to show
*/
private RowNum maxResult = RowNum.TEN;

private Order order = Order.ASC;

/**
* DB current firstResult, from where we start retrieve data.
*/
private int firstResult = 0;

/**
* current page number.
*/
private int currentPageNumber = 0;

/**
* total pages Number.
*/
private int numOfPages = 0;

/**
* total data lines count.
*/
private int numOfLines = 0;

/**
* current loaded list
*/
List<T> currentList = null;

private String orderBy = “”;

private Map<String, Object> filter = null;

/**
* let us to update pages number in depend with the number of line to show.
*
*/
protected void initPagination() {
this.currentPageNumber = 0;
this.firstResult = 0;
this.orderBy = “”;
this.numOfPages = numOfLines / maxResult.value;

if (numOfLines % maxResult.value != 0) {
this.numOfPages++;
}
}

/**
* @param currentList
*            the currentList to set
*/
protected void setCurrentList(List<T> bindedList) {
this.currentList = bindedList;
}

/**
* @return the firstResult
*/
public int getFirstResult() {
return firstResult;
}

/**
* @param firstResult
*            the firstResult to set
*/
public void setFirstResult(int index) {
this.firstResult = index;
}

/**
* @return the numOfLines
*/
public int getNumOfLines() {
return numOfLines;
}

/**
* @param numOfLines
*            the numOfLines to set
*/
public void setNumOfLines(int numOfLines) {

this.numOfLines = numOfLines;
initPagination();
}

/**
* @return the numOfPages
*/
public int getNumOfPages() {
return numOfPages;
}

/**
* @param numOfPages
*            the numOfPages to set
*/
public void setNumOfPages(int numOfPages) {
this.numOfPages = numOfPages;
}

/**
* @return the currentPageNumber
*/
public int getCurrentPageNumber() {
return currentPageNumber;
}

/**
* @param currentPageNumber
*            the currentPageNumber to set
*/
public void setCurrentPageNumber(int pageNumber) {
this.currentPageNumber = pageNumber;
}

/**
* @return the orderBy
*/
public String getOrderBy() {
return orderBy;
}

/**
* @param orderBy
*            the orderBy to set
*/
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}

/**
* @return the maxResult
*/
public RowNum getMaxResult() {
return maxResult;
}

/**
* @param maxResult
*            the maxResult to set
*/

protected void setMaxResult(RowNum numOfLineToShow) {

this.maxResult = numOfLineToShow;

initPagination();

}

/**
* go to the previous page.
*
*/
protected void goToPrevious() {
this.currentPageNumber–;
this.firstResult = this.currentPageNumber * this.maxResult.value;
}

/**
* go to the next page.
*
*/
protected void goToTheNext() {
this.currentPageNumber++;
this.firstResult = this.currentPageNumber * this.maxResult.value;
}

/**
* go to the first page.
*
*/
protected void goToTheFirst() {
this.currentPageNumber = 0;
this.firstResult = this.currentPageNumber * this.maxResult.value;
}

/**
* go to the last page.
*
*/
protected void goToTheLast() {
this.currentPageNumber = this.numOfPages – 1;
this.firstResult = this.currentPageNumber * this.maxResult.value;
}

/**
* @return the order
*/
public Order getOrder() {
return order;
}

/**
* @param order
*            the order to set
*/
protected void setOrder(Order order) {
this.order = order;
}

/**
* @return the filter
*/
protected Map<String, Object> getFilter() {
if (filter == null) {
filter = new HashMap<String, Object>();
}

return filter;
}

/**
* @param filter
*            the filter to set
*/
@SuppressWarnings(“unused”)
protected void setFilter(Map<String, Object> filter) {
this.filter = filter;
}

protected void sortTheList(String orderBy, String order) {
initPagination();
setOrderBy(orderBy);
setOrder(Order.valueOf(order));

}

public Object getFilterValue(String key) {
return getFilter().get(key);
}

public final RowNum[] getRowNumList() {

return RowNum.values();
}

public Iterator<T> iterator() {
return this.currentList.iterator();
}

}

—————————————————–
package org.pagination.realpagination;

import java.lang.reflect.Field;
import java.util.Map;

/**
* A controller class that makes pagination possible, the current page is
* stocked in “page attribute”,this attribute must be stocked in scope like
* request or session for re-use, this controllor is used inside a
* controller(MVC), if no page at the first moment insert null, else insert your
* saved page.
*
* @author Younss AZZAYANI
*
* @param <code><T></code>
*/
public class PaginationHandler<T> {

IPagination pagination = null;

Page<T> page = null;

/**
* @param pagination
*            the pagination service
* @param page
*            the page stocked in a scope
*/
public PaginationHandler(IPagination pagination, Page<T> page) {
super();
setPagination(pagination);
setPage(page);
}

/**
*
* @param clazz
*            Business Object
* @param paramMap
*            <code>Map<String,String></code>params from request
* @param classes
*            “instance of <code>Class<T></code> if you are doing
*            inheritance
* @throws SecurityException
* @throws NoSuchFieldException
*/
public void paginate(Class<T> clazz, Map<String, String> paramMap,
Class<? extends T>… classes) throws SecurityException,
NoSuchFieldException {
String action = null;
String sizeOfPage = null;
if (paramMap != null && paramMap.size() > 0) {
action = paramMap.get(Page.PAGE_ACTION);
sizeOfPage = paramMap.get(Page.PARAM_SIZE_PAGE);
}

if (sizeOfPage != null
&& sizeOfPage.trim().length() > 0
&& Page.RowNum.valueOf(sizeOfPage).getValue() != getPage()
.getMaxResult().getValue()) {
// set the number of lines per page
getPage().setMaxResult(Page.RowNum.valueOf(sizeOfPage));
}

if (action == null || action.length() == 0) {
// when no action sent brings me the first page
countNumberOfObject(clazz, classes);
} else {

if (action.equals(Page.PREVIOUS_PAGE)) {
getPage().goToPrevious();
}
if (action.equals(Page.NEXT_PAGE)) {
getPage().goToTheNext();
}
if (action.equals(Page.FIRST_PAGE)) {
getPage().goToTheFirst();
}
if (action.equals(Page.LAST_PAGE)) {
getPage().goToTheLast();
}

if (action.equals(Page.SORT_TABLE)) {
getPage().sortTheList(paramMap.get(Page.PARAM_ORDER_BY),
paramMap.get(Page.PARAM_ORDER_TYPE));
}
if (action.equals(Page.FILTER)) {
// upfate the filter
updateFilter(clazz, paramMap);
// reinit the num of lines per page
countNumberOfObject(clazz, classes);
}
}

// update the page element list contents
fillTheList(clazz, classes);

}

/**
* populate the filter. the filter keys are the attributes of the Business
* Object (a Java Bean). so in your interface (a jsp interface for example)
* the input names must correspond to the Java Bean Properties.
*
* @param paramMap
*            <code>Map<String,String[]></code> ,may be your request
*            params Map
* @param fieldArray
*            Field[] array of your JAva Bean
*/
private void populateFilter(Map<String, String> paramMap, Field[] fieldArray) {

for (Field field : fieldArray) {

String paramName = field.getName();
String paramValue = (String) paramMap.get(paramName);
if (paramValue != null && paramValue.length() > 0) {
Class<?> c = null;
try {
c = Class.forName(field.getType().getName());
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// when the field is an Enum
if (field.getType().isEnum()) {

@SuppressWarnings(“unchecked”)
Class<? extends Enum> ce = (Class<? extends Enum>) c;
@SuppressWarnings(“unchecked”)
Enum<?> enumValue = Enum.valueOf(ce, paramValue);
getPage().getFilter().put(paramName, enumValue);

} else if (c == Boolean.class) {
getPage().getFilter().put(
paramName,
(paramValue.equals(“true”) ? Boolean.valueOf(true)
: Boolean.valueOf(false)));
} else {

getPage().getFilter().put(paramName, paramValue);
}
// this filter can be more developped (agregation…)
// add code here

}
}
}

/**
* popultate the page list of Business Object returned by the service
*
* @param clazz
*            master Business Object
* @param classes
*            sub Classes Of Business Object Class
*
*/
private void fillTheList(Class<T> clazz, Class<? extends T>… classes) {

getPage().setCurrentList(
getPagination().getPaggedObjectList(clazz,
getPage().getFirstResult(),
getPage().getMaxResult().getValue(),
getPage().getOrderBy(),
getPage().getOrder().getValue(), getPage().getFilter(),
classes));

}

/**
* update the filter
*
* @param clazz
*            business Object(java bean) Class instance
* @param paramMap
*            <code>Map<String,String[]></code> ,may be the request
*            params Map
* @throws SecurityException
* @throws NoSuchFieldException
*/
private void updateFilter(Class<T> clazz, Map<String, String> paramMap)
throws SecurityException, NoSuchFieldException {
getPage().setFilter(null);
// get the field array of Business Object
Field[] fieldArray = clazz.getDeclaredFields();
// init the filter with new values
populateFilter(paramMap, fieldArray);

}

/**
* set the number of lines founded
*
* @param clazz
* @param classes
*/
private void countNumberOfObject(Class<T> clazz,
Class<? extends T>… classes) {

getPage().setNumOfLines(
getPagination().countNumberOfObject(clazz,
getPage().getFilter(), classes));

}

/**
* @return the page
*/
public Page<T> getPage() {
return page;
}

/**
* @param page
*            the page to set
*/
private void setPage(Page<T> page) {
this.page = page;
}

/**
* @return the pagination
*/
public IPagination getPagination() {
return pagination;
}

/**
* @param pagination
*            the pagination to set
*/
public void setPagination(IPagination pagination) {
this.pagination = pagination;
}

}

——————————————-

an example of IPagination implementation:

package some.package;
import org.pagination.realpagination.IPagination;
public class MyMasterBusinessObjectDao implements IPagination{…

//this may be your hibernate dao or others


//the implementation
public List getPaggedObjectList(Class clazz, int firstResult,
int maxResult, String orderBy, String order,
Map<String, Object> filter,Class<? extends T>… classes) {String query = “SELECT obj FROM ” + clazz.getName() + ” obj “;
boolean clauseWhereAdded = false;
if (filter != null && !filter.isEmpty()) {for (Iterator iter = filter.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
if (filter.get(key) == null ||(filter.get(key) instanceof String
&&((String) filter.get(key)).lenght==0))  {
continue;
}if (!clauseWhereAdded) {
query += “WHERE”;
clauseWhereAdded = true;
} else {
query += ” AND “;
}
query += ” obj.” + key + ”  like :_” + key + ” “;
}
}

if(classes != null && classes.length >0){
if(!clauseWhereAdded){
query += “WHERE”;
clauseWhereAdded = true;
}else{
query += ” AND “;
}
query += ” obj.class in(“;
boolean addComma = false;
for(Class instanceClass : classes){
if(!addComma){

addComma = true;
}else{
query+=”,”;
}
query+=instanceClass.getCanonicalName();
}
query += “) “;
}

if (orderBy !=null && orderBy.length()>0) {
query += ” ORDER BY obj.” + orderBy + ” ” + order;
} else {
query += ” ORDER BY obj.id ASC”;
}
logger.debug(“hqlQuery=[“+query+”]”);
//hibernate query
Query hqlQuery = createQuery(query);
if (filter != null && !filter.isEmpty()) {
for (Iterator iter = filter.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
if (filter.get(key) == null ||(filter.get(key) instanceof String
&& ((String) filter.get(key))length()==0) ) {
continue;
}

hqlQuery.setParameter(“_” + key, filter.get(key));
}
}
return hqlQuery.setFirstResult(firstResult).setMaxResults(maxResult)
.getResultList();

}

//the implementation
public int countNumberOfObject(Class clazz,
Map<String, Object> filter, Class<? extends T>… classes) {

String query = “SELECT count(*) FROM ” + clazz.getName() + ” obj “;
boolean clauseWhereAdded = false;
if (filter != null && !filter.isEmpty()) {

for (Iterator iter = filter.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
if (filter.get(key) == null || (filter.get(key) instanceof String
&& ((String) filter.get(key)).length()==0)) {
continue;
}

if (!clauseWhereAdded) {
query += “WHERE”;
clauseWhereAdded = true;
} else {
query += ” AND “;
}
query += ” obj.” + key + ”  like :_” + key + ” “;

}
}
if(classes != null && classes.length >0){
if(!clauseWhereAdded){
query += “WHERE”;
clauseWhereAdded = true;
}else{
query += ” AND “;
}
query += ” obj.class in(“;
boolean addComma = false;
for(Class<?extends T> instanceClass : classes){
if(!addComma){
addComma = true;
}else{
query+=”,”;
}
query+=instanceClass.getCanonicalName();
}
query += “) “;
}
Query hqlQuery = createQuery(query);
if (filter != null && !filter.isEmpty()) {
for (Iterator<String> iter = filter.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
if (filter.get(key) == null || (filter.get(key) instanceof String
&& ((String) filter.get(key)).length()==0)) {
continue;
}

hqlQuery.setParameter(“_” + key, filter.get(key));
}
}
logger.debug(“hql query = [” + query +”]”);
return ((Long) hqlQuery.getSingleResult()).intValue();
}


public T findElement(Class clazz, Serializable id){
return (T) getEntityManager().find(clazz, id);
}


}

Posted in Java_corner