tags:

views:

43

answers:

2

private String getEmailTemplateWithActualValueForAccount(String template, Account account) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Map<String,String> map = new HashMap<String, String>(); 
    List<String> listTags = new ArrayList<String>();
    Map<Method, String> methodList = new HashMap<Method, String>();

    int startIndex=0;
    int endIndex=0;

    for(int i=0; i<template.length(); i++)
    {
        char ch = template.charAt(i);
        if(ch=='$')
            startIndex = i+1;
        if(ch=='#')
        {
            endIndex = i+1;
            listTags.add(template.substring(startIndex,endIndex));
        }

    }

    Method[] methods = Account.class.getMethods();

    for (Method method : methods) {
        String methodName = method.getName();
        if(method.getName().startsWith("get"))
        {
            methodList.put(method, methodName.substring(3,methodName.length()).toUpperCase()+"#");
        }
    }

    Set<Method> methodKeySet = methodList.keySet();
    for (Method method : methodKeySet) {
        for (String string : listTags) {

            if(methodList.get(method).equals(string))
            {
                try{
                    Object obj = method.invoke(account, null);
                    if(obj!=null)
                        map.put(string, obj.toString());
                }catch(NullPointerException e){
                }
            }
        }
    } 

    final StringBuilder list = new StringBuilder( "\\$(" );
    for( final String key: map.keySet() )
    { 
        list.append( key ); 
        list.append( "|" ); 
    }
    list.append( "[^\\s\\S])" );
    Pattern pattern = Pattern.compile( list.toString() );
    Matcher matcher = pattern.matcher( template );


    final StringBuffer stringBuffer = new StringBuffer();
    while( matcher.find() ){
        final String string = matcher.group( 1 );
        matcher.appendReplacement( stringBuffer, map.get( string )); 
    }
    matcher.appendTail( stringBuffer );

    return stringBuffer.toString();
}

I got an exception at line of code "Object obj = method.invoke(account, null);" Code is perfectly working but as this code is in scheduler it will create an log at every 20 second on jboss server.

A: 

Instead of catching NullPointerException, you should catch InvocationTargetException, and check the wrapped exception.

eljenso
A: 

The invoke method of Method throws an InvocationTargetException "if the underlying method throws an exception", according to the Javadoc. So you better look into the method that you are invoking to find out why it's throwing an exception. Check the exception stack trace for the root cause.

David