Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?
I currently have this:
#NotNull
#Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
#Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;
When I pass a value with letters I get a NumberFormatException before #Digits and #Min is executed. I also tried #Pattern with a regex value but that caused a 500 error.
"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
The answer is very short: no. That's because the validation is configured for the Integer year field. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to an Integer.
The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a MismatchedInputException.
An alternative is to change the field to a String. That allows you to use #Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.
Related
I have application which gives access token after authentication and I want to check if token is not expired
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String expires_in;
public boolean isNotExpired() {
return ! Instant.now().isBefore(Instant.parse(expires_in));
}
But after I run application I get errors:
JSON encoding error: Text '3600' could not be parsed at index 4; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Text '3600' could not be parsed at index 4 (through reference chain: com.Auth.AuthInfo["notExpired"])
How can I fix this?
Why do you keep the value of 3600 there instead of the actual date-time of the expiration?
It will easily solve your problem.
If you want to keep how long the token is valid you would also need the issue time of the token to check that the diff of current time - issue time is not greater than the value of a field like validFor.
I want to compare input String from Database in tMap component in Talend Open Studio. If my String is equal to "{}", I want to put there "nodata" string. Otherwise I leave the original input as it is.
My code in expression/filter in tMap:
(row1.parameter).equals("{}")?"nodata":row1.parameter
Error I'm getting:
Detail Message: Type mismatch: cannot convert from String to boolean
Do you have any suggestions?
Try to assign the result to a String variable, like
String someVariable = row1.parameter.equals("{}") ? "nodata" : row1.parameter;
because your expression returns a String… Are you assigning it to a Boolean? If yes, that will cause / be a type mismatch.
Assuming you're keeping the "Parameter" field, it sounds like your Output field that you are assigning 'Parameter' to is not a 'String' field, and is set as 'Boolean':
So the first point of call would be to check/change the output to a type of 'String':
Hello I am getting this error:
java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer
at this line of the code:
int est;
est=(Integer) session.getAttribute("estado");
I think that the problem is that "estado" is not filled yet. I use this session-attribubute in order to see if session has been signed in and so that it doesnt need to log in again.
You cannot type-cast here, as Integer is not compatible with String.
Use Integer#parseInt to parse it as an int
est = Integer.parseInt(session.getAttribute("estado"));
The session.getAttribute("estado"); returns the session attribute held in estado, What happened here that, the JVM has found (during runtime) the returned value's type is String so when you tried to cast it into Integer it fired a ClassCastException
What you need here is to parse the result returned by the attribute estado using Integer.parseInt(session.getAttribute("estado"));, which was suggested in the answers
NOTE: you maybe questioning that you have added an integer (not a String) to that attribute, but trace your code carefully considering that request.getParameter("attrName") returns a String, just an assumption
use Integer.parseInt
int est= Integer.parseInt(session.getAttribute("estado").toString());
I am using validation annotations to validate the Email field, Here the email field is not mandatory, Still when I click on submit, It is validating and throwing error message when the field is empty,
Here are the annotations:
#Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$",
message = "registration.label.useremailformat.invalidformat")
#Size(min = 6, max = 20, message = "registration.label.useremail.length")
#SafeHtml
private String userEmailId;
How can I skip #Pattern validation when the email field is empty and validate only when the value is given? Any help would be highly appreciated.
Modify your regexp to allow empty string and remove #Size:
#Pattern("^$|(<<old regexp>>)")
#SafeHtml
private String userEmailId;
... where <<old regex>> is a placeholder for your current lengthy regexp.
It seems that the problem is that the #Size restriction does not allow form submission even after making the whole regex pattern optional.
The workaround I suggest is moving the size restriction into the regex pattern:
regexp = "^(?:(?=.{6,20}$)[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,}))?$"
Where the outer (?:...)? encloses your pattern making it possible to match an empty string, and (?=.{6,20}$) is a positive lookahead that - before matching the pattern - checks if there are 6 to 20 characters in the text. If there are fewer or more, the match is failed.
The only disadvantage is that you can only display one error message with it.
I am using text fields for displaying column names . For showing the corresponding name of the column I have tried the following method:
Method 1:
textField.setX(currentXPos);
textField.setY(0);
textField.setWidth(columnWidth);
textField.setPrintWhenDetailOverflows(false);
textField.setHeight(colDtlBandHeight);
textField.setStretchWithOverflow(true);
textField.setStretchType(StretchTypeEnum.RELATIVE_TO_BAND_HEIGHT);
textField.setStyle(normalFont);
textField.setBlankWhenNull(true);
JRDesignExpression expression = new JRDesignExpression();
expression.setValueClass(columnClass);
expression.setText("$F{" + columnName + "}");
But on using the above method it throws an exception saying:
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. Syntax error on token "ID", delete this token
value = SHIFT ID; //$JR_EXPR_ID=44$
2. Syntax error, insert ";" to complete BlockStatements
value = BILL NO.; //$JR_EXPR_ID=45$
3. Syntax error on token ".", invalid VariableDeclarator
value = BILL NO.; //$JR_EXPR_ID=45$
4. Syntax error on token "DATE", delete this token
value = BILL DATE; //$JR_EXPR_ID=46$
But on using the below lines the column Names are set correctly .
Method 2:
textField.setExpression(new JRDesignExpression("new String(\""+colTitle+"\")"));
My doubts are:
1. For displaying the data the first method mentioned is used . Then how come there are no exceptions in that case ?
2. Why did it throw those exceptions when the same method was used for displaying column names?
3. How did the 2nd method work ?
1.:
I suppose the data is properly enclosed in quotes.
2.:
Judging by the exception explanation (e.g. Syntax error on token "ID", delete this token) the interpreter sees two values, SHIFT and ID. It seems here that quotes are missing, e.g.
"SHIFT ID"
"BILL NO."
3.:
In your first example, you create a JRDesignExpression, set the value class and set the text.
The field isn't enclosed in quotes as seen in your lower example. It should look like this:
expression.setText("\"$F{" + columnName + "}\"");
Also, you didn't assign the expression to your textField:
textField.setExpression(expression)