Spring is converting String values to false for #queryparam Boolean - spring

I have this as queryparam in my requestmapping:
#QueryParam("isBenchmark") boolean isBenchmark
Now if am passing any String value also it is defaulting it to false. How can I avoid this and throw error if it is anything other than true/false.
Is there any annotations with which I can throw such validations

It is a known issue.
It is converted to boolean using the new Boolean(isBenchmark) So when isBenchmark is true it converts to true, in all other cases it converts to false.
Unfortunately you have to handle it by your self
public void YourMethod(#QueryParam("isBenchmark") String isBenchmark) {
boolean val
if (isBenchmark != null && isBenchmark.equals("true")){
val = true;
} else if (isBenchmark != null && isBenchmark.equals("false")) {
val = false;
} else {
Throw Exception or return a bad request
}
}

Related

rewrite if else null check using optionals

Is there a way to rewrite this using Optional and lambdas in a more succinct and clear way?
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm == null){
return false;
}else{
if(avgBuySellPriceTerm.getIndicator()!= null && ! avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}else{
return false;
}
}
}
Here's a suggestion with Optional:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.map(i -> !i.isEmpty()) // return true if getIndicator
// is not empty
.orElse(false);
}
The following should do it, using an Optional::ofNullable and the classic map, filter and isPresent methods
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.filter(ind -> !ind.isEmpty())
.isPresent();
}
!Optional.ofNullable(t)
.map(AvgBuySellPriceTerm::getIndicator)
.map(List::isEmpty)
.orElse(true);
Not sure this is more readable though.
Again, not using lambdas here but keeping it readable. The first if statement can be omitted, so it can all boil down to:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm != null && avgBuySellPriceTerm.getIndicator()!= null && !avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}
return false;
}

map has list as value check if null

I have a Map in Java 8.
I need to check if the list that comprises the map value is empty or null and return the result .
I have tried likewise with no luck
public boolean mapValuesEmpty() {
boolean result = true;
for (Entry<Integer, List<SomeObjectName>> entry : eventLogsMap.entrySet()) {
if (entry.getValue() != null) {
result = false;
break;
}
}
return result;
}
Many thanks
boolean result = eventLogsMap
.values()
.stream()
.anyMatch(list -> list != null && !list.isEmpty())

Boolean Method for ArrayList

I have created an ArrayList and I am looking to use a boolean method to add an element to the ArrayList.
private static Arraylist <Bicycle> bikelist = new Arraylist<Bicycle>();
public boolean add(Bicycle bicycle)
{
if( bikelist.size() != -1)
return true;
bikelist.add(bicycle);
}
return false;
Would this be plausible? I'm not quite sure how boolean methods work? Do they have to contain an if statement to return true or false?
Using: public boolean add(Object obj): Adds an element obj to the Arraylist. If the element is added successfully, this method returns true
Depends on what you want to return the boolean value for.
For whether the add operation succeeded: the only reason why adding an Object to an ArrayList would fail is due to an OutOfMemoryException AFAIK. Then you would do:
public boolean add(Object obj) {
try {
list.add(obj);
} catch (OutOfMemoryException e) {
return false;
}
return true;
}
If you want to return false if the list already contains the object, then:
public boolean add(Object obj) {
if (list.contains(obj)) {
return false;
}
list.add(obj);
return true;
}
Note that ArrayList<T>.contains(T) checks for object equality using Object.equals(Object). Thus you need to override equals() for your custom class.
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bicycle other = (Bicycle) obj;
if (other.owner != this.owner) {
return false;
}
if (this.model != other.model) {
return false;
}
return true;
}

Printing grails error messages with custom arguments

So I want to use the standard format for error messages. I don't want to specify other than default codes.
Example:
domain.property.minSize.notmet=I like purple {?}.
So I am looping through my errors:
domain.errors.fieldErrors.each {
println g.message(error: it, args: ['bunnies'])
}
This doesn't work correctly because I think the first x arguments are already defined because of the default error message, and that number changes depending on what the error is. How can I specify arguments to the standard error codes without struggling to know what number '?' should be?
So I've gone down this road, hopefully there isn't some way easier option. I am overriding the messageSource bean with my own implementation that simply adds a method:
public class MessageSource extends PluginAwareResourceBundleMessageSource implements GrailsApplicationAware, PluginManagerAware, InitializingBean {
public final String getMessage(MessageSourceResolvable resolvable, Object[] args, Locale locale)
throws NoSuchMessageException {
Object[] arguments;
if (args == null) {
arguments = resolvable.getArguments();
} else {
arguments = args;
}
String[] codes = resolvable.getCodes();
if (codes == null) {
codes = new String[0];
}
for (String code : codes) {
String msg = getMessageInternal(code, arguments, locale);
if (msg != null) {
return msg;
}
}
String defaultMessage = resolvable.getDefaultMessage();
if (defaultMessage != null) {
return renderDefaultMessage(defaultMessage, arguments, locale);
}
if (codes.length > 0) {
String fallback = getDefaultMessage(codes[0]);
if (fallback != null) {
return fallback;
}
}
throw new NoSuchMessageException(codes.length > 0 ? codes[codes.length - 1] : null, locale);
}
}
This is really almost an exact copy of one of the other methods, that I just modified to take in arguments. The problem I am having with this is that it never finds my error message, always falling back to default. msg is always null.
Edit: Just tried it with the standard method and the same is true with msg always being null.

What's "inside" the TextField

I have the following JavaFX code:
final TextField textField = new TextField();
and anEventHandler<ActionEvent>with checking textField wether it's empty or not. The problem is that textField.getText() == null or textField.getText() == "" both returns false, but i didn't print anything in that field, so it should return true.
final TextField textField = new TextField();
browse.setOnAction(new EventHandler() {
#Override
public void handle(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
File chFile = fileChooser.showOpenDialog(stage);
if (chFile != null) {
// some code
if (textField.getText() != null && textField.getText() != "") {
// some code
}
}
}
});
The textField.getText() returns a java String. Java String is an Object so you should use equals() method instead of == to compare Strings. == operator is used for comparing primitive types in Java. To understand this better, please look this How do I compare strings in Java? Q/A for string comparison in Java.
As I said you can use textField.getText().equals("") for checking the String emptiness but the common usage for it is:
if (textField.getText() != null && ! textField.getText().trim().isEmpty()) {
// some code
}
where ! is a boolean NOT operator. Also not the trim() method. This is for checking if the user entered whitespaces only then treat them as an empty value. Otherwise checking the whitespaces with equals("") will fail.
if(textfield.getText().trim().length>0)
//do Something
else
//can't be blank

Resources