Java tutorial
/* * Copyright (C) 2018 FormKiQ Inc. * * 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 com.formkiq.core.form.bean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Optional; import org.apache.commons.beanutils.ConvertUtilsBean; import com.formkiq.core.form.JSONService; import com.formkiq.core.util.Strings; /** * Custom {@link ConvertUtilsBean} with custom registered beans. * */ public class CustomConvertUtilsBean extends ConvertUtilsBean { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Object convert(final String value, final Class clazz) { if (clazz.isEnum()) { String val = Strings.extractLabelAndValue(value).getRight(); try { Method method = clazz.getMethod("find", String.class); Object result = method.invoke(method, val); if (result instanceof Optional) { Optional<Object> op = (Optional<Object>) result; if (op.isPresent()) { return op.get(); } } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // ignore error } return Enum.valueOf(clazz, val); } return super.convert(value, clazz); } @Override public String convert(final Object value) { if (value instanceof Timestamp) { SimpleDateFormat df = new SimpleDateFormat(JSONService.DEFAULT_DATE_FORMAT); return df.format((Timestamp) value); } return super.convert(value); } }