TypeMismatch in PropertyEditorSupport - java

I'm afraid I don't fully understand how to use PropertyEditorSupport in Spring.
public class IntegerFormat extends PropertyEditorSupport
{
#Override
public void setAsText(String text) throws IllegalArgumentException
{
try
{
int v = Integer.parseInt(text);
super.setValue(v);
}
catch(Exception ex)
{
super.setValue(null); // TypeMismatch
}
}
}
In the code snippet above how am I supposed to indicate type mismatch occurred?
If I do setValue(null) type mismatch will be confused with the case in which the parameter is not provided at all.

There are two solutions
Ideally you should go for client side validation using JavaScript
Using typeMismatch.java.lang.Integer
Else you can go for server side spring validation
public static boolean isParsable(String input){ boolean parsable = true; try{ Integer.parseInt(input); }catch(NumberFormatException e){ parsable = false; } return parsable; }

Related

Need design suggestions for nested conditions

I need to write the logic with many conditions(up to 30 conditions) in one set of rule with many if else conditions and it could end in between or after all the conditions.
Here is the sample code I have tried with some possible scenario. This gives me result but doesn't look good and any minor miss in one condition would take forever to track.
What I have tried so far is, Take out common conditions and refactored to some methods. Tried creating interface with conditions and various set would implement it.
If you have any suggestion to design this, would help me. Not looking for detailed solution but even a hint would be great.
private Boolean RunCondition(Input input) {
Boolean ret=false;
//First if
if(input.a.equals("v1")){
//Somelogic1();
//Second if
if(input.b.equals("v2"))
//Third if
if(input.c >1)
//Fourth if
//Somelogic2();
//Go fetch key Z1 from database and see if d matches.
if(input.d.equals("Z1"))
System.out.println("Passed 1");
// Fourth Else
else{
System.out.println("Failed at fourth");
}
//Third Else
else{
if(input.aa.equals("v2"))
System.out.println("Failed at third");
}
//Second Else
else{
if(input.bb.equals("v2"))
System.out.println("Failed at second");
}
}
//First Else
else{
if(input.cc.equals("v2"))
System.out.println("Failed aat first");
}
return ret;
}
public class Input {
String a;
String b;
int c;
String d;
String e;
String aa;
String bb;
String cc;
String dd;
String ee;
}
The flow is complicated because you have a normal flow, plus many possible exception flows when some of the values are exceptional (e.g. invalid).
This is a perfect candidate to be handled using a try/catch/finally block.
Your program can be rewritten into following:
private Boolean RunCondition(Input input) {
Boolean ret=false;
try {
//First if
if(!input.a.equals("v1")) {
throw new ValidationException("Failed aat first");
}
//Somelogic1();
//Second if
if(!input.b.equals("v2")) {
throw new ValidationException("Failed at second");
}
//Somelogic2()
//Third if
if(input.c<=1) {
throw new ValidationException("Failed at third");
}
//Fourth if
//Somelogic2();
//Go fetch key Z1 from database and see if d matches.
if(!input.d.equals("Z1")) {
throw new ValidationException("Failed at fourth");
}
System.out.println("Passed 1");
} catch (ValidationException e) {
System.out.println(e.getMessage());
}
return ret;
}
Where you can define your own ValidationException (like below), or you can reuse some of the existing standard exception such as RuntimeException
class ValidationException extends RuntimeException {
public ValidationException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
You can read more about this in
https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
Make a separate class for the condition:
package com.foo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class App
{
static class Condition<T> {
final int idx;
final T compareValue;
public Condition(final int idx, final T compareValue) {
this.idx = idx;
this.compareValue = compareValue;
}
boolean satisfies(final T other) {
return other.equals(compareValue);
}
int getIdx() {
return idx;
}
}
public static void main( String[] args )
{
final List<Condition<String>> conditions = new ArrayList<Condition<String>>();
conditions.add(new Condition<String>(1, "v1"));
conditions.add(new Condition<String>(2, "v2"));
final List<String> inputs = new ArrayList<String>(Arrays.asList("v1", "xyz"));
boolean ret = true;
for (int i = 0; i < inputs.size(); i++) {
if (!conditions.get(i).satisfies(inputs.get(i)))
{
System.out.println("failed at " + conditions.get(i).getIdx());
ret = false;
break;
}
}
System.out.println("ret=" + ret);
}
}
#leeyuiwah's answer has a clear structure of the conditional logic, but exceptions aren't the right tool for the job here.
You shouldn't use exceptions to cope with non-exceptional conditions. For one thing, exceptions are really expensive to construct, because you have to walk all the way up the call stack to construct the stack trace; but you don't need the stack trace at all.
Check out Effective Java 2nd Ed Item 57: "Use exceptions only for exceptional conditions" for a detailed discussion of why you shouldn't use exceptions like this.
A simpler option is to define a little helper method:
private static boolean printAndReturnFalse(String message) {
System.out.println(message);
return false;
}
Then:
if(!input.a.equals("v1")) {
return printAndReturnFalse("Failed aat first");
}
// etc.
which I think is a simpler; and it'll be a lot faster.
Think of each rule check as an object, or as a Strategy that returns whether or not the rule passes. Each check should implement the same IRuleCheck interface and return a RuleCheckResult, which indicates if the check passed or the reason for failure.
public interface IRuleCheck
{
public RuleCheckResult Check(Input input);
public String Name();
}
public class RuleCheckResult
{
private String _errorMessage;
public RuleCheckResult(){}//All Good
public RuleCheckResult(String errorMessage)
{
_errorMessage = errorMessage;
}
public string ErrorMessage()
{
return _errorMessage;
}
public Boolean Passed()
{
return _errorMessage == null || _errorMessage.isEmpty();
}
}
public class CheckOne implements IRuleCheck
{
public RuleCheckResult Check(Input input)
{
if (input.d.equals("Z1"))
{
return new RuleCheckResult();//passed
}
return new RuleCheckResult("d did not equal z1");
}
public String Name();
}
Then you can simply build a list of rules and loop through them,
and either jump out when one fails, or compile a list of failures.
for (IRuleCheck check : checkList)
{
System.out.println("checking: " + check.Name());
RuleCheckResult result = check.Check(input);
if(!result.Passed())
{
System.out.println("FAILED: " + check.Name()+ " - " + result.ErrorMessage());
//either jump out and return result or add it to failure list to return later.
}
}
And the advantage of using the interface is that the checks can be as complicated or simple as necessary, and you can create arbitrary lists for checking any combination of rules in any order.

java getting concept of OOP right

hi guys I already searched a lot but weren't really satisfied with what I found. hope it's the right place to ask this question.
I'm doing Java now for a small amount of time (changed from C) and have problems of getting a grip of how to structure my code best for OOP.
let's give a simple example:
If I'm using some predefined strings (let's say e.g. filepaths or error messages) I'm currently creating an own class doing something like:
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
Would it be better to create a Map, add everything to it and get it by key?
Or am I doing it completely wrong?
Second example:
let's say I return an error string somewhere
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
And anywhere else in my program I'm checking for the return value:
if (!string.equals("I HAVE AN ERROR")) {
//do something
}
else {
// handle error
}
that's obviously a bad way having to change the code twice once the error message changes. and yeah, I could define the error string the same way I'm doing it in the first example but as I'm not satisfied with that one either I'm reaching a dead end.
would be glad to hear some of your suggestions how to properly do OOP !
First example :
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
In this case, no need to create a Map. That is the right way to do it. Just note that the libPath would be better defined like this :
private static final Path libPath = Paths.get("this", "is", "a", "path");
(The class Path exists since Java 7, current version is Java 8)
Second example:
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
No : Never return error codes in Java. Prefer using an exception.
Example :
public class ElementNotFoundException extends Exception {
...
}
public String getSomething() {
if (something == null) {
throw new ElementNotFoundException();
} else {
return something;
}
}
Then, you handle the exception like this :
try {
myObject.getSomething();
} catch(ElementNotFoundException e) {
//handle error
}
For the first example, take a look at Internationalization: http://docs.oracle.com/javase/tutorial/i18n/
You can use statics or maps, but sooner or later you will need to show the messages in several languages.
For the second example, it's better to use Exceptions as they are intended to be used when an abnormal condition (like an error) happens.
Anyway, with Exceptions take care not to use it as flow control structures: Why not use exceptions as regular flow of control?
Here are some examples for handling constants throug out your code:
1. Class
public final class MyConstants {
public static final int ERROR_CODE = -1;
}
if (getSomething() == MyConstants.ERROR_CODE) {
// ...
}
2. Interface
public interface MyConstantsHolder {
int ERROR_CODE = -1;
}
public MyClass implements MyConstantsHolder {
public void myMethod() {
if (getSomething() == ERROR_CODE) {
// ...
}
}
}

How would I write a test case in Java to test that the input is an int?

Would I do something like this?
Assert.assertTrue(value = int n);
Also, if I had a method such as:
public int get(){
return count;
}
What kind of a test case would I write for it? Would I write a test case testing if the return is an integer?
Regrading your first question - the return type is an int (so you don't need to verify that).
Regarding your second question, if it's just a getter, there's no need to write test for it.
Generally, unit test helps you to test bussiness logic and that a certain behavior of a building block of your app works.
If we'll take the count for example, you would probably want to build up a test case with actions that affects the count in a specific way and then assert on it's expected value.
You can look here for a nice tutorial on Unit Tests in Java.
Class for testing purpose:
public class Item {
private int number;
public Item(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
Your test cases could be:
import static org.junit.Assert.*;
public class Test {
#org.junit.Test
public void testCase1() {
Item item = new Item(1);
assertEquals(1, item.getNumber());
}
#org.junit.Test
public void testCase2() {
Item item = new Item(2);
assertEquals(2, item.getNumber());
}
}
You can verify your business logic via assertEquals method.
How would I write a test case in Java to test that the input is an int?
Assuming your concern is someone could change input type of a method.
public final void testSet() {
try {
MyClass.class.getDeclaredMethod("set", new Class[] { Integer.TYPE });
} catch (NoSuchMethodException e) {
Assert.assertFalse(true);
} catch (SecurityException e) {
e.printStackTrace();
}
}
Would I write a test case testing if the return is an integer?
Assuming your concern is someone could change return type of a method. By the way you are returning int in your example so I have used Integer.TYPE, if you want to check for Integer then use Integer.class
public final void testGet() {
try {
java.lang.reflect.Method m = MyClass.class.getDeclaredMethod("get", null);
Assert.assertTrue(m.getReturnType() == Integer.TYPE);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}

Applying a custom CharTokenizer in Solr4

I just wrote a custom CharTokenizer, and I want to use it in my Solr server.
In Solr3, I could just extend TokenizerFactory and return my CharTokenizer in the create method, but TokenizerFactory does not exist in Solr4.
So, I was noticed that I should replace TokenizerFactory with TokenFilterFactory, but in this case, I cannot return my custom CharTokenizer, because the parameters don't match.
I also search for some documentation, but looks like there is nothing really useful about that out there.
So, how can I make it works?
Example:
public class MyCustomTokenizer extends CharTokenizer {
char anotherSpace = 24;
public MyCustomTokenizer(Version matchVersion, Reader in) {
super(matchVersion, in);
}
protected boolean isTokenChar(int c) {
return !Character.isWhitespace(c) && isToken((char) c);
}
private boolean isToken(char c) {
if (c == anotherSpace || c == ',') {
return false;
}
return true;
}
}
public class MyCustomTokenizerFactory extends TokenFilterFactory {
public void init(Map<String, String> args) {
super.init(args);
assureMatchVersion();
}
#Override
public TokenStream create(TokenStream input) {
// sh*t happens here
return new MyCustomTokenizer(luceneMatchVersion, input);
}
}
Thanks in advance.
The best way to check for implementation is looking the Source code of an existing Tokenizer in Lucene.
Example :-
WhitespaceTokenizer
WhitespaceTokenizerFactory

Design API for taking xpath input from user

I want to design API which could handle XPATH input from user.
Currently i have model the XPATH input in following way,
public interface ICondition {
String getConditionString();
}
public class XPathCondition implements ICondition {
private Class<? extends XPATHFunction> clazz = null;
private Operator operator = null;
private String compValue = null;
private String param = null;
public void setXPathFunction(Class<? extends XPATHFunction> clazz) {
this.clazz = clazz;
}
public void setComparisionType(Operator operator) {
this.operator = operator;
}
public void setComparisionValue(String value) {
this.compValue = value;
}
public void setParam(String param) {
this.param = param;
}
public String getConditionString() {
XPATHFunction function = null;
try {
function = (XPATHFunction) clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return function.call(param) + operator.getOprValue() + compValue;
}
public static void main(String[] args) {
XPathCondition xpathCond = new XPathCondition();
xpathCond.setXPathFunction(CountFunction.class);
xpathCond.setParam("/CPRRegistrationInfo/*");
xpathCond.setComparisionType(Operator.GT);
xpathCond.setComparisionValue("0");
System.out.println(xpathCond.getConditionString());
}
}
public interface XPATHFunction {
public String call(String param);
}
public class CountFunction implements XPATHFunction {
public String call(String param) {
return "count(" + param + ") ";
}
}
There could be other XPATH function which have to implement and interface XPATHFunction and implement it in its way.
API just have create XPATHCondition and set appropriate function and call getConditionString() method to get the final xpath.
Is there any better way, we can model XPATH input?
Please help me to re factor the above design.
I don't think I cannot really comment on your class structure or suggest something different. It is a very tough problem.
What I'd suggest is:
Start with some simple sub-set of the full XPath syntax
Instead of starting from the design of the API and the classes start designing the user interface: what are you going to show the user? What are his/her possible actions? The class design should then derive from the UI design.
If possible use a schema for the underlying XML, so that you can present the user with a limited choice of the possible element and attribute name to use in the expression

Categories