text:
package com.angkorteam.pluggable.framework.page;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.angkorteam.pluggable.framework.database.EntityMapper;
import com.angkorteam.pluggable.framework.mapper.GenericEntityMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.reflections.ReflectionUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.angkorteam.pluggable.framework.core.AbstractWebApplication;
import com.angkorteam.pluggable.framework.layout.AbstractLayout;
import com.angkorteam.pluggable.framework.panel.widget.WidgetCheckBox;
import com.angkorteam.pluggable.framework.panel.widget.WidgetCheckBoxMultipleChoice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetDateField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetDateTimeField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetDropDownChoice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetFileUploadField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetImageField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetLabelField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetListMultipleChoice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetMultiFileUploadField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetPasswordTextField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetRadioChoice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetSelect2Choice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetSelect2MultiChoice;
import com.angkorteam.pluggable.framework.panel.widget.WidgetTextArea;
import com.angkorteam.pluggable.framework.panel.widget.WidgetTextField;
import com.angkorteam.pluggable.framework.panel.widget.WidgetTimeField;
import com.angkorteam.pluggable.framework.utilities.SelectionUtilities;
import com.angkorteam.pluggable.framework.utilities.TableUtilities;
import com.angkorteam.pluggable.framework.validation.constraints.DecimalMax;
import com.angkorteam.pluggable.framework.validation.constraints.DecimalMin;
import com.angkorteam.pluggable.framework.validation.constraints.Digits;
import com.angkorteam.pluggable.framework.validation.constraints.Future;
import com.angkorteam.pluggable.framework.validation.constraints.Max;
import com.angkorteam.pluggable.framework.validation.constraints.Min;
import com.angkorteam.pluggable.framework.validation.constraints.NotNull;
import com.angkorteam.pluggable.framework.validation.constraints.Past;
import com.angkorteam.pluggable.framework.validation.constraints.Pattern;
import com.angkorteam.pluggable.framework.validation.constraints.Size;
import com.angkorteam.pluggable.framework.validation.constraints.Unique;
import com.angkorteam.pluggable.framework.validation.controller.ButtonController;
import com.angkorteam.pluggable.framework.validation.controller.ChoiceController;
import com.angkorteam.pluggable.framework.validation.controller.FieldController;
import com.angkorteam.pluggable.framework.validation.controller.Navigation;
import com.angkorteam.pluggable.framework.validation.type.Choice;
import com.angkorteam.pluggable.framework.validation.type.ChoiceType;
import com.angkorteam.pluggable.framework.validation.type.TextFieldType;
import com.angkorteam.pluggable.framework.wicket.markup.html.image.Image;
import com.angkorteam.pluggable.framework.widget.CheckBox;
import com.angkorteam.pluggable.framework.widget.CheckBoxMultipleChoice;
import com.angkorteam.pluggable.framework.widget.DropDownChoice;
import com.angkorteam.pluggable.framework.widget.FileUploadField;
import com.angkorteam.pluggable.framework.widget.ImageField;
import com.angkorteam.pluggable.framework.widget.LabelField;
import com.angkorteam.pluggable.framework.widget.ListMultipleChoice;
import com.angkorteam.pluggable.framework.widget.MultiFileUploadField;
import com.angkorteam.pluggable.framework.widget.RadioChoice;
import com.angkorteam.pluggable.framework.widget.Select2Choice;
import com.angkorteam.pluggable.framework.widget.Select2MultiChoice;
import com.angkorteam.pluggable.framework.widget.TextArea;
import com.angkorteam.pluggable.framework.widget.TextField;
import com.vaynberg.wicket.select2.ChoiceProvider;
import com.vaynberg.wicket.select2.DragAndDropBehavior;

/**
 * @author Socheat KHAUV
 */
public abstract class KnownPage extends WebPage {

    /**
     *
     */
    private static final long serialVersionUID = 4257287705775101884L;

    private Map<String, Object> model = new HashMap<String, Object>();

    private Map<String, ButtonController> buttonController = new HashMap<String, ButtonController>();

    private Map<String, FieldController> fieldController = new HashMap<String, FieldController>();

    private Map<String, Class<?>> fieldTypes = new HashMap<String, Class<?>>();

    private Map<String, Object> components = new HashMap<String, Object>();

    private Map<String, FormComponent<?>> buttons = new HashMap<String, FormComponent<?>>();

    private Form<Void> form;

    public KnownPage() {
        super();
        initializeInterceptor();
    }

    public Map<String, Object> getModel() {
        return model;
    }

    protected String getFormTitle() {
        return "";
    }

    public KnownPage(IModel<?> model) {
        super(model);
        initializeInterceptor();
    }

    protected Object getFormComponent(String name) {
        return this.components.get(name);
    }

    protected Form<?> getForm() {
        return this.form;
    }

    protected FormComponent<?> getFormButton(String name) {
        return this.buttons.get(name);
    }

    public KnownPage(PageParameters parameters) {
        super(parameters);
        initializeInterceptor();
    }

    private void prepareModel(String query) {
        String where = query.replace(" and ", "[||]");
        where = where.replace(" or ", "[||]");
        String[] criterias = StringUtils.split(where, "[||]");

        for (String criteria : criterias) {
            int b = criteria.indexOf(":");
            if (b > -1) {
                String tmp = criteria.substring(b + 1).trim();
                try {
                    this.model.put(tmp, FieldUtils.readField(this, tmp, true));
                } catch (IllegalArgumentException e) {
                } catch (IllegalAccessException e) {
                }
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void onInitialize() {
        super.onInitialize();

        for (Field field : ReflectionUtils.getAllFields(this.getClass())) {

            if (field.getAnnotation(Unique.class) != null) {
                Unique unique = field.getAnnotation(Unique.class);
                String where = unique.where();
                if (where != null && !"".equals(where)) {
                    prepareModel(where);
                }
            }

            if (field.getAnnotation(ImageField.class) != null) {
                ImageField imageField = field.getAnnotation(ImageField.class);
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        if (value instanceof String) {
                            model.put(field.getName(), value);
                        }
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(TextField.class) != null) {
                TextField textField = field.getAnnotation(TextField.class);
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        if (value instanceof String) {
                            model.put(field.getName(), value);
                        } else if (value instanceof Date) {
                            SimpleDateFormat format = new SimpleDateFormat(
                                    textField.pattern());
                            model.put(field.getName(),
                                    format.format((Date) value));
                        } else if (value instanceof Integer) {
                            model.put(field.getName(),
                                    String.valueOf((Integer) value));
                        } else if (value instanceof Byte) {
                            model.put(field.getName(),
                                    String.valueOf((Byte) value));
                        } else if (value instanceof Long) {
                            model.put(field.getName(),
                                    String.valueOf((Long) value));
                        } else if (value instanceof Short) {
                            model.put(field.getName(),
                                    String.valueOf((Short) value));
                        } else if (value instanceof Double) {
                            model.put(field.getName(),
                                    String.valueOf((Double) value));
                        } else if (value instanceof Float) {
                            model.put(field.getName(),
                                    String.valueOf((Float) value));
                        }
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(CheckBox.class) != null) {
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        if (value instanceof String) {
                            model.put(field.getName(),
                                    Boolean.valueOf((String) value));
                        } else if (value instanceof Boolean) {
                            model.put(field.getName(), value);
                        }
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(LabelField.class) != null) {
                try {
                    model.put(field.getName(),
                            FieldUtils.readField(field, this, true));
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(CheckBoxMultipleChoice.class) != null) {
                CheckBoxMultipleChoice checkBoxMultipleChoice = field
                        .getAnnotation(CheckBoxMultipleChoice.class);
                if (checkBoxMultipleChoice.where() != null
                        && !"".equals(checkBoxMultipleChoice.where())) {
                    prepareModel(checkBoxMultipleChoice.where());
                }

                if (checkBoxMultipleChoice.type() == ChoiceType.QUERY) {
                    org.apache.wicket.markup.html.form.CheckBoxMultipleChoice<Map<String, String>> component = (org.apache.wicket.markup.html.form.CheckBoxMultipleChoice<Map<String, String>>) this.components
                            .get(field.getName());
                    List<Map<String, String>> choices = (List<Map<String, String>>) component
                            .getChoices();

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
                    List<Map<String, String>> values = SelectionUtilities
                            .getSystemQueryChoices(jdbcTemplate, field
                                    .getType().getComponentType(),
                                    checkBoxMultipleChoice.display(),
                                    checkBoxMultipleChoice.where(), model,
                                    components);
                    if (values != null && !values.isEmpty()) {
                        for (Map<String, String> item : values) {
                            choices.add(item);
                        }
                    }
                }

                try {
                    Object object = FieldUtils.readField(field, this, true);
                    if (object != null) {
                        List<Map<String, String>> values = null;
                        if (checkBoxMultipleChoice.type() == ChoiceType.JAVA) {
                            if (object instanceof String[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (String[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Long[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Long[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof long[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (long[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Byte[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Byte[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof byte[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (byte[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Double[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Double[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof double[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (double[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Short[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Short[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof short[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (short[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Integer[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Integer[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof int[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (int[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof Float[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Float[]) object,
                                        checkBoxMultipleChoice.choices());
                            } else if (object instanceof float[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (float[]) object,
                                        checkBoxMultipleChoice.choices());
                            }
                        } else if (checkBoxMultipleChoice.type() == ChoiceType.QUERY) {
                            AbstractWebApplication application = (AbstractWebApplication) getApplication();
                            JdbcTemplate jdbcTemplate = application
                                    .getJdbcTemplate();
                            values = SelectionUtilities.getUserQueryChoices(
                                    jdbcTemplate, (Object[]) object,
                                    checkBoxMultipleChoice.display());
                        }
                        model.put(field.getName(), values);
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(ListMultipleChoice.class) != null) {
                ListMultipleChoice listMultipleChoice = field
                        .getAnnotation(ListMultipleChoice.class);
                if (listMultipleChoice.where() != null
                        && !"".equals(listMultipleChoice.where())) {
                    prepareModel(listMultipleChoice.where());
                }

                if (listMultipleChoice.type() == ChoiceType.QUERY) {
                    org.apache.wicket.markup.html.form.ListMultipleChoice<Map<String, String>> component = (org.apache.wicket.markup.html.form.ListMultipleChoice<Map<String, String>>) this.components
                            .get(field.getName());
                    List<Map<String, String>> choices = (List<Map<String, String>>) component
                            .getChoices();

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
                    List<Map<String, String>> values = SelectionUtilities
                            .getSystemQueryChoices(jdbcTemplate, field
                                    .getType().getComponentType(),
                                    listMultipleChoice.display(),
                                    listMultipleChoice.where(), model,
                                    components);
                    if (values != null && !values.isEmpty()) {
                        for (Map<String, String> item : values) {
                            choices.add(item);
                        }
                    }
                }

                try {
                    Object object = FieldUtils.readField(field, this, true);
                    if (object != null) {
                        List<Map<String, String>> values = null;
                        if (listMultipleChoice.type() == ChoiceType.JAVA) {
                            if (object instanceof String[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (String[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Long[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Long[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof long[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (long[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Byte[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Byte[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof byte[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (byte[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Double[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Double[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof double[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (double[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Short[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Short[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof short[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (short[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Integer[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Integer[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof int[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (int[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof Float[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (Float[]) object,
                                        listMultipleChoice.choices());
                            } else if (object instanceof float[]) {
                                values = SelectionUtilities.getUserJavaChoices(
                                        (float[]) object,
                                        listMultipleChoice.choices());
                            }
                        } else if (listMultipleChoice.type() == ChoiceType.QUERY) {
                            AbstractWebApplication application = (AbstractWebApplication) getApplication();
                            JdbcTemplate jdbcTemplate = application
                                    .getJdbcTemplate();
                            values = SelectionUtilities.getUserQueryChoices(
                                    jdbcTemplate, (Object[]) object,
                                    listMultipleChoice.display());
                        }
                        model.put(field.getName(), values);
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(RadioChoice.class) != null) {
                RadioChoice radioChoice = field
                        .getAnnotation(RadioChoice.class);
                if (radioChoice.where() != null
                        && !"".equals(radioChoice.where())) {
                    prepareModel(radioChoice.where());
                }

                if (radioChoice.type() == ChoiceType.QUERY) {
                    org.apache.wicket.markup.html.form.RadioChoice<Map<String, String>> component = (org.apache.wicket.markup.html.form.RadioChoice<Map<String, String>>) this.components
                            .get(field.getName());
                    List<Map<String, String>> choices = (List<Map<String, String>>) component
                            .getChoices();

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
                    List<Map<String, String>> values = SelectionUtilities
                            .getSystemQueryChoices(jdbcTemplate,
                                    field.getType(), radioChoice.display(),
                                    radioChoice.where(), model, components);
                    if (values != null && !values.isEmpty()) {
                        for (Map<String, String> item : values) {
                            choices.add(item);
                        }
                    }
                }

                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        Map<String, String> values = null;
                        if (radioChoice.type() == ChoiceType.JAVA) {
                            if (value instanceof String) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (String) value, radioChoice.choices());
                            } else if (value instanceof Integer) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Integer) value, radioChoice.choices());
                            } else if (value instanceof Byte) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Byte) value, radioChoice.choices());
                            } else if (value instanceof Long) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Long) value, radioChoice.choices());
                            } else if (value instanceof Short) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Short) value, radioChoice.choices());
                            } else if (value instanceof Double) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Double) value, radioChoice.choices());
                            } else if (value instanceof Float) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Float) value, radioChoice.choices());
                            }
                        } else if (radioChoice.type() == ChoiceType.QUERY) {
                            AbstractWebApplication application = (AbstractWebApplication) getApplication();
                            JdbcTemplate jdbcTemplate = application
                                    .getJdbcTemplate();
                            values = SelectionUtilities.getUserQueryChoice(
                                    jdbcTemplate, value, radioChoice.display());
                        }
                        model.put(field.getName(), values);
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(DropDownChoice.class) != null) {
                DropDownChoice dropDownChoice = field
                        .getAnnotation(DropDownChoice.class);
                if (dropDownChoice.where() != null
                        && !"".equals(dropDownChoice.where())) {
                    prepareModel(dropDownChoice.where());
                }
                if (dropDownChoice.type() == ChoiceType.QUERY) {
                    org.apache.wicket.markup.html.form.DropDownChoice<Map<String, String>> component = (org.apache.wicket.markup.html.form.DropDownChoice<Map<String, String>>) this.components
                            .get(field.getName());
                    List<Map<String, String>> choices = (List<Map<String, String>>) component
                            .getChoices();

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
                    List<Map<String, String>> values = SelectionUtilities
                            .getSystemQueryChoices(jdbcTemplate,
                                    field.getType(), dropDownChoice.display(),
                                    dropDownChoice.where(), model, components);
                    if (values != null && !values.isEmpty()) {
                        for (Map<String, String> item : values) {
                            choices.add(item);
                        }
                    }
                }
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        Map<String, String> values = null;
                        if (dropDownChoice.type() == ChoiceType.JAVA) {
                            if (value instanceof String) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (String) value,
                                        dropDownChoice.choices());
                            } else if (value instanceof Integer) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Integer) value,
                                        dropDownChoice.choices());
                            } else if (value instanceof Byte) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Byte) value, dropDownChoice.choices());
                            } else if (value instanceof Long) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Long) value, dropDownChoice.choices());
                            } else if (value instanceof Short) {
                                values = SelectionUtilities
                                        .getUserJavaChoice((Short) value,
                                                dropDownChoice.choices());
                            } else if (value instanceof Double) {
                                values = SelectionUtilities.getUserJavaChoice(
                                        (Double) value,
                                        dropDownChoice.choices());
                            } else if (value instanceof Float) {
                                values = SelectionUtilities
                                        .getUserJavaChoice((Float) value,
                                                dropDownChoice.choices());
                            }
                        } else if (dropDownChoice.type() == ChoiceType.QUERY) {
                            AbstractWebApplication application = (AbstractWebApplication) getApplication();
                            JdbcTemplate jdbcTemplate = application
                                    .getJdbcTemplate();
                            values = SelectionUtilities.getUserQueryChoice(
                                    jdbcTemplate, value,
                                    dropDownChoice.display());
                        }
                        model.put(field.getName(), values);
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(TextArea.class) != null) {
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        if (value instanceof String) {
                            model.put(field.getName(), value);
                        }
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(Select2MultiChoice.class) != null) {
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    if (value != null) {
                        Object[] values = (Object[]) value;
                        model.put(field.getName(),
                                new ArrayList<Object>(Arrays.asList(values)));
                    }
                } catch (IllegalAccessException e) {
                }
            } else if (field.getAnnotation(Select2Choice.class) != null) {
                try {
                    Object value = FieldUtils.readField(field, this, true);
                    model.put(field.getName(), value);
                } catch (IllegalAccessException e) {
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    private void initializeInterceptor() {
        AbstractLayout layout = requestLayout("layout");
        add(layout);

        Fragment fragment = null;

        if (getFormTitle() == null || "".equals(getFormTitle())) {
            fragment = new Fragment("fragment", "formFragment", this);
        } else {
            fragment = new Fragment("fragment", "labelFormFragment", this);
            Label formTitle = new Label("formTitle", getFormTitle());
            fragment.add(formTitle);
        }

        form = new Form<Void>("form");
        // form.setOutputMarkupPlaceholderTag(true);
        fragment.add(form);

        layout.add(fragment);

        List<FieldController> fields = new ArrayList<FieldController>();
        for (Field field : ReflectionUtils.getAllFields(this.getClass())) {
            FieldController widget = null;
            if (field.getAnnotation(ImageField.class) != null) {
                widget = new FieldController();
                ImageField imageField = field.getAnnotation(ImageField.class);
                widget.setOrder(imageField.order());
                widget.setImageField(imageField);
                Image component = new Image("field", new PropertyModel<String>(
                        model, field.getName()));
                components.put(field.getName(), component);
            } else if (field.getAnnotation(TextField.class) != null) {
                widget = new FieldController();
                TextField textField = field.getAnnotation(TextField.class);
                widget.setTextField(textField);
                widget.setOrder(textField.order());

                if (textField.type() == TextFieldType.PASSWORD) {
                    org.apache.wicket.markup.html.form.TextField<String> component = new PasswordTextField(
                            "field", new PropertyModel<String>(model,
                                    field.getName()));
                    component.setType(String.class);
                    components.put(field.getName(), component);
                } else {
                    org.apache.wicket.markup.html.form.TextField<String> component = new org.apache.wicket.markup.html.form.TextField<String>(
                            "field", new PropertyModel<String>(model,
                                    field.getName()));
                    component.setType(String.class);
                    components.put(field.getName(), component);
                }
            } else if (field.getAnnotation(LabelField.class) != null) {
                widget = new FieldController();
                LabelField labelField = field.getAnnotation(LabelField.class);
                widget.setLabelField(labelField);
                widget.setOrder(labelField.order());

                Label component = new Label("field", "");
                components.put(field.getName(), component);
            } else if (field.getAnnotation(CheckBox.class) != null) {
                widget = new FieldController();
                CheckBox checkBox = field.getAnnotation(CheckBox.class);
                widget.setCheckBox(checkBox);
                widget.setOrder(checkBox.order());

                org.apache.wicket.markup.html.form.CheckBox component = new org.apache.wicket.markup.html.form.CheckBox(
                        "field", new PropertyModel<Boolean>(model,
                                field.getName()));
                components.put(field.getName(), component);
            } else if (field.getAnnotation(CheckBoxMultipleChoice.class) != null) {
                widget = new FieldController();
                CheckBoxMultipleChoice checkBoxMultipleChoice = field
                        .getAnnotation(CheckBoxMultipleChoice.class);
                widget.setCheckBoxMultipleChoice(checkBoxMultipleChoice);
                widget.setOrder(checkBoxMultipleChoice.order());

                List<Map<String, String>> values = null;
                if (widget.getCheckBoxMultipleChoice().type() == ChoiceType.JAVA) {
                    Choice[] choices = widget.getCheckBoxMultipleChoice()
                            .choices();
                    if (choices != null && choices.length > 0) {
                        values = SelectionUtilities.getSystemJavaChoices(widget
                                .getCheckBoxMultipleChoice().choices());
                    }
                } else if (widget.getCheckBoxMultipleChoice().type() == ChoiceType.QUERY) {
                    values = new ArrayList<Map<String, String>>();
                }
                org.apache.wicket.markup.html.form.CheckBoxMultipleChoice<Map<String, String>> component = new org.apache.wicket.markup.html.form.CheckBoxMultipleChoice<Map<String, String>>(
                        "field", new PropertyModel<List<Map<String, String>>>(
                                model, field.getName()), values,
                        new ChoiceController());
                components.put(field.getName(), component);
            } else if (field.getAnnotation(ListMultipleChoice.class) != null) {
                widget = new FieldController();
                ListMultipleChoice listMultipleChoice = field
                        .getAnnotation(ListMultipleChoice.class);
                widget.setListMultipleChoice(listMultipleChoice);
                widget.setOrder(listMultipleChoice.order());

                List<Map<String, String>> values = null;
                if (widget.getListMultipleChoice().type() == ChoiceType.JAVA) {
                    Choice[] choices = widget.getListMultipleChoice().choices();
                    if (choices != null && choices.length > 0) {
                        values = SelectionUtilities.getSystemJavaChoices(widget
                                .getListMultipleChoice().choices());
                    }
                } else if (widget.getListMultipleChoice().type() == ChoiceType.QUERY) {
                    values = new ArrayList<Map<String, String>>();
                }
                org.apache.wicket.markup.html.form.ListMultipleChoice<Map<String, String>> component = new org.apache.wicket.markup.html.form.ListMultipleChoice<Map<String, String>>(
                        "field", new PropertyModel<List<Map<String, String>>>(
                                model, field.getName()), values,
                        new ChoiceController());
                components.put(field.getName(), component);
            } else if (field.getAnnotation(FileUploadField.class) != null) {
                widget = new FieldController();
                FileUploadField fileUploadField = field
                        .getAnnotation(FileUploadField.class);
                widget.setFileUploadField(fileUploadField);
                widget.setOrder(fileUploadField.order());

                org.apache.wicket.markup.html.form.upload.FileUploadField component = new org.apache.wicket.markup.html.form.upload.FileUploadField(
                        "field", new PropertyModel<List<FileUpload>>(model,
                                field.getName()));
                components.put(field.getName(), component);
            } else if (field.getAnnotation(MultiFileUploadField.class) != null) {
                widget = new FieldController();
                MultiFileUploadField multiFileUploadField = field
                        .getAnnotation(MultiFileUploadField.class);
                widget.setMultiFileUploadField(multiFileUploadField);
                widget.setOrder(multiFileUploadField.order());

                model.put(field.getName(), new ArrayList<FileUpload>());
                org.apache.wicket.markup.html.form.upload.MultiFileUploadField component = new org.apache.wicket.markup.html.form.upload.MultiFileUploadField(
                        "field", new PropertyModel<List<FileUpload>>(model,
                                field.getName()));
                components.put(field.getName(), component);
            } else if (field.getAnnotation(RadioChoice.class) != null) {
                widget = new FieldController();
                RadioChoice radioChoice = field
                        .getAnnotation(RadioChoice.class);
                widget.setRadioChoice(radioChoice);
                widget.setOrder(radioChoice.order());

                List<Map<String, String>> values = null;
                if (widget.getRadioChoice().type() == ChoiceType.JAVA) {
                    Choice[] choices = widget.getRadioChoice().choices();
                    if (choices != null && choices.length > 0) {
                        values = SelectionUtilities.getSystemJavaChoices(widget
                                .getRadioChoice().choices());
                    }
                } else if (widget.getRadioChoice().type() == ChoiceType.QUERY) {
                    values = new ArrayList<Map<String, String>>();
                }
                org.apache.wicket.markup.html.form.RadioChoice<Map<String, String>> component = new org.apache.wicket.markup.html.form.RadioChoice<Map<String, String>>(
                        "field", new PropertyModel<Map<String, String>>(model,
                                field.getName()), values,
                        new ChoiceController());
                components.put(field.getName(), component);
            } else if (field.getAnnotation(DropDownChoice.class) != null) {
                widget = new FieldController();
                DropDownChoice dropDownChoice = field
                        .getAnnotation(DropDownChoice.class);
                widget.setDropDownChoice(dropDownChoice);
                widget.setOrder(dropDownChoice.order());

                List<Map<String, String>> values = null;
                if (widget.getDropDownChoice().type() == ChoiceType.JAVA) {
                    Choice[] choices = widget.getDropDownChoice().choices();
                    if (choices != null && choices.length > 0) {
                        values = SelectionUtilities.getSystemJavaChoices(widget
                                .getDropDownChoice().choices());
                    }
                } else if (widget.getDropDownChoice().type() == ChoiceType.QUERY) {
                    values = new ArrayList<Map<String, String>>();
                }

                org.apache.wicket.markup.html.form.DropDownChoice<Map<String, String>> component = new org.apache.wicket.markup.html.form.DropDownChoice<Map<String, String>>(
                        "field", new PropertyModel<Map<String, String>>(model,
                                field.getName()), values,
                        new ChoiceController());
                components.put(field.getName(), component);
            } else if (field.getAnnotation(TextArea.class) != null) {
                widget = new FieldController();
                TextArea textArea = field.getAnnotation(TextArea.class);
                widget.setTextArea(textArea);
                widget.setOrder(textArea.order());

                org.apache.wicket.markup.html.form.TextArea<String> component = new org.apache.wicket.markup.html.form.TextArea<String>(
                        "field", new PropertyModel<String>(model,
                                field.getName()));
                component.setType(String.class);
                components.put(field.getName(), component);
            } else if (field.getAnnotation(Select2MultiChoice.class) != null) {
                widget = new FieldController();
                Select2MultiChoice select2MultiChoice = field
                        .getAnnotation(Select2MultiChoice.class);
                widget.setSelect2MultiChoice(select2MultiChoice);
                widget.setOrder(select2MultiChoice.order());

                ChoiceProvider<Serializable> provider = null;
                try {
                    provider = (ChoiceProvider<Serializable>) select2MultiChoice
                            .provider().newInstance();
                } catch (InstantiationException e) {
                } catch (IllegalAccessException e) {
                }

                com.vaynberg.wicket.select2.Select2MultiChoice<Serializable> component = new com.vaynberg.wicket.select2.Select2MultiChoice<Serializable>(
                        "field", new PropertyModel<Collection<Serializable>>(
                                model, field.getName()), provider);
                component.setType(field.getType());
                component.getSettings().setMinimumInputLength(
                        select2MultiChoice.minimumInputLength());
                component.add(new DragAndDropBehavior());
                components.put(field.getName(), component);
            } else if (field.getAnnotation(Select2Choice.class) != null) {
                widget = new FieldController();
                Select2Choice select2Choice = field
                        .getAnnotation(Select2Choice.class);
                widget.setSelect2Choice(select2Choice);
                widget.setOrder(select2Choice.order());

                ChoiceProvider<Serializable> provider = null;
                try {
                    provider = (ChoiceProvider<Serializable>) select2Choice
                            .provider().newInstance();
                } catch (InstantiationException e) {
                } catch (IllegalAccessException e) {
                }

                com.vaynberg.wicket.select2.Select2Choice<Serializable> component = new com.vaynberg.wicket.select2.Select2Choice<Serializable>(
                        "field", new PropertyModel<Serializable>(model,
                                field.getName()), provider);
                component.setType(field.getType());
                component.getSettings().setMinimumInputLength(
                        select2Choice.minimumInputLength());
                component.add(new DragAndDropBehavior());
                components.put(field.getName(), component);
            }

            if (widget != null) {
                Component component = (Component) components.get(field
                        .getName());
                // component.setOutputMarkupPlaceholderTag(true);
                this.fieldTypes.put(field.getName(), field.getType());
                this.fieldController.put(field.getName(), widget);
                if (field.getType().isArray()) {
                    widget.setElementType(field.getType().getComponentType());
                }
                widget.setType(field.getType());
                widget.setName(field.getName());
                widget.setPast(field.getAnnotation(Past.class));
                widget.setUnique(field.getAnnotation(Unique.class));
                widget.setDigits(field.getAnnotation(Digits.class));
                widget.setDecimalMax(field.getAnnotation(DecimalMax.class));
                widget.setDecimalMin(field.getAnnotation(DecimalMin.class));
                widget.setFuture(field.getAnnotation(Future.class));
                widget.setSize(field.getAnnotation(Size.class));
                widget.setNotNull(field.getAnnotation(NotNull.class));
                widget.setMin(field.getAnnotation(Min.class));
                widget.setMax(field.getAnnotation(Max.class));
                widget.setPattern(field.getAnnotation(Pattern.class));
                fields.add(widget);
            }
        }

        Collections.sort(fields);

        ListView<FieldController> widgetListView = new ListView<FieldController>(
                "fields", fields) {

            /**
             *
             */
            private static final long serialVersionUID = 8700106567169972527L;

            @Override
            protected void populateItem(ListItem<FieldController> item) {
                // item.setOutputMarkupPlaceholderTag(true);
                FieldController widget = item.getModelObject();
                if (widget.getTextField() != null) {
                    TextFieldType widgetType = widget.getTextField().type();
                    if (widgetType == TextFieldType.EMAIL
                            || widgetType == TextFieldType.NUMBER
                            || widgetType == TextFieldType.REGX
                            || widgetType == TextFieldType.TEXT
                            || widgetType == TextFieldType.URL) {
                        WidgetTextField widgetTextField = new WidgetTextField(
                                "field", model, widget, components, form);
                        // widgetTextField.setOutputMarkupPlaceholderTag(true);
                        item.add(widgetTextField);
                    } else if (widgetType == TextFieldType.DATETIME) {
                        WidgetDateTimeField widgetDateTimeField = new WidgetDateTimeField(
                                "field", model, widget, components);
                        item.add(widgetDateTimeField);
                    } else if (widgetType == TextFieldType.DATE) {
                        WidgetDateField widgetDateField = new WidgetDateField(
                                "field", model, widget, components);
                        item.add(widgetDateField);
                    } else if (widgetType == TextFieldType.TIME) {
                        WidgetTimeField widgetTimeField = new WidgetTimeField(
                                "field", model, widget, components);
                        item.add(widgetTimeField);
                    } else if (widgetType == TextFieldType.PASSWORD) {
                        WidgetPasswordTextField widgetPasswordTextField = new WidgetPasswordTextField(
                                "field", model, widget, components, form);
                        item.add(widgetPasswordTextField);
                    }
                }
                if (widget.getLabelField() != null) {
                    WidgetLabelField widgetLabelField = new WidgetLabelField(
                            "field", model, widget, components);
                    item.add(widgetLabelField);
                }
                if (widget.getImageField() != null) {
                    WidgetImageField widgetImageField = new WidgetImageField(
                            "field", model, widget, components);
                    item.add(widgetImageField);
                }
                if (widget.getCheckBox() != null) {
                    WidgetCheckBox widgetCheckBox = new WidgetCheckBox("field",
                            model, widget, components);
                    item.add(widgetCheckBox);
                }
                if (widget.getCheckBoxMultipleChoice() != null) {
                    WidgetCheckBoxMultipleChoice widgetCheckBoxMultipleChoice = new WidgetCheckBoxMultipleChoice(
                            "field", model, widget, components);
                    item.add(widgetCheckBoxMultipleChoice);
                }
                if (widget.getListMultipleChoice() != null) {
                    WidgetListMultipleChoice widgetListMultipleChoice = new WidgetListMultipleChoice(
                            "field", model, widget, components);
                    item.add(widgetListMultipleChoice);
                }
                if (widget.getFileUploadField() != null) {
                    WidgetFileUploadField widgetFileUploadField = new WidgetFileUploadField(
                            "field", model, widget, components);
                    item.add(widgetFileUploadField);
                }
                if (widget.getMultiFileUploadField() != null) {
                    WidgetMultiFileUploadField widgetMultiFileUploadField = new WidgetMultiFileUploadField(
                            "field", model, widget, components);
                    item.add(widgetMultiFileUploadField);
                }
                if (widget.getRadioChoice() != null) {
                    WidgetRadioChoice widgetRadioChoice = new WidgetRadioChoice(
                            "field", model, widget, components);
                    item.add(widgetRadioChoice);
                }
                if (widget.getDropDownChoice() != null) {
                    WidgetDropDownChoice widgetDropDownChoice = new WidgetDropDownChoice(
                            "field", model, widget, components);
                    item.add(widgetDropDownChoice);
                }
                if (widget.getTextArea() != null) {
                    WidgetTextArea widgetTextArea = new WidgetTextArea("field",
                            model, widget, components);
                    item.add(widgetTextArea);
                }
                if (widget.getSelect2MultiChoice() != null) {
                    WidgetSelect2MultiChoice widgetSelect2MultiChoice = new WidgetSelect2MultiChoice(
                            "field", model, widget, components);
                    item.add(widgetSelect2MultiChoice);
                }
                if (widget.getSelect2Choice() != null) {
                    WidgetSelect2Choice widgetSelect2Choice = new WidgetSelect2Choice(
                            "field", model, widget, components);
                    item.add(widgetSelect2Choice);
                }
            }
        };

        // widgetListView.setOutputMarkupPlaceholderTag(true);

        form.add(widgetListView);
        widgetListView.setReuseItems(true);

        List<ButtonController> commands = new ArrayList<ButtonController>();
        for (Method method : ReflectionUtils.getAllMethods(this.getClass())) {
            if (method
                    .getAnnotation(com.angkorteam.pluggable.framework.widget.Button.class) != null) {
                com.angkorteam.pluggable.framework.widget.Button widget = method
                        .getAnnotation(com.angkorteam.pluggable.framework.widget.Button.class);
                ButtonController command = new ButtonController();
                command.setName(method.getName());
                command.setButton(widget);
                command.setOrder(widget.order());
                commands.add(command);

                Button button = new Button("button", new Model<String>(
                        command.getName())) {

                    /**
                     *
                     */
                    private static final long serialVersionUID = -8528703498437930841L;

                    @Override
                    public void onSubmit() {
                        String name = (String) getDefaultModelObject();
                        transfer();
                        buttonClick(name);
                    }

                    @Override
                    public void onError() {
                        String name = (String) getDefaultModelObject();
                        try {
                            Method method = Form.class
                                    .getDeclaredMethod("updateFormComponentModels");
                            method.setAccessible(true);
                            method.invoke(getForm());
                        } catch (SecurityException e) {
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalArgumentException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                        if (!KnownPage.this.buttonController.get(name)
                                .getButton().validate()) {
                            buttonClick(name);
                        }
                    }
                };
                this.buttons.put(method.getName(), button);

                this.buttonController.put(method.getName(), command);
            }
        }

        Collections.sort(commands);

        ListView<ButtonController> commandListView = new ListView<ButtonController>(
                "buttons", commands) {

            /**
             *
             */
            private static final long serialVersionUID = 2265771875020994354L;

            @Override
            protected void populateItem(ListItem<ButtonController> item) {
                ButtonController command = item.getModelObject();
                Button button = (Button) buttons.get(command.getName());

                item.add(button);
                if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.DEFAULT) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-default"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.PRIMARY) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-primary"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.SUCCESS) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-success"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.INFO) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-info"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.WARNING) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-warning"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.DANGER) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-danger"));
                } else if (command.getButton().type() == com.angkorteam.pluggable.framework.validation.type.ButtonType.LINK) {
                    button.add(AttributeModifier.replace("class",
                            "btn btn-link"));
                }

                Label label = new Label("label", command.getButton().label());
                button.add(label);
            }
        };
        form.add(commandListView);
        commandListView.setReuseItems(true);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected void transfer() {

        for (Field field : ReflectionUtils.getAllFields(this.getClass())) {
            Class<?> fieldType = this.fieldTypes.get(field.getName());
            if (field.getAnnotation(CheckBox.class) != null) {
                if (model.get(field.getName()) == null) {
                    try {
                        FieldUtils.writeField(field, this, false, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                Boolean value = (Boolean) this.model.get(field.getName());
                if (fieldType.getName().equals("java.lang.Boolean")
                        || fieldType.getName().equals("boolean")) {
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.String")) {
                    try {
                        FieldUtils.writeField(field, this,
                                String.valueOf(value), true);
                    } catch (IllegalAccessException e) {
                    }
                }
            }

            if (field.getAnnotation(CheckBoxMultipleChoice.class) != null
                    || field.getAnnotation(ListMultipleChoice.class) != null) {
                if (model.get(field.getName()) == null
                        || ((List<?>) model.get(field.getName())).isEmpty()) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }

                if (int[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    int[] value = new int[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Integer.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Integer[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Integer[] value = new Integer[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Integer.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (short[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    short[] value = new short[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Short.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Short[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Short[] value = new Short[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Short.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (byte[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    byte[] value = new byte[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Byte.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Byte[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Byte[] value = new Byte[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Byte.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Float[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Float[] value = new Float[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Float.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (float[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    float[] value = new float[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Float.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Long[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Long[] value = new Long[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Long.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (long[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    long[] value = new long[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Long.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (Double[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    Double[] value = new Double[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Double.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (double[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    double[] value = new double[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = Double.valueOf(list.get(i).get("value"));
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (String[].class.isAssignableFrom(field.getType())) {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    String[] value = new String[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        value[i] = list.get(i).get("value");
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else {
                    List<Map<String, String>> list = (List<Map<String, String>>) model
                            .get(field.getName());
                    String id = TableUtilities.getIdentityField(field.getType()
                            .getComponentType());

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    String tableName = TableUtilities.getTableName(field
                            .getType().getComponentType());
                    String query = "select * from " + tableName + " where "
                            + id + " = ?";
                    Object[] value = (Object[]) Array.newInstance(field
                            .getType().getComponentType(), list.size());
                    for (int i = 0; i < list.size(); i++) {
                        try {
                            value[i] = application.getJdbcTemplate()
                                    .queryForObject(
                                            query,
                                            new GenericEntityMapper(field.getType()
                                                    .getComponentType()),
                                            list.get(i).get("value"));
                        } catch (EmptyResultDataAccessException e) {
                        }
                    }
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                }
            }

            if (field.getAnnotation(DropDownChoice.class) != null
                    || field.getAnnotation(RadioChoice.class) != null) {
                Map<String, String> value = (Map<String, String>) model
                        .get(field.getName());
                if (value == null || value.isEmpty()) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                if (fieldType.getName().equals("java.lang.Short")
                        || fieldType.getName().equals("short")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Short.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Long")
                        || fieldType.getName().equals("long")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Long.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Integer")
                        || fieldType.getName().equals("int")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Integer.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Byte")
                        || fieldType.getName().equals("byte")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Byte.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Float")
                        || fieldType.getName().equals("float")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Float.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Double")
                        || fieldType.getName().equals("double")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Double.valueOf(value.get("value")), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.String")) {
                    try {
                        FieldUtils.writeField(field, this, value.get("value"),
                                true);
                    } catch (IllegalAccessException e) {
                    }
                } else {
                    String id = TableUtilities
                            .getIdentityField(field.getType());

                    AbstractWebApplication application = (AbstractWebApplication) getApplication();
                    String tableName = TableUtilities.getTableName(field
                            .getType());
                    String query = "select * from " + tableName + " where "
                            + id + " = ?";
                    try {
                        Object entity = application.getJdbcTemplate()
                                .queryForObject(query,
                                        new GenericEntityMapper(field.getType()),
                                        value.get("value"));
                        try {
                            FieldUtils.writeField(field, this, entity, true);
                        } catch (IllegalAccessException e) {
                        }
                    } catch (EmptyResultDataAccessException e) {
                    }
                }
            }

            if (field.getAnnotation(FileUploadField.class) != null) {
                List<FileUpload> values = (List<FileUpload>) model.get(field
                        .getName());
                if (values == null || values.isEmpty()) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                try {
                    FieldUtils.writeField(field, this, values.get(0), true);
                } catch (IllegalAccessException e) {
                }
            }

            if (field.getAnnotation(MultiFileUploadField.class) != null) {
                List<FileUpload> values = (List<FileUpload>) model.get(field
                        .getName());
                if (values == null || values.isEmpty()) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                try {
                    FieldUtils.writeField(field, this, Arrays.asList(values),
                            true);
                } catch (IllegalAccessException e) {
                }
            }

            if (field.getAnnotation(Select2MultiChoice.class) != null) {
                List<?> list = (List<?>) model.get(field.getName());
                if (list == null || list.isEmpty()) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                Object[] objects = (Object[]) Array.newInstance(field.getType()
                        .getComponentType(), list.size());
                for (int i = 0; i < list.size(); i++) {
                    objects[i] = list.get(i);
                }
                try {
                    FieldUtils.writeField(field, this, objects, true);
                } catch (IllegalAccessException e) {
                }
            }
            if (field.getAnnotation(Select2Choice.class) != null) {
                Object object = model.get(field.getName());
                if (object == null || "".equals(object)) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                try {
                    FieldUtils.writeField(field, this, object, true);
                } catch (IllegalAccessException e) {
                }
            }

            if (field.getAnnotation(TextArea.class) != null) {
                String value = (String) model.get(field.getName());
                if (value == null || "".equals(value)) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                try {
                    FieldUtils.writeField(field, this, value, true);
                } catch (IllegalAccessException e) {
                }
            }

            if (field.getAnnotation(TextField.class) != null) {
                String value = (String) model.get(field.getName());
                if (value == null || "".equals(value)) {
                    try {
                        FieldUtils.writeField(field, this, null, true);
                    } catch (IllegalAccessException e) {
                    }
                    continue;
                }
                if (fieldType.getName().equals("java.lang.Short")
                        || fieldType.getName().equals("short")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Short.valueOf(value), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Long")
                        || fieldType.getName().equals("long")) {
                    try {
                        FieldUtils.writeField(field, this, Long.valueOf(value),
                                true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Integer")
                        || fieldType.getName().equals("int")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Integer.valueOf(value), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Byte")
                        || fieldType.getName().equals("byte")) {
                    try {
                        FieldUtils.writeField(field, this, Byte.valueOf(value),
                                true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Float")
                        || fieldType.getName().equals("float")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Float.valueOf(value), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.Double")
                        || fieldType.getName().equals("double")) {
                    try {
                        FieldUtils.writeField(field, this,
                                Double.valueOf(value), true);
                    } catch (NumberFormatException e) {
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.lang.String")) {
                    try {
                        FieldUtils.writeField(field, this, value, true);
                    } catch (IllegalAccessException e) {
                    }
                } else if (fieldType.getName().equals("java.util.Date")) {
                    SimpleDateFormat format = new SimpleDateFormat(field
                            .getAnnotation(TextField.class).pattern());
                    try {
                        FieldUtils.writeField(field, this,
                                format.parseObject(value), true);
                    } catch (IllegalAccessException e) {
                    } catch (ParseException e) {
                        try {
                            Date val = (Date) FieldUtils.readField(field, this,
                                    true);
                            if (val != null) {
                                model.put(field.getName(), format.format(val));
                            }
                        } catch (IllegalAccessException e1) {
                        }

                    }
                }
            }
        }
    }

    protected final void buttonClick(String methodName) {
        try {
            Method method = this.getClass().getMethod(methodName);
            Navigation navigation = (Navigation) method.invoke(this);
            if (navigation != null) {
                if (navigation.getInstance() != null) {
                    setResponsePage(navigation.getInstance());
                }
                if (navigation.getClazz() != null) {
                    if (navigation.getParameters() != null) {
                        setResponsePage(navigation.getClazz(),
                                navigation.getParameters());
                    } else {
                        setResponsePage(navigation.getClazz());
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}


text:
import FileStatus from "../FileStatus/FileStatus";

export default ({filename, status}) =>

{filename}

  <FileStatus file={{status}} />

redpajama_set_name: RedPajamaGithub


text:
package reflex.util.function;

public class FunctionKey {

    public static final String DEFAULT_NAMESPACE = "#default_namespace";

    public String getNamespace() {
        return namespacePrefix;
    }

    public void setNamespace(String namespace) {
        this.namespacePrefix = namespace;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumParams() {
        return numParams;
    }

    public void setNumParams(int numParams) {
        this.numParams = numParams;
    }

    private String namespacePrefix;
    private String name;
    private int numParams;

    public FunctionKey(String namespacePrefix, String name, int numParams) {
        this.namespacePrefix = namespacePrefix;
        this.name = name;
        this.numParams = numParams;
    }

    @Override
    public String toString() {
        return namespacePrefix + name + "." + numParams;
    }
}


text:
import base64
import os
import shutil
import tempfile

from oslo_config import cfg

from ironic_discoverd.plugins import standard as std_plugins
from ironic_discoverd import process
from ironic_discoverd.test import base as test_base
from ironic_discoverd import utils

CONF = cfg.CONF

class TestRamdiskError(test_base.BaseTest):
    def setUp(self):
        super(TestRamdiskError, self).setUp()
        self.msg = 'BOOM'
        self.bmc_address = '1.2.3.4'
        self.data = {
            'error': self.msg,
            'ipmi_address': self.bmc_address,
        }

        self.tempdir = tempfile.mkdtemp()
        self.addCleanup(lambda: shutil.rmtree(self.tempdir))
        CONF.set_override('ramdisk_logs_dir', self.tempdir, 'discoverd')

    def test_no_logs(self):
        self.assertRaisesRegexp(utils.Error,
                                self.msg,
                                process.process, self.data)
        self.assertEqual([], os.listdir(self.tempdir))

    def test_logs_disabled(self):
        self.data['logs'] = 'some log'
        CONF.set_override('ramdisk_logs_dir', None, 'discoverd')

        self.assertRaisesRegexp(utils.Error,
                                self.msg,
                                process.process, self.data)
        self.assertEqual([], os.listdir(self.tempdir))

    def test_logs(self):
        log = b'log contents'
        self.data['logs'] = base64.b64encode(log)

        self.assertRaisesRegexp(utils.Error,
                                self.msg,
                                process.process, self.data)

        files = os.listdir(self.tempdir)
        self.assertEqual(1, len(files))
        filename = files[0]
        self.assertTrue(filename.startswith('bmc_%s_' % self.bmc_address),
                        '%s does not start with bmc_%s'
                        % (filename, self.bmc_address))
        with open(os.path.join(self.tempdir, filename), 'rb') as fp:
            self.assertEqual(log, fp.read())

    def test_logs_create_dir(self):
        shutil.rmtree(self.tempdir)
        self.data['logs'] = base64.b64encode(b'log')

        self.assertRaisesRegexp(utils.Error,
                                self.msg,
                                process.process, self.data)

        files = os.listdir(self.tempdir)
        self.assertEqual(1, len(files))

    def test_logs_without_error(self):
        log = b'log contents'
        del self.data['error']
        self.data['logs'] = base64.b64encode(log)

        std_plugins.RamdiskErrorHook().before_processing(self.data)

        files = os.listdir(self.tempdir)
        self.assertFalse(files)

    def test_always_store_logs(self):
        CONF.set_override('always_store_ramdisk_logs', True, 'discoverd')

        log = b'log contents'
        del self.data['error']
        self.data['logs'] = base64.b64encode(log)

        std_plugins.RamdiskErrorHook().before_processing(self.data)

        files = os.listdir(self.tempdir)
        self.assertEqual(1, len(files))
        filename = files[0]
        self.assertTrue(filename.startswith('bmc_%s_' % self.bmc_address),
                        '%s does not start with bmc_%s'
                        % (filename, self.bmc_address))
        with open(os.path.join(self.tempdir, filename), 'rb') as fp:
            self.assertEqual(log, fp.read())


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// ReSharper disable CommentTypo

/* ReaderManager.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System;
using System.Collections.Generic;
using System.Linq;

using AM;

using CodeJam;

using JetBrains.Annotations;

using ManagedIrbis.Batch;

#endregion

namespace ManagedIrbis.Readers
{
    /// <summary>
    /// Основные операции с читателями.
    /// </summary>
    [PublicAPI]
    public sealed class ReaderManager
    {
        #region Constants

        /// <summary>
        /// Стандартный префикс идентификатора читателя.
        /// </summary>
        // TODO: брать индекс из настроек клиента
        public const string ReaderIdentifier = "RI=";

        #endregion

        #region Events

        /// <summary>
        /// Fired on batch read.
        /// </summary>
        public event EventHandler BatchRead;

        #endregion

        #region Properties

        /// <summary>
        /// Клиент, общающийся с сервером.
        /// </summary>
        [NotNull]
        public IrbisConnection Connection { get; private set; }

        /// <summary>
        /// Omit deleted records?
        /// </summary>
        public bool OmitDeletedRecords { get; set; }

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the <see cref="ReaderManager"/> class.
        /// </summary>
        public ReaderManager
            (
                [NotNull] IrbisConnection connection
            )
        {
            Code.NotNull(connection, "connection");

            Connection = connection;
        }

        #endregion

        #region Private members

        private void HandleBatchRead
            (
                object sender,
                EventArgs eventArgs
            )
        {
            BatchRead.Raise(sender, eventArgs);
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Получение массива всех (не удалённых) читателей из базы данных.
        /// </summary>
        [NotNull]
        [ItemNotNull]
        public ReaderInfo[] GetAllReaders
            (
                [NotNull] string database
            )
        {
            Code.NotNullNorEmpty(database, "database");

            List<ReaderInfo> result = new List<ReaderInfo>
                (
                    Connection.GetMaxMfn() + 1
                );

            IEnumerable<MarcRecord> batch = BatchRecordReader.WholeDatabase
                (
                    Connection,
                    database,
                    500
                );

            BatchRecordReader batch2 = batch as BatchRecordReader;
            if (!ReferenceEquals(batch2, null))
            {
                batch2.BatchRead += HandleBatchRead;
            }

            foreach (MarcRecord record in batch)
            {
                if (!ReferenceEquals(record, null))
                {
                    if (OmitDeletedRecords && record.Deleted)
                    {
                        continue;
                    }

                    ReaderInfo reader = ReaderInfo.Parse(record);
                    result.Add(reader);
                }
            }

            if (!ReferenceEquals(batch2, null))
            {
                batch2.BatchRead -= HandleBatchRead;
            }

            return result.ToArray();
        }

        /// <summary>
        /// Получение массива всех (не удалённых) читателей из базы данных.
        /// </summary>
        [NotNull]
        [ItemNotNull]
        public ReaderInfo[] GetReaders
            (
                [NotNull] string database,
                [NotNull] IEnumerable<int> mfns
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.NotNull(mfns, "mfns");

            List<ReaderInfo> result = new List<ReaderInfo>();

            IEnumerable<MarcRecord> batch = new BatchRecordReader
                (
                    Connection,
                    database,
                    500,
                    mfns
                );

            BatchRecordReader batch2 = (BatchRecordReader) batch;
            batch2.BatchRead += HandleBatchRead;

            foreach (MarcRecord record in batch)
            {
                if (!ReferenceEquals(record, null))
                {
                    if (OmitDeletedRecords && record.Deleted)
                    {
                        continue;
                    }

                    ReaderInfo reader = ReaderInfo.Parse(record);
                    result.Add(reader);
                }
            }

            batch2.BatchRead -= HandleBatchRead;

            return result.ToArray();
        }

        /// <summary>
        /// Получение записи читателя по его идентификатору.
        /// </summary>
        [CanBeNull]
        public ReaderInfo GetReader
            (
                [NotNull] string ticket
            )
        {
            Code.NotNullNorEmpty(ticket, "ticket");

            MarcRecord record = Connection.SearchReadOneRecord
                (
                    "{0}{1}",
                    ReaderIdentifier,
                    ticket
                );
            if (ReferenceEquals(record, null))
            {
                return null;
            }

            ReaderInfo result = ReaderInfo.Parse(record);

            return result;
        }

        /// <summary>
        /// Поиск читателя, соответствующего выражению.
        /// </summary>
        [CanBeNull]
        public ReaderInfo FindReader
            (
                [NotNull] string format,
                params object[] args
            )
        {
            Code.NotNullNorEmpty(format, "format");

            var record = Connection.SearchReadOneRecord(format, args);
            if (ReferenceEquals(record, null))
            {
                return null;
            }

            var result = ReaderInfo.Parse(record);

            return result;
        }

        /// <summary>
        /// Merge readers (i. e. from some databases).
        /// </summary>
        [NotNull]
        [ItemNotNull]
        public static List<ReaderInfo> MergeReaders
            (
                [NotNull] IEnumerable<ReaderInfo> readers
            )
        {
            Code.NotNull(readers, "readers");

            var grouped = readers
                .Where(r => !string.IsNullOrEmpty(r.Ticket))
                .GroupBy(r => r.Ticket);

            List<ReaderInfo> result = new List<ReaderInfo>();

            foreach (var grp in grouped)
            {
                ReaderInfo first = grp.First();
                first.Visits = grp
                    .SelectMany(r => r.Visits)
                    .OrderBy(v => v.DateGivenString)
                    .ToArray();
                first.Registrations = grp
                    .SelectMany(r => r.Registrations)
                    .OrderBy(r => r.DateString)
                    .ToArray();
                first.Enrollment = grp
                    .SelectMany(r => r.Enrollment)
                    .OrderBy(r => r.DateString)
                    .ToArray();
                first.Marked = grp.Any(r => r.Marked);
                result.Add(first);
            }

            return result;
        }

        #endregion
    }
}