jp.primecloud.auto.ui.WinUserAuthAddEdit.java Source code

Java tutorial

Introduction

Here is the source code for jp.primecloud.auto.ui.WinUserAuthAddEdit.java

Source

/*
 * Copyright 2014 by SCSK Corporation.
 * 
 * This file is part of PrimeCloud Controller(TM).
 * 
 * PrimeCloud Controller(TM) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 * 
 * PrimeCloud Controller(TM) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>.
 */
package jp.primecloud.auto.ui;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.primecloud.auto.entity.crud.AuthoritySet;
import jp.primecloud.auto.entity.crud.Farm;
import jp.primecloud.auto.entity.crud.UserAuth;
import jp.primecloud.auto.exception.AutoApplicationException;
import jp.primecloud.auto.service.UserManagementService;
import jp.primecloud.auto.service.UserService;
import jp.primecloud.auto.service.dto.FarmDto;
import jp.primecloud.auto.service.dto.UserDto;
import jp.primecloud.auto.ui.DialogConfirm.Buttons;
import jp.primecloud.auto.ui.DialogConfirm.Result;
import jp.primecloud.auto.ui.util.BeanContext;
import jp.primecloud.auto.ui.util.ConvertUtil;
import jp.primecloud.auto.ui.util.Icons;
import jp.primecloud.auto.ui.util.ViewMessages;
import jp.primecloud.auto.ui.util.ViewProperties;
import jp.primecloud.auto.util.MessageUtils;
import com.vaadin.data.Item;
import com.vaadin.data.Validator;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

/**
 * <p>
 * ?/?????
 * </p>
 *
 */
@SuppressWarnings("serial")
public class WinUserAuthAddEdit extends Window {

    /////  /////
    //?()
    private Long masterUserNo;
    //?(??)
    private Long userNo;
    //(?)
    private UserDto userDto;
    //
    //(??:???????:??????)
    private List<FarmDto> farmDtos;
    //?<?, UserAuth>
    private Map<Long, UserAuth> userAuthMap;
    //?
    private List<AuthoritySet> authoritySets;
    //?/? 
    private Boolean isAddUser;
    //??
    private ConvertUtil convertUtil;

    ///// vaadin component /////
    //?? 
    private TextField userNameField;
    //?? 
    private TextField passwordField;
    //?
    private UserAuthTable userAuthTable;

    WinUserAuthAddEdit(Long masterUserNo, Long userNo) {

        this.masterUserNo = masterUserNo;
        this.userNo = userNo;

        //?
        isAddUser = (userNo == null) ? true : false;

        // ???
        initData();

        //
        //????
        if (isAddUser) {
            //??
            setIcon(Icons.ADD.resource());
            setCaption(ViewProperties.getCaption("window.winUserAdd"));
        } else {
            //?
            setIcon(Icons.EDIT.resource());
            setCaption(ViewProperties.getCaption("window.winUserEdit"));
        }
        //
        setModal(true);
        setWidth("450px");
        //
        setResizable(false);

        //
        VerticalLayout layout = (VerticalLayout) getContent();
        layout.setMargin(false, true, false, true);
        layout.setSpacing(false);

        // 
        layout.addComponent(new AuthAddForm());

        // ?
        userAuthTable = new UserAuthTable();
        layout.addComponent(userAuthTable);

        // ??
        HorizontalLayout okbar = new HorizontalLayout();
        okbar.setSpacing(true);
        okbar.setMargin(true, false, true, false);
        layout.addComponent(okbar);
        layout.setComponentAlignment(okbar, Alignment.BOTTOM_RIGHT);

        // OK
        Button okButton = new Button(ViewProperties.getCaption("button.ok"));
        if (isAddUser) {
            //??
            okButton.setDescription(ViewProperties.getCaption("description.addUserAuth.ok"));
        } else {
            //?
            okButton.setDescription(ViewProperties.getCaption("description.editUserAuth.ok"));
        }
        okButton.addListener(new Button.ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                WinUserAuthAddEdit.this.okButtonClick(event);
            }
        });
        okbar.addComponent(okButton);

        //Delete
        if (!isAddUser) {
            //?????
            Button deleteButton = new Button(ViewProperties.getCaption("button.delete"));
            deleteButton.setDescription(ViewProperties.getCaption("description.editUserAuth.delete"));
            deleteButton.addListener(new Button.ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    WinUserAuthAddEdit.this.deleteButtonClick(event);
                }
            });
            okbar.addComponent(deleteButton);
        }

        // Cancel
        Button cancelButton = new Button(ViewProperties.getCaption("button.cancel"));
        cancelButton.setDescription(ViewProperties.getCaption("description.cancel"));
        cancelButton.addListener(new Button.ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                WinUserAuthAddEdit.this.cancelButtonClick(event);
            }
        });
        okbar.addComponent(cancelButton);

        // ??
        showData();

        // ??
        initValidation();
    }

    private void setCustomErrorHandler(Button button) {
        //?????PCC??????????
        if (button.getErrorHandler() == null
                || button.getErrorHandler().getClass() != ComponentsErrorHandler.class) {
            button.setErrorHandler(new ComponentsErrorHandler(this.getParent()));
        }
    }

    private class AuthAddForm extends Form {
        AuthAddForm() {
            setImmediate(true);

            //??
            userNameField = new TextField(ViewProperties.getCaption("field.userName"));
            userNameField.setImmediate(true);
            getLayout().addComponent(userNameField);

            //
            passwordField = new TextField(ViewProperties.getCaption("field.password"));
            passwordField.setSecret(true);
            passwordField.setImmediate(true);
            getLayout().addComponent(passwordField);
        }
    }

    private class UserAuthTable extends Table {
        private final String[] HEADER_NAMES_ADD = { ViewProperties.getCaption("field.couldname"),
                ViewProperties.getCaption("label.userAuth.authority") };

        private final String[] HEADER_NAMES_EDIT = { ViewProperties.getCaption("field.couldname"),
                ViewProperties.getCaption("label.userAuth.authority"),
                ViewProperties.getCaption("label.userAuth.edit") };

        private final String PID_TABLE_CLOUD_NAME = "CloudName";
        private final String PID_TABLE_AUTHORITY_SET = "AuthoritySet";
        private final String PID_TABLE_EDIT = "Edit";

        private final String COLUMN_HEIGHT = "28px";

        private final String PID_COMBOX_AUTHORITY_SET = "AuthoritySet";

        private final String AUTHORITY_SET_NOTHING = ViewProperties.getCaption("label.nothing");

        private final String AUTHORITY_SET_CUSTOM = ViewProperties.getCaption("label.custom");

        private final Long AUTHORITY_SET_SETNO_CUSTOM = new Long(-1);
        private final Long AUTHORITY_SET_SETNO_NOTHING = new Long(0);

        UserAuthTable() {
            //
            setWidth("100%");
            setHeight("363px");
            setPageLength(10);
            setSortDisabled(true);
            setColumnCollapsingAllowed(false);
            setColumnReorderingAllowed(false);
            setSelectable(true);
            setMultiSelect(false);
            setNullSelectionAllowed(false);
            setImmediate(true);
            addStyleName("user-table");

            //
            addContainerProperty(PID_TABLE_CLOUD_NAME, Label.class, null);
            addContainerProperty(PID_TABLE_AUTHORITY_SET, ComboBox.class, null);
            if (!isAddUser) {
                //???
                addContainerProperty(PID_TABLE_EDIT, Button.class, null);
            }
            setColumnHeaders((isAddUser) ? HEADER_NAMES_ADD : HEADER_NAMES_EDIT);

            //????StyleName
            setCellStyleGenerator(new Table.CellStyleGenerator() {
                public String getStyle(Object itemId, Object propertyId) {
                    if (propertyId == null) {
                        return "";
                    } else {
                        return propertyId.toString().toLowerCase();
                    }
                }
            });
        }

        private void showUserAuths() {
            userAuthTable.removeAllItems();

            // ?
            for (FarmDto farmDto : farmDtos) {
                final Farm farm = farmDto.getFarm();

                //???
                Label myCloudLbl = new Label(farm.getFarmName());
                myCloudLbl.setHeight(COLUMN_HEIGHT);

                //??
                ComboBox authoritySetSelect = new ComboBox();
                authoritySetSelect.setItemCaptionPropertyId(PID_COMBOX_AUTHORITY_SET);
                authoritySetSelect.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
                authoritySetSelect.setNullSelectionAllowed(false);
                //
                authoritySetSelect.setContainerDataSource(createAuthoritySetContainer());
                //??
                if (isAddUser) {
                    //??  ???
                    authoritySetSelect.select(userAuthTable.AUTHORITY_SET_SETNO_NOTHING);
                } else {
                    //?  ??????
                    UserAuth userAuth = userAuthMap.get(farm.getFarmNo());
                    authoritySetSelect.select(convertUtil.ConvertAuthToSetNo(userAuth));
                }

                if (isAddUser) {
                    //????
                    userAuthTable.addItem(new Object[] { myCloudLbl, authoritySetSelect }, farm.getFarmNo());
                } else {
                    //?????
                    //?
                    Button btnEdit = new Button(ViewProperties.getCaption("button.editUserAuthDetail"));
                    btnEdit.setDescription(ViewProperties.getCaption("description.editUserAuthDetail"));
                    btnEdit.addStyleName("borderless");
                    btnEdit.addListener(new Button.ClickListener() {
                        @Override
                        public void buttonClick(ClickEvent event) {
                            editButtonClick(event, farm.getFarmNo());
                        }
                    });
                    userAuthTable.addItem(new Object[] { myCloudLbl, authoritySetSelect, btnEdit },
                            farm.getFarmNo());
                }
            }

            Long farmNo = null;
            if (userAuthTable.getItemIds().size() > 0) {
                farmNo = (Long) userAuthTable.getItemIds().toArray()[0];
            }

            // ???
            userAuthTable.select(farmNo);
        }

        private IndexedContainer createAuthoritySetContainer() {
            IndexedContainer authoritySetContainer = new IndexedContainer();
            authoritySetContainer.addContainerProperty(PID_COMBOX_AUTHORITY_SET, String.class, null);

            for (AuthoritySet authoritySet : authoritySets) {
                Item item = authoritySetContainer.addItem(authoritySet.getSetNo());
                item.getItemProperty(PID_COMBOX_AUTHORITY_SET).setValue(authoritySet.getSetName());
            }

            if (!isAddUser) {
                //????????????
                //???
                Item itemCustom = authoritySetContainer.addItem(AUTHORITY_SET_SETNO_CUSTOM);
                itemCustom.getItemProperty(PID_COMBOX_AUTHORITY_SET).setValue(AUTHORITY_SET_CUSTOM);
            }
            //?????
            Item itemNothing = authoritySetContainer.addItem(AUTHORITY_SET_SETNO_NOTHING);
            itemNothing.getItemProperty(PID_COMBOX_AUTHORITY_SET).setValue(AUTHORITY_SET_NOTHING);

            return authoritySetContainer;
        }

        private void editButtonClick(ClickEvent event, final Long farmNo) {
            //?
            String message = ViewMessages.getMessage("IUI-000119");
            DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.confirm"), message,
                    Buttons.OKCancel);
            //?????PCC??????????
            setCustomErrorHandler(dialog.okButton);
            dialog.setCallback(new DialogConfirm.Callback() {
                @Override
                public void onDialogResult(Result result) {
                    if (result != Result.OK) {
                        //OK???????
                        return;
                    }

                    //?
                    WinUserAuthEditDetail winUserAuthDetailEdit = new WinUserAuthEditDetail(userNo, farmNo);
                    winUserAuthDetailEdit.addListener(new Window.CloseListener() {
                        @Override
                        public void windowClose(Window.CloseEvent e) {
                            //?????
                            initData();
                            showData();
                        }
                    });
                    WinUserAuthAddEdit.this.getParent().addWindow(winUserAuthDetailEdit);
                }
            });
            WinUserAuthAddEdit.this.getParent().addWindow(dialog);
        }
    }

    private void initValidation() {
        //??
        String message = ViewMessages.getMessage("IUI-000117");
        userNameField.setRequired(true);
        userNameField.setRequiredError(message);
        userNameField.addValidator(new StringLengthValidator(message, -1, 15, false));
        userNameField.addValidator(new RegexpValidator("^[a-z]|[a-z][0-9a-z-]*[0-9a-z]$", true, message));

        //
        message = ViewMessages.getMessage("IUI-000118");
        passwordField.setRequired(true);
        passwordField.setRequiredError(message);
        passwordField.addValidator(new StringLengthValidator(message, 1, 15, false));
        passwordField.addValidator(new Validator() {
            @Override
            public void validate(Object value) throws InvalidValueException {
                if (isValid(value)) {
                    throw new InvalidValueException(ViewMessages.getMessage("IUI-000118"));
                }
            }

            @Override
            public boolean isValid(Object value) {
                if (value == null || !(value instanceof String)) {
                    return false;
                }
                return ((String) value).matches(".*&.*|.*\".*|.*'.*|.*<.*|.*>.*");
            }
        });
    }

    private void initData() {
        // ?
        if (!isAddUser) {
            //???
            UserService userService = BeanContext.getBean(UserService.class);
            this.userDto = userService.getUser(userNo);
        }

        // ?(?????)
        UserManagementService userManagementService = BeanContext.getBean(UserManagementService.class);
        this.farmDtos = userManagementService.getFarms(masterUserNo);

        //??(?)
        this.authoritySets = userManagementService.getAuthoritySet();

        if (!isAddUser) {
            //???
            //??
            this.userAuthMap = userManagementService.getUserAuthMap(userNo);
            //??
            this.convertUtil = new ConvertUtil();
        }
    }

    private void showData() {
        if (!isAddUser) {
            //???
            //??
            userNameField.setValue(userDto.getUser().getUsername());
            //
            passwordField.setValue(userDto.getUser().getPassword());
        }

        //??
        userAuthTable.showUserAuths();
    }

    private void okButtonClick(ClickEvent event) {
        //?????PCC??????????
        //??ParentWindow????(NULL)?????
        setCustomErrorHandler(event.getButton());

        //?
        try {
            //??
            userNameField.validate();
            //
            passwordField.validate();
        } catch (InvalidValueException e) {
            String errMes = e.getMessage();
            if (null == errMes) {
                //?????????? ?
                InvalidValueException[] exceptions = e.getCauses();
                errMes = exceptions[0].getMessage();
            }

            DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.error"), errMes);
            getParent().addWindow(dialog);
            return;
        }

        // ??
        //??
        String userName = (String) userNameField.getValue();
        //
        String password = (String) passwordField.getValue();

        //?
        Map<Long, Long> authMap = new HashMap<Long, Long>();
        for (int i = 0; i < userAuthTable.getItemIds().size(); i++) {
            Long farmNo = (Long) userAuthTable.getItemIds().toArray()[i];
            Item item = userAuthTable.getItem(farmNo);
            ComboBox comBox = (ComboBox) item.getItemProperty(userAuthTable.PID_TABLE_AUTHORITY_SET).getValue();
            Long setNo = (Long) comBox.getValue();
            if (userAuthTable.AUTHORITY_SET_SETNO_CUSTOM.equals(setNo)) {
                //??????????????
                continue;
            } else {
                //?????????setNo?0?????
                authMap.put(farmNo, setNo);
            }
        }

        //?
        try {
            UserManagementService userManagementService = BeanContext.getBean(UserManagementService.class);
            if (isAddUser) {
                //??
                userManagementService.createUserAndUserAuth(masterUserNo, userName, password, authMap);
            } else {
                //?
                userManagementService.updateUserAndUserAuth(userNo, userName, password, authMap);
            }
        } catch (AutoApplicationException e) {
            //??
            String message = ViewMessages.getMessage(e.getCode(), e.getAdditions());
            DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.error"), message);
            getParent().addWindow(dialog);
            return;
        }

        // ??
        close();
    }

    private void deleteButtonClick(ClickEvent event) {
        //?
        String message = ViewMessages.getMessage("IUI-000120");
        DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.confirm"), message,
                Buttons.OKCancel);
        //?????PCC??????????
        setCustomErrorHandler(dialog.okButton);
        dialog.setCallback(new DialogConfirm.Callback() {
            @Override
            public void onDialogResult(Result result) {
                if (result != Result.OK) {
                    //OK???????
                    return;
                }

                //?
                try {
                    UserManagementService userManagementService = BeanContext.getBean(UserManagementService.class);
                    userManagementService.deleteUser(userNo);
                } catch (AutoApplicationException e) {
                    //??
                    String message = ViewMessages.getMessage(e.getCode(), e.getAdditions());
                    DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.error"), message);
                    getParent().addWindow(dialog);
                    return;
                }

                // ??
                close();
            }
        });
        getParent().addWindow(dialog);
    }

    private void cancelButtonClick(ClickEvent event) {
        //?????PCC??????????
        setCustomErrorHandler(event.getButton());
        WinUserAuthAddEdit.this.close();
    }
}