de.cbb.mplayer.mapping.MappingUtil.java Source code

Java tutorial

Introduction

Here is the source code for de.cbb.mplayer.mapping.MappingUtil.java

Source

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.cbb.mplayer.mapping;

import java.lang.reflect.Field;
import javafx.scene.control.Control;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;

/**
 *
 * @author cbb
 */
@Slf4j
public class MappingUtil {

    public static void mapToEntity(Object presenter, Object entity) {
        for (Field field : presenter.getClass().getDeclaredFields()) {
            mapFieldToEntity(field, presenter, entity);
        }
    }

    public static void mapToPresenter(Object entity, Object presenter) {
        for (Field field : entity.getClass().getDeclaredFields()) {
            mapFieldToPresenter(field, entity, presenter);
        }
    }

    public static Object getAccessableControl(String fieldname, Object presenter) throws Exception {
        Field cbField = presenter.getClass().getDeclaredField(fieldname);
        cbField.setAccessible(true);
        Object control = cbField.get(presenter);
        return control;
    }

    private static void mapFieldToEntity(Field field, Object presenter, Object entity) {
        try {
            if (!Control.class.isAssignableFrom(field.getType()))
                return;
        } catch (Exception ex) {
            log.debug("mapFieldToEntity failed", ex);
        }
        try {
            String fieldname = field.getName();
            field.setAccessible(true);
            Object value1 = null;

            ValueWrapper wrapper = MappingFactory.buildValueWrapper(presenter, field, value1, entity, fieldname);
            if (wrapper == null)
                return;
            value1 = wrapper.getValue();

            PropertyUtils.setSimpleProperty(entity, fieldname, value1);
        } catch (Exception ex) {
            log.debug("Unmapped control: " + field.getName() + " [" + ex.toString() + "]");
        }
    }

    private static void mapFieldToPresenter(Field field, Object entity, Object presenter) {
        if (MappingFactory.EXCLUSIONS.contains(field.getName())) {
            return;
        }
        try {
            Object value1 = PropertyUtils.getSimpleProperty(entity, field.getName());
            String fieldname = field.getName();

            MappingFactory.buildMapper(presenter, fieldname, value1).map(value1);

        } catch (Exception ex) {
            log.debug("Unmapped attribute: " + field.getName() + " [" + ex.toString() + "]");
        }
    }

}