SelfCleaning.java

/*
 * 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 {

	/**
	 * Trim strings to null.
	 */
	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()));
	};
}