I use it to check for null.DataSet has a structure of both String Integer and Bigdecimal data types.
How to shorten the condition code? Is there any way? To shorten my code. Thank you.
public void ConfrimData(DataSet data) {
if (StringUtils.isEmpty(data.getA())
|| StringUtils.isEmpty(data.getB())
|| StringUtils.isEmpty(data.getC())
|| StringUtils.isEmpty(data.getD())
|| StringUtils.isEmpty(data.getE())
|| StringUtils.isEmpty(data.getF())
){
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
return;
}
_DataSet
private String A = null;
private Integer B = null;
private String C= null;
private String D = null;
private BigDecimal E= null;
private String F= null;
Well, you could make it slightly less repeaty using streams, but it won't make it necessarily better, let alone faster:
LinkedHashMap<Supplier, String> map = new LinkedHashMap<>();
map.put(data::getA, Var.VALUE_A);
map.put(data::getB, Var.VALUE_B);
map.put(data::getC, Var.VALUE_C);
map.put(data::getD, Var.VALUE_D);
map.put(data::getE, Var.VALUE_E);
map.put(data::getF, Var.VALUE_F);
List<String> logMessages = map.entrySet().stream()
.filter(entry -> StringUtils.isEmpty(entry.getKey().get()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
if (!logMessages.isEmpty()) {
logMessages.forEach(loggerTransaction::info);
}
else {
// Remaining code
}
In your first if statement you check all the parameters to see if any of them are empty.
Then, in the inner if statements, you check them again. The first check is redundant. The return statement is also not necessary since it does not end the method early or returns any data.
Here is a shorter version that should give the same result:
public void confirmData(DataSet data) {
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
}
EDIT
Here is a slightly prettier solution with less code repetition:
public void confirmData(DataSet data) {
logIfEmpty(data.getA(), Var.VALUE_A);
logIfEmpty(data.getB(), Var.VALUE_B);
logIfEmpty(data.getC(), Var.VALUE_C);
logIfEmpty(data.getD(), Var.VALUE_D);
logIfEmpty(data.getE(), Var.VALUE_E);
logIfEmpty(data.getF(), Var.VALUE_F);
}
private void logIfEmpty(Object check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
}
}
EDIT #2
And if you have other code you want to execute if you did not find any empty values, you can do this:
public void confirmData(DataSet data) {
boolean foundEmpty;
foundEmpty = logIfEmpty(data.getA(), Var.VALUE_A);
foundEmpty = logIfEmpty(data.getB(), Var.VALUE_B) || foundEmpty;
foundEmpty = logIfEmpty(data.getC(), Var.VALUE_C) || foundEmpty;
foundEmpty = logIfEmpty(data.getD(), Var.VALUE_D) || foundEmpty;
foundEmpty = logIfEmpty(data.getE(), Var.VALUE_E) || foundEmpty;
foundEmpty = logIfEmpty(data.getF(), Var.VALUE_F) || foundEmpty;
if(foundEmpty) {
return;
}
}
private boolean logIfEmpty(String check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
return true;
}
return false;
}
Maybe assigning a flag...
public void ConfrimData(DataSet data) {
boolean flag;
if (flag = StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (flag = StringUtils.isEmpty(data.getB()) || flag) {
loggerTransaction.info(Var.VALUE_B);
}
if (flag = StringUtils.isEmpty(data.getC()) || flag) {
loggerTransaction.info(Var.VALUE_C);
}
if (flag = StringUtils.isEmpty(data.getD()) || flag) {
loggerTransaction.info(Var.VALUE_D);
}
if (flag = StringUtils.isEmpty(data.getE()) || flag) {
loggerTransaction.info(Var.VALUE_E);
}
if (flag = StringUtils.isEmpty(data.getF()) || flag) {
loggerTransaction.info(Var.VALUE_F);
}
if (flag) return;
I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts
Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);
My code throwing java.lang.ClassCastException exception error, Why this error will get?. I am using com.android.internal.telephony API's. i.e You can find classes I am using here Call.java<http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/com/android/internal/telephony/Call.java>, CallManger.java <http://hi-android.info/src/com/android/internal/telephony/CallManager.java.html> I have created a Subclaas of Call.java like this:
public class MyCall extends Call{
CallManager cm = CallManager.getInstance();
Phone.State state;
Connection c;
Phone mDefaultPhone;
private final ArrayList<Connection> emptyConnections = new ArrayList<Connection>();
MyCall ringingCall;
#Override
public List<Connection> getConnections() {
state = cm.getState();
ringingCall = (MyCall) cm.getRingingCalls();
System.out.println("**inside getConnections="+ringingCall);
if ( ringingCall != null && !ringingCall.isIdle()) {
System.out.println("**call is not null***");
return ((MyCall) ringingCall).getConnections();
}
else
{
System.out.println("**list is null***");
return emptyConnections;
}
}
#Override
public Phone getPhone() {
// TODO Auto-generated method stub
return null;
}
#Override
public void hangup() throws CallStateException {
// TODO Auto-generated method stub
}
#Override
public boolean isMultiparty() {
// TODO Auto-generated method stub
return false;
}
public Connection
getEarliestConnection() {
System.out.println("inside EarliestConnection");
List l;
long time = Long.MAX_VALUE;
Connection c;
Connection earliest = null;
l = getConnections();
if (l == null) {
return null;
}else if ( l.size() == 0)
{
return null;
}
System.out.println("value of connection is=="+l);
for (int i = 0, s = l.size() ; i < s ; i++) {
c = (Connection) l.get(i);
long t;
t = c.getCreateTime();
if (t < time) {
earliest = c;
time = t;
}
}
return earliest;
}
}
I called CallManger.java like this in my own class
CallManager cm = CallManager.getInstance();
My another class is CallUpdate, it should give me a OutgoingCall states (i.e other side phone is Busy, Power-off, not-reachable etc.) The code is like this:
public class CallUpdate {
Call myCall = new MyCall();
Connection myConn = new MyConnection();
CallManager cm = CallManager.getInstance();
public Object getCallFailedString(){
myConn = myCall.getEarliestConnection();
System.out.println("myConn is ******"+myConn);
System.out.println("myCall is ******"+myCall);
if(myConn == null){
System.out.println("myConn is null ******");
return null;
}
else
{
Connection.DisconnectCause cause = myConn.getDisconnectCause();
System.out.println("myconn is not null ******"+cause);
switch(cause){
case BUSY :
System.out.println("inside busy");
break;
case NUMBER_UNREACHABLE :
System.out.println("inside un-reachable");
break;
case POWER_OFF :
System.out.println("inside power off");
break;
}
}
return myConn;
}
I called this class in BroadCastReceiver(). But i am getting connection is null. My code is not getting inside else part. So that I added some code in getConnection method of MyCall class like this:
public List<Connection> getConnections() {
state = cm.getState();
ringingCall = (MyCall) cm.getRingingCalls();
System.out.println("**inside getConnections="+ringingCall);
if ( ringingCall != null && !ringingCall.isIdle()) {
System.out.println("**call is not null***");
return ((MyCall) ringingCall).getConnections();
}
else
{
System.out.println("**list is null***");
return emptyConnections;
}
}
But I am getting java.lang.ClassCastException: on Line:
ringingCall = (MyCall) cm.getRingingCalls();
And also on l = getConnection();
How to solve this ??
Thx in advance.
Change your code as below
List<MyCall> ringingCall = cm.getRingingCalls();
I believe your cm.getRingingCalls(); returning ArrayList of Call / MyCall
getRingingCalls returns a List<Call> i.e. a list of Call objects. You're trying to cast it to a single MyCall, instead of a List, so you get a ClassCastException.
You need to correct your type to a List:
List<MyCall> ringingCall;
ringingCall = cm.getRingingCalls();
or, use the first element in the list:
MyCall ringingCall;
if(!cm.getRingingCalls().isEmpty()){
ringingCall = cm.getRingingCalls().get(0);
}
I'm doing a simple MessageRenderer.
It's specification:
Render message based on an Context (it's a map that's contains all key/value pair parameters)
Supports simple render such as: Your username is << username >>. Assume username in the context is barcelona and the result will be Your username is Barcelona.
Supported function-like object. Example: Current time is << now() >>, now(): is an object that will returns a string of current date time. And result will be: Current time is 2011-05-30
Each parameter of function can also be templated: Current time is << now( << date_format >> ) >> . This template returns a string of current date time with format is the value of key 'date_format' retrieved from the Context. Assume date_format in Context is dd/MM/yyyy and the result will be: Current time is 30/05/2011
Each parameter of function can also be templated with a different method call: Time is << now_locale ( << getLocale() >> ). Assume that getLocale() is an function object that will be return a locale is en_US and the result will be: Time is 2011/05/30 11:20:34 PM
Template can be nested. Example: Your user name is << << username >> >>. It means, Key username has value param1, Key param1 has value is barcelona so the final result will be: Your user name is Barcelona.
My classes and interfaces:
RenderContext.java
public interface RenderContext {
public String getParameter(String key);
}
MessageRenderer.java
public interface MessageRenderer {
public String render(String s, RenderContext... context);
}
MethodExpressionEvaluator.java
// Using this class to implements the method evaluation, such as now(), now_locale()
public interface MethodExpressionEvaluator {
public String evaluate(String[] methodParams, RenderContext... context);
}
AbstractMessageRenderer.java
public abstract class AbstractMessageRenderer implements MessageRenderer {
public static final String DEFAULT_NULL = "###";
public static final String PLACEHOLDER_START_TOKEN = "<<";
public static final String PLACEHOLDER_END_TOKEN = ">>";
protected int lenPlaceholderStartToken = 0;
protected int lenPlaceholderEndToken = 0;
protected String nullToken;
protected String placeholderStartToken;
protected String placeholderEndToken;
protected boolean escape = true;
public AbstractMessageRenderer() {
placeholderStartToken = PLACEHOLDER_START_TOKEN;
placeholderEndToken = PLACEHOLDER_END_TOKEN;
lenPlaceholderStartToken = placeholderStartToken.length();
lenPlaceholderEndToken = placeholderEndToken.length();
nullToken = DEFAULT_NULL;
}
public String getNullToken() {
return nullToken;
}
public void setNullToken(String defaultNull) {
this.nullToken = defaultNull;
}
public String getPlaceholderStartToken() {
return placeholderStartToken;
}
public void setPlaceholderStartToken(String placeholderStartToken) {
this.placeholderStartToken = placeholderStartToken;
lenPlaceholderStartToken = placeholderStartToken.length();
}
public String getPlaceholderEndToken() {
return placeholderEndToken;
}
public void setPlaceholderEndToken(String placeholderEndToken) {
this.placeholderEndToken = placeholderEndToken;
lenPlaceholderEndToken = placeholderEndToken.length();
}
public boolean isEscape() {
return escape;
}
public boolean getEscape() {
return escape;
}
public void setEscape(boolean escape) {
this.escape = escape;
}
public String getParam(String key, RenderContext... context) {
if(context != null)
{
for(RenderContext param:context)
{
if(param != null)
{
String value = param.getParameter(key);
if(!StringUtil.isEmpty(value))
{
return value;
}
}
}
}
return nullToken;
}
public String render(String s, RenderContext... context) {
// handle trivial cases of empty template or no placeholders
if (s == null)
{
Log4j.app.debug("Message is null in template. Cannot render null message.");
return nullToken;
}
if (context == null)
{
Log4j.app.debug("RenderContext is null. Cannot render message with null RenderContext.");
return nullToken;
}
if (s.indexOf(placeholderStartToken) < 0)
{
return s;
}
String msg = nullToken;
try
{
// private int renderTemplate(Renderable r, String src, StringBuffer dst, String nil, int i, String[] marks, StringBuffer end,boolean escapes)
msg = doRender(s, context);
}
catch (Exception e)
{
Log4j.app.error("Exception in rendering template: " + e.getMessage(), e);
return nullToken;
}
return msg;
}
protected abstract String doRender(String s, RenderContext... context);
}
MethodExpressionRenderer.java
public class MethodExpressionRenderer extends AbstractMessageRenderer {
private boolean inSingleQuote = false;
private boolean inDoubleQuote=false;
private int placeholders;
private Stack<String> methodStack;
private String[] endTokens;
private String marker;
private List<String> methodParams;
private String prefix = "&";
public MethodExpressionRenderer() {
super();
methodStack = new Stack<String>();
marker = ",";
endTokens = new String[] { placeholderEndToken, marker, "(", ")" };
methodParams = new ArrayList<String>();
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getMarker() {
return marker;
}
public void setMarker(String marker) {
this.marker = marker;
endTokens = new String[] { placeholderEndToken, marker };
}
#Override
public void setPlaceholderEndToken(String placeholderEndToken) {
super.setPlaceholderEndToken(placeholderEndToken);
endTokens = new String[] { placeholderEndToken, marker };
}
protected String doRender(String s, RenderContext... context) {
StringBuffer sb = new StringBuffer();
try
{
renderTemplate(s, sb, nullToken, 0, endTokens, null, context);
}
catch (Exception e)
{
Log4j.app.error("Exception in rendering method expression message emplate: " + e.getMessage(), e);
return nullToken;
}
return sb.toString();
}
private int renderTemplate(String src, StringBuffer dst, String nil, int i, String[] marks, StringBuffer end, RenderContext... context) {
int len = src.length();
while (i < len)
{
char c = src.charAt(i);
if (escape)
{
if (c=='\\')
{
i++;
char ch = src.charAt(i);
if(inSingleQuote)
{
if(ch=='\'')
{
inSingleQuote=false;
}
}
else if(inDoubleQuote)
{
if(ch=='"')
{
inDoubleQuote=false;
}
}
else
{
if(ch=='\'')
{
inSingleQuote=true;
}
else if(ch=='"')
{
inDoubleQuote=true;
}
}
dst.append(ch);
i++;
continue;
}
}
if(inSingleQuote)
{
if(c=='\'')
{
inSingleQuote=false;
}
}
else if(inDoubleQuote)
{
if(c=='"')
{
inDoubleQuote=false;
}
}
else
{
if(c=='\'')
{
inSingleQuote=true;
}
else if(c=='"')
{
inDoubleQuote=true;
}
}
// check for end marker
if (marks != null && !inSingleQuote && !inDoubleQuote)
{
for (int m = 0; m < marks.length; m++)
{
// If one of markers found
if (src.regionMatches(i, marks[m], 0, marks[m].length()))
{
// return marker if required
if (end != null)
{
end.append(marks[m]);
}
return i+marks[m].length();
}
}
}
// check for start of placeholder
if (src.regionMatches(i, placeholderStartToken, i, lenPlaceholderStartToken))
{
synchronized(this)
{
++placeholders;
}
i = renderPlaceholder(src, dst, nil, i, new ArrayList<String>(), context);
continue;
}
// just add plain character
if(c != '\'' && c!= '"')
{
dst.append(c);
}
i++;
}
return i;
}
private int renderPlaceholder(String src, StringBuffer dst, String nil, int i, List<String> params, RenderContext... context){
StringBuffer token = new StringBuffer(); // placeholder token
StringBuffer end = new StringBuffer(); // placeholder end marker
String value;
i = renderTemplate(src, token, nil, i+lenPlaceholderStartToken, endTokens, end);
String sToken = token.toString().trim();
String sEnd = end.toString().trim();
boolean isFunction = sEnd.equals("(");
// This is method name
if(isFunction && placeholders > methodStack.size())
{ // Method
synchronized(this)
{
methodStack.push(sToken); // put method into stack
}
}
else if(!isFunction && (methodStack.size()==0) && sEnd.equals(placeholderEndToken)) // Single template param such as <<param>>
{
value = getParam(sToken, context);
if(value != null)
{
if(value.trim().startsWith(placeholderStartToken))
{
value = render(src, context);
}
dst.append(value);
return i;
}
}
// TODO: Process method parameters to invoke
//.... ?????????
// Found end method token ')'
// Pop method out of stack to invoke
if ( (methodStack.size() >0) && (sEnd.length() == 0 || sEnd.equals(")")))
{
String method = null;
synchronized(this)
{
// Pop method out of stack to invoke
method = methodStack.pop();
--placeholders;
dst.append(invokeMethodEvaluator(method, methodParams.toArray(new String[0]), context));
methodParams.clear();
}
}
return i;
}
// Currently this method just implement to test so it just printout the method name
// and its parameter
// We can register MethodExpressionEvaluator to process
protected String invokeMethodEvaluator(String method, String[] params, RenderContext... context){
StringBuffer result = new StringBuffer();
result.append("[ ")
.append(method)
.append(" ( ");
if(params != null)
{
for(int i=0; i<params.length; i++)
{
result.append(params[i]);
if(i != params.length-1)
{
result.append(" , ");
}
}
}
result.append(" ) ")
.append(" ] ");
return result.toString();
}
}
We can easily register more method to the renderer to invoke. Each method will be an object and can be reused. But I'm in trouble how to resolve the nested method parameter. Can anyone give me an advice how we can process nested template of method parameter to invoke??? The line has TODO. Will my code in on the right way???
When you evaluate something like << count( << getTransId() >> ) >> you can either:
perform direct-evaluation as you parse, and push each function onto a stack, so that once you've evaluated getTransId() you pop the stack and use the return value (from the stack) as an argument for count(), or
you can build a parse tree to represent all the function calls that will be made, and then evaluate your parse tree after building it. (Building a tree probably doesn't buy you anything; since you're writing a template engine there is probably no high-level tree operation 'optimizations' that you could perform.)
An excellent little book I really enjoyed was Language Implementation Patterns by Parr. He walks through building simple to complex languages, and covers decisions like this in some depth. (Yes, he uses the ANTLR parser generator throughout, but your code looks like you're familiar enough with hand-generated parsers that different tools won't be a distraction for you.)
I found the bug and fixed it.
This is my new source:
// AbstractMethodExpressionRenderer.java
public class AbstractMethodExpressionRenderer extends AbstractMessageRenderer {
private boolean inSingleQuote = false;
private boolean inDoubleQuote=false;
private Stack<MethodExpressionDescriptor> functionStack;
private String[] endTokens;
private String marker;
private String prefix = "~";
public AbstractMethodExpressionRenderer() {
super();
functionStack = new Stack<MethodExpressionDescriptor>();
marker = ",";
endTokens = new String[] { placeholderEndToken, "(", ")", };
}
private class MethodExpressionDescriptor {
public List<String> params;
public String function;
public MethodExpressionDescriptor() {
params = new ArrayList<String>();
}
public MethodExpressionDescriptor(String name) {
this();
this.function = name;
}
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getMarker() {
return marker;
}
public void setMarker(String marker) {
this.marker = marker;
endTokens = new String[] { placeholderEndToken, marker };
}
#Override
public void setPlaceholderEndToken(String placeholderEndToken) {
super.setPlaceholderEndToken(placeholderEndToken);
endTokens = new String[] { placeholderEndToken, marker };
}
protected String doRender(String s, RenderContext... context) {
StringBuffer sb = new StringBuffer();
try
{
renderTemplate(s, sb, nullToken, 0, endTokens, null, context);
}
catch (Exception e)
{
Log4j.app.error("Exception in rendering method expression message emplate: " + e.getMessage(), e);
return nullToken;
}
return sb.toString();
}
private int renderTemplate(String src, StringBuffer dst, String nil, int i, String[] marks, StringBuffer end, RenderContext... context) {
int len = src.length();
while (i < len)
{
char c = src.charAt(i);
if (escape)
{
if (c=='\\')
{
i++;
char ch = src.charAt(i);
if(inSingleQuote)
{
if(ch=='\'')
{
inSingleQuote=false;
}
}
else if(inDoubleQuote)
{
if(ch=='"')
{
inDoubleQuote=false;
}
}
else
{
if(ch=='\'')
{
inSingleQuote=true;
}
else if(ch=='"')
{
inDoubleQuote=true;
}
}
dst.append(ch);
i++;
continue;
}
}
if(inSingleQuote)
{
if(c=='\'')
{
inSingleQuote=false;
}
}
else if(inDoubleQuote)
{
if(c=='"')
{
inDoubleQuote=false;
}
}
else
{
if(c=='\'')
{
inSingleQuote=true;
}
else if(c=='"')
{
inDoubleQuote=true;
}
}
// check for end marker
if (marks != null && !inSingleQuote && !inDoubleQuote)
{
for (int m = 0; m < marks.length; m++)
{
// If one of markers found
if (src.regionMatches(i, marks[m], 0, marks[m].length()))
{
// return marker if required
if (end != null)
{
end.append(marks[m]);
}
return i+marks[m].length();
}
}
}
// check for start of placeholder
if (src.regionMatches(i, placeholderStartToken, 0, lenPlaceholderStartToken))
{
i = renderPlaceholder(src, dst, nil, i, new ArrayList<String>(), context);
continue;
}
// just add plain character
if(c != '\'' && c!= '"')
{
dst.append(c);
}
i++;
}
return i;
}
/**
* Render a placeholder as follows:
*
* <<key>>: Simple render, key value map
* <<function(<<param1>>, <<param2>>)>> : Function object render
*
* #param src
* #param dst
* #param nil
* #param i
* #param params
* #param context
* #return
*/
private int renderPlaceholder(String src, StringBuffer dst, String nil, int i, List<String> params, RenderContext... context){
StringBuffer token = new StringBuffer(); // placeholder token
StringBuffer end = new StringBuffer(); // placeholder end marker
String value = null;
// Simple key
i = renderTemplate(src, token, nil, i+lenPlaceholderStartToken, endTokens, end, context);
String sToken = token.toString().trim();
String sEnd = end.toString().trim();
// This is method name
if(sEnd.equals("("))
{ // Method
functionStack.add(new MethodExpressionDescriptor(sToken));
}
else // Try to resolve value
{
if(sToken.startsWith(placeholderStartToken))
{
value = render(sToken, context);
}
else if(sToken.startsWith(prefix))
{
if(functionStack.size() > 0)
{
functionStack.peek().params.add(sToken.substring(1));
}
return i;
}
else
{
value = getParam(sToken, context);
}
}
if (sEnd.length() == 0 || sEnd.equals(placeholderEndToken))
{
// No method found but found the end of placeholder token
if(functionStack.size() == 0)
{
if(value != null)
{
dst.append(value);
}
else
{
dst.append(nil);
}
}
else
{
functionStack.peek().params.add(value);
}
}
else
{
if(value != null)
{
value = value.trim();
}
if(end.substring(0, 1).equals("(") ||
end.substring(0, 1).equals(marker))
{
// right hand side is remainder of placeholder
StringBuffer tmp = new StringBuffer();
end = new StringBuffer();
i = renderTemplate(src, tmp, nil, i, endTokens, end, context);
}
if(end.substring(0, 1).equals(")"))
{
if ( functionStack.size() > 0 )
{
// Pop method out of stack to invoke
MethodExpressionDescriptor descriptor = functionStack.pop();
if(functionStack.size() > 0 )
{
functionStack.peek().params.add(invokeMethodEvaluator(descriptor.function, descriptor.params.toArray(new String[0]), context));
}
else
{
dst.append(invokeMethodEvaluator(descriptor.function, descriptor.params.toArray(new String[0]), context));
}
end = new StringBuffer();
StringBuffer tmp = new StringBuffer();
i = renderTemplate(src, tmp, nil, i, endTokens, end, context);
}
}
}
return i;
}
protected String invokeMethodEvaluator(String method, String[] params, RenderContext... context){
StringBuffer result = new StringBuffer();
result.append("[ ")
.append(method)
.append(" ( ");
if(params != null)
{
for(int i=0; i<params.length; i++)
{
result.append(params[i]);
if(i != params.length-1)
{
result.append(" , ");
}
}
}
result.append(" ) ")
.append(" ] ");
return result.toString();
}
}
Hello
I am not able to get the correct validation.I think there is some error in this code so can anyone please help me solving this problem.
public static boolean validateFee(String value) {
boolean isvalid = true;
try {
int fee = 0;
if (value != null && !value.isEmpty()) {
fee = Integer.parseInt(value);
}
} catch (NumberFormatException ne) {
// ne.printStackTrace();
isvalid = false;
return isvalid;
}
return isvalid;
}
}
I am actaully using this code for validation of fee in which i m using a regex as [0-9]+.
This code i m using it in a common function.Actually validation call is done in the servlet as follows:
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
Boolean isvalid = true;
HashMap hashMap = new LinkedHashMap();
number = ApplicationConstants.FEE_PATTERN;
if (!Validation.validateFee(number)) {
isvalid = false;
hashMap.put("time", props.getText("error.fee.invalid.type"));
}
session.setAttribute("errorMessage", hashMap);
System.out.println("Map size " + hashMap.size());
logger.info("Exit validateTIme"); return isvalid;
}
I think there is no error in that but i have a doubt in this function.I am facing a problem like if i give number to the fee also its taking validation.please help me out
Currently it allows value of null or "" to count as being valid - is that deliberate?
Note that your current code can be rewritten more simply:
public static boolean validateFee(String value) {
try {
if (value != null && !value.isEmpty()) {
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException ne) {
return false;
}
}
Now if you want null/empty to count as invalid, I'd rewrite it as:
public static boolean validateFee(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException ne) {
return false;
}
}
trim your string and then pass it to.
StringUtils.isNumeric(StringUtils.trimToNull(fees));
You can directly use StringUtils.isNumeric()
I recommend you use commons-lang StringUtils class, your validate method is re-written
public static boolean validateFee(String value) {
return StringUtils.isNumeric(StringUtils.trimToNull(value));
}
And you remove ApplicationConstants.FEE_PATTERN completely. The problem you are currently facing is that your servlet overwrites its input value with ApplicationConstants.FEE_PATTERN. Your servlet method is re-written
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
final Boolean valid = Validation.validateFee(number);
if (!valid) {
final HashMap hashMap = new LinkedHashMap();
hashMap.put("time", props.getText("error.fee.invalid.type"));
session.setAttribute("errorMessage", hashMap);
}
}