Commit 22502ff7 authored by Matija Obreza's avatar Matija Obreza

SelfCleaning trims strings to null

parent 8eb38716
......@@ -36,7 +36,7 @@ public interface Copyable<T> {
/**
* Make a deep copy of the object, with all new instances. Implementations
* should use {@link #apply(Object)} to apply this values to the new instance.
*
* Default implementation returns null.
* <pre>
* &#64;Override
* public Budget copy() {
......@@ -48,7 +48,9 @@ public interface Copyable<T> {
*
* @return a deep copy
*/
T copy();
default T copy() {
return null;
}
/**
* Apply values from source to this object. It should not handle lists, sets and
......
/*
* Copyright 2018 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.model;
import java.lang.reflect.Modifier;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldFilter;
/**
* Automatically trims all strings down to null on persist or merge.
*
* @author Matija Obreza
*/
public interface SelfCleaning {
default void trimStringsToNull() {
// System.err.println("Self-cleanup of " + this);
ReflectionUtils.doWithFields(this.getClass(), field -> {
if (Modifier.isPrivate(field.getModifiers()) || Modifier.isProtected(field.getModifiers()) || Modifier.isPublic(field.getModifiers())) {
ReflectionUtils.makeAccessible(field);
// System.err.println(field + " is made accessible, modifiers = " +
// field.getModifiers());
}
final String srcValue = (String) field.get(this);
if (srcValue != null) {
field.set(this, StringUtils.trimToNull(srcValue));
// System.err.println(field + " cleaned");
}
}, STRING_FIELDS);
}
/**
* FieldFilter that matches all non-static, non-final, strings fields.
*/
public static final FieldFilter STRING_FIELDS = field -> {
// is string, not static or final
return field.getType().equals(String.class) && !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
};
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment