Example usage for com.vaadin.ui TextField getValue

List of usage examples for com.vaadin.ui TextField getValue

Introduction

In this page you can find the example usage for com.vaadin.ui TextField getValue.

Prototype

@Override
    public String getValue() 

Source Link

Usage

From source file:it.vige.greenarea.bpm.custom.ui.form.GreenareaPagedTable.java

License:Apache License

@Override
public HorizontalLayout createControls() {
    I18nManager I18nManager = get().getI18nManager();
    final PagedTableContainer container = (PagedTableContainer) getContainerDataSource();
    Label itemsPerPageLabel = new Label(I18nManager.getMessage(PAGINAZIONE_PER_PAGINA));
    final ComboBox itemsPerPageSelect = new ComboBox();

    itemsPerPageSelect.addItem("3");
    itemsPerPageSelect.addItem("10");
    itemsPerPageSelect.addItem("25");
    itemsPerPageSelect.addItem("50");
    itemsPerPageSelect.setImmediate(true);
    itemsPerPageSelect.setNullSelectionAllowed(false);
    itemsPerPageSelect.setWidth("50px");
    itemsPerPageSelect.addListener(new ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            setPageLength(Integer.valueOf(String.valueOf(event.getProperty().getValue())));
        }//from   ww  w  .j a v  a2 s  .c  o m
    });
    itemsPerPageSelect.select(maxRecords + "");
    Label pageLabel = new Label(I18nManager.getMessage(PAGINAZIONE_PAG) + " ", Label.CONTENT_XHTML);
    final TextField currentPageTextField = new TextField();
    currentPageTextField.setValue(String.valueOf(getCurrentPage()));
    currentPageTextField.addValidator(new IntegerValidator(null));
    Label separatorLabel = new Label(" / ", Label.CONTENT_XHTML);
    final Label totalPagesLabel = new Label(String.valueOf(getTotalAmountOfPages()), Label.CONTENT_XHTML);
    currentPageTextField.setStyleName(Reindeer.TEXTFIELD_SMALL);
    currentPageTextField.setImmediate(true);
    currentPageTextField.addListener(new ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            if (currentPageTextField.isValid() && currentPageTextField.getValue() != null) {
                int page = Integer.valueOf(String.valueOf(currentPageTextField.getValue()));
                setCurrentPage(page);
            }
        }
    });
    pageLabel.setWidth(null);
    currentPageTextField.setWidth("20px");
    separatorLabel.setWidth(null);
    totalPagesLabel.setWidth(null);

    HorizontalLayout controlBar = new HorizontalLayout();
    HorizontalLayout pageSize = new HorizontalLayout();
    HorizontalLayout pageManagement = new HorizontalLayout();
    final Button first = new Button("<<", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(ClickEvent event) {
            setCurrentPage(0);
            if (values != null && !values.isEmpty() && values.iterator().next() instanceof Selectable) {
                Selectable selectable = (Selectable) values.toArray()[container.getStartIndex()];
                GreenareaFormPropertiesComponent greenareaFormPropertiesComponent = (GreenareaFormPropertiesComponent) greenareaFormPropertiesForm
                        .getComponent(1);
                FormProperty formProperty = greenareaFormPropertiesComponent.getFormProperties().get(0);
                FormPropertyRenderer formPropertyRenderer = greenareaFormPropertiesComponent
                        .getRenderer(formProperty);
                greenareaFormPropertiesComponent.getForm()
                        .getField(greenareaFormPropertiesComponent.getFormProperties().get(0).getId())
                        .setValue(formPropertyRenderer.getPropertyLabel(formProperty) + " "
                                + selectable.getValue());
            }
        }
    });
    final Button previous = new Button("<", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(ClickEvent event) {
            previousPage();
            if (values != null && !values.isEmpty() && values.iterator().next() instanceof Selectable) {
                Selectable selectable = (Selectable) values.toArray()[container.getStartIndex()];
                GreenareaFormPropertiesComponent greenareaFormPropertiesComponent = (GreenareaFormPropertiesComponent) greenareaFormPropertiesForm
                        .getComponent(1);
                FormProperty formProperty = greenareaFormPropertiesComponent.getFormProperties().get(0);
                FormPropertyRenderer formPropertyRenderer = greenareaFormPropertiesComponent
                        .getRenderer(formProperty);
                greenareaFormPropertiesComponent.getForm()
                        .getField(greenareaFormPropertiesComponent.getFormProperties().get(0).getId())
                        .setValue(formPropertyRenderer.getPropertyLabel(formProperty) + " "
                                + selectable.getValue());
            }
        }
    });
    final Button next = new Button(">", new ClickListener() {
        private static final long serialVersionUID = -1927138212640638452L;

        public void buttonClick(ClickEvent event) {
            nextPage();
            if (values != null && !values.isEmpty() && values.iterator().next() instanceof Selectable) {
                Selectable selectable = (Selectable) values.toArray()[container.getStartIndex()];
                GreenareaFormPropertiesComponent greenareaFormPropertiesComponent = (GreenareaFormPropertiesComponent) greenareaFormPropertiesForm
                        .getComponent(1);
                FormProperty formProperty = greenareaFormPropertiesComponent.getFormProperties().get(0);
                FormPropertyRenderer formPropertyRenderer = greenareaFormPropertiesComponent
                        .getRenderer(formProperty);
                greenareaFormPropertiesComponent.getForm()
                        .getField(greenareaFormPropertiesComponent.getFormProperties().get(0).getId())
                        .setValue(formPropertyRenderer.getPropertyLabel(formProperty) + " "
                                + selectable.getValue());
            }
        }
    });
    final Button last = new Button(">>", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(ClickEvent event) {
            setCurrentPage(getTotalAmountOfPages());
            if (values != null && !values.isEmpty() && values.iterator().next() instanceof Selectable) {
                Selectable selectable = (Selectable) values.toArray()[container.getStartIndex()];
                GreenareaFormPropertiesComponent greenareaFormPropertiesComponent = (GreenareaFormPropertiesComponent) greenareaFormPropertiesForm
                        .getComponent(1);
                FormProperty formProperty = greenareaFormPropertiesComponent.getFormProperties().get(0);
                FormPropertyRenderer formPropertyRenderer = greenareaFormPropertiesComponent
                        .getRenderer(formProperty);
                greenareaFormPropertiesComponent.getForm()
                        .getField(greenareaFormPropertiesComponent.getFormProperties().get(0).getId())
                        .setValue(formPropertyRenderer.getPropertyLabel(formProperty) + " "
                                + selectable.getValue());
            }
        }
    });
    first.setStyleName(Reindeer.BUTTON_LINK);
    previous.setStyleName(Reindeer.BUTTON_LINK);
    next.setStyleName(Reindeer.BUTTON_LINK);
    last.setStyleName(Reindeer.BUTTON_LINK);

    itemsPerPageLabel.addStyleName("pagedtable-itemsperpagecaption");
    itemsPerPageSelect.addStyleName("pagedtable-itemsperpagecombobox");
    pageLabel.addStyleName("pagedtable-pagecaption");
    currentPageTextField.addStyleName("pagedtable-pagefield");
    separatorLabel.addStyleName("pagedtable-separator");
    totalPagesLabel.addStyleName("pagedtable-total");
    first.addStyleName("pagedtable-first");
    previous.addStyleName("pagedtable-previous");
    next.addStyleName("pagedtable-next");
    last.addStyleName("pagedtable-last");

    itemsPerPageLabel.addStyleName("pagedtable-label");
    itemsPerPageSelect.addStyleName("pagedtable-combobox");
    pageLabel.addStyleName("pagedtable-label");
    currentPageTextField.addStyleName("pagedtable-label");
    separatorLabel.addStyleName("pagedtable-label");
    totalPagesLabel.addStyleName("pagedtable-label");
    first.addStyleName("pagedtable-button");
    previous.addStyleName("pagedtable-button");
    next.addStyleName("pagedtable-button");
    last.addStyleName("pagedtable-button");

    pageSize.addComponent(itemsPerPageLabel);
    pageSize.addComponent(itemsPerPageSelect);
    pageSize.setComponentAlignment(itemsPerPageLabel, Alignment.MIDDLE_LEFT);
    pageSize.setComponentAlignment(itemsPerPageSelect, Alignment.MIDDLE_LEFT);
    pageSize.setSpacing(true);
    pageManagement.addComponent(first);
    pageManagement.addComponent(previous);
    pageManagement.addComponent(pageLabel);
    pageManagement.addComponent(currentPageTextField);
    pageManagement.addComponent(separatorLabel);
    pageManagement.addComponent(totalPagesLabel);
    pageManagement.addComponent(next);
    pageManagement.addComponent(last);
    pageManagement.setComponentAlignment(first, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(previous, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(pageLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(currentPageTextField, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(separatorLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(totalPagesLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(next, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(last, Alignment.MIDDLE_LEFT);
    pageManagement.setWidth(null);
    pageManagement.setSpacing(true);
    controlBar.addComponent(pageSize);
    controlBar.addComponent(pageManagement);
    controlBar.setComponentAlignment(pageManagement, Alignment.MIDDLE_CENTER);
    controlBar.setWidth("100%");
    controlBar.setExpandRatio(pageSize, 1);
    addListener(new PageChangeListener() {
        public void pageChanged(PagedTableChangeEvent event) {
            first.setEnabled(container.getStartIndex() > 0);
            previous.setEnabled(container.getStartIndex() > 0);
            next.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
            last.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
            currentPageTextField.setValue(String.valueOf(getCurrentPage()));
            totalPagesLabel.setValue(getTotalAmountOfPages());
            itemsPerPageSelect.setValue(String.valueOf(getPageLength()));
        }
    });
    controlBar.setStyleName("pagination");
    return controlBar;
}

From source file:lu.uni.lassy.excalibur.examples.icrash.dev.web.java.views.AdminAuthView.java

License:Open Source License

public AdminAuthView() {

    setSizeFull();//from  ww  w.ja  va  2 s  .c o  m

    VerticalLayout header = new VerticalLayout();
    header.setSizeFull();

    HorizontalLayout content = new HorizontalLayout();
    content.setSizeFull();

    addComponents(header, content);
    setExpandRatio(header, 1);
    setExpandRatio(content, 6);

    welcomeText.setValue("<h1>Welcome to the iCrash Administrator console!</h1>");
    welcomeText.setContentMode(ContentMode.HTML);
    welcomeText.setSizeUndefined();
    header.addComponent(welcomeText);
    header.setComponentAlignment(welcomeText, Alignment.MIDDLE_CENTER);

    Panel controlPanel = new Panel("Administrator control panel");
    controlPanel.setSizeUndefined();

    Panel addCoordPanel = new Panel("Create a new coordinator");
    addCoordPanel.setSizeUndefined();

    Panel messagesPanel = new Panel("Administrator messages");
    messagesPanel.setWidth("580px");

    Table adminMessagesTable = new Table();

    adminMessagesTable.setContainerDataSource(actAdmin.getMessagesDataSource());

    adminMessagesTable.setColumnWidth("inputEvent", 180);
    adminMessagesTable.setSizeFull();

    VerticalLayout controlLayout = new VerticalLayout(controlPanel);
    controlLayout.setSizeFull();
    controlLayout.setMargin(false);
    controlLayout.setComponentAlignment(controlPanel, Alignment.TOP_CENTER);

    VerticalLayout coordOperationsLayout = new VerticalLayout(addCoordPanel);
    coordOperationsLayout.setSizeFull();
    coordOperationsLayout.setMargin(false);
    coordOperationsLayout.setComponentAlignment(addCoordPanel, Alignment.TOP_CENTER);

    /******************************************/
    coordOperationsLayout.setVisible(true); // main layout in the middle
    addCoordPanel.setVisible(false); // ...which contains the panel "Create a new coordinator"
    /******************************************/

    HorizontalLayout messagesExternalLayout = new HorizontalLayout(messagesPanel);
    VerticalLayout messagesInternalLayout = new VerticalLayout(adminMessagesTable);

    messagesExternalLayout.setSizeFull();
    messagesExternalLayout.setMargin(false);
    messagesExternalLayout.setComponentAlignment(messagesPanel, Alignment.TOP_CENTER);

    messagesInternalLayout.setMargin(false);
    messagesInternalLayout.setSizeFull();
    messagesInternalLayout.setComponentAlignment(adminMessagesTable, Alignment.TOP_CENTER);

    messagesPanel.setContent(messagesInternalLayout);

    TextField idCoordAdd = new TextField();
    TextField loginCoord = new TextField();
    PasswordField pwdCoord = new PasswordField();

    Label idCaptionAdd = new Label("ID");
    Label loginCaption = new Label("Login");
    Label pwdCaption = new Label("Password");

    idCaptionAdd.setSizeUndefined();
    idCoordAdd.setSizeUndefined();

    loginCaption.setSizeUndefined();
    loginCoord.setSizeUndefined();

    pwdCaption.setSizeUndefined();
    pwdCoord.setSizeUndefined();

    Button validateNewCoord = new Button("Validate");
    validateNewCoord.setClickShortcut(KeyCode.ENTER);
    validateNewCoord.setStyleName(ValoTheme.BUTTON_PRIMARY);

    GridLayout addCoordinatorLayout = new GridLayout(2, 4);
    addCoordinatorLayout.setSpacing(true);
    addCoordinatorLayout.setMargin(true);
    addCoordinatorLayout.setSizeFull();

    addCoordinatorLayout.addComponents(idCaptionAdd, idCoordAdd, loginCaption, loginCoord, pwdCaption,
            pwdCoord);

    addCoordinatorLayout.addComponent(validateNewCoord, 1, 3);

    addCoordinatorLayout.setComponentAlignment(idCaptionAdd, Alignment.MIDDLE_LEFT);
    addCoordinatorLayout.setComponentAlignment(idCoordAdd, Alignment.MIDDLE_LEFT);
    addCoordinatorLayout.setComponentAlignment(loginCaption, Alignment.MIDDLE_LEFT);
    addCoordinatorLayout.setComponentAlignment(loginCoord, Alignment.MIDDLE_LEFT);
    addCoordinatorLayout.setComponentAlignment(pwdCaption, Alignment.MIDDLE_LEFT);
    addCoordinatorLayout.setComponentAlignment(pwdCoord, Alignment.MIDDLE_LEFT);

    addCoordPanel.setContent(addCoordinatorLayout);

    content.addComponents(controlLayout, coordOperationsLayout, messagesExternalLayout);
    content.setComponentAlignment(messagesExternalLayout, Alignment.TOP_CENTER);
    content.setComponentAlignment(controlLayout, Alignment.TOP_CENTER);
    content.setComponentAlignment(messagesExternalLayout, Alignment.TOP_CENTER);

    content.setExpandRatio(controlLayout, 20);
    content.setExpandRatio(coordOperationsLayout, 10);
    content.setExpandRatio(messagesExternalLayout, 28);

    Button addCoordinator = new Button("Add coordinator");
    Button deleteCoordinator = new Button("Delete coordinator");

    addCoordinator.addStyleName(ValoTheme.BUTTON_HUGE);
    deleteCoordinator.addStyleName(ValoTheme.BUTTON_HUGE);
    logoutBtn.addStyleName(ValoTheme.BUTTON_HUGE);

    VerticalLayout buttons = new VerticalLayout();

    buttons.setMargin(true);
    buttons.setSpacing(true);
    buttons.setSizeFull();

    buttons.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);

    controlPanel.setContent(buttons);

    buttons.addComponents(addCoordinator, deleteCoordinator, logoutBtn);

    /******* DELETE COORDINATOR PANEL BEGIN *********/
    Label idCaptionDel = new Label("ID");
    TextField idCoordDel = new TextField();

    Panel delCoordPanel = new Panel("Delete a coordinator");

    coordOperationsLayout.addComponent(delCoordPanel);
    delCoordPanel.setVisible(false);

    coordOperationsLayout.setComponentAlignment(delCoordPanel, Alignment.TOP_CENTER);
    delCoordPanel.setSizeUndefined();

    GridLayout delCoordinatorLayout = new GridLayout(2, 2);
    delCoordinatorLayout.setSpacing(true);
    delCoordinatorLayout.setMargin(true);
    delCoordinatorLayout.setSizeFull();

    Button deleteCoordBtn = new Button("Delete");
    deleteCoordBtn.setClickShortcut(KeyCode.ENTER);
    deleteCoordBtn.setStyleName(ValoTheme.BUTTON_PRIMARY);

    delCoordinatorLayout.addComponents(idCaptionDel, idCoordDel);

    delCoordinatorLayout.addComponent(deleteCoordBtn, 1, 1);

    delCoordinatorLayout.setComponentAlignment(idCaptionDel, Alignment.MIDDLE_LEFT);
    delCoordinatorLayout.setComponentAlignment(idCoordDel, Alignment.MIDDLE_LEFT);

    delCoordPanel.setContent(delCoordinatorLayout);
    /******* DELETE COORDINATOR PANEL END *********/

    /************************************************* MAIN BUTTONS LOGIC BEGIN *************************************************/

    addCoordinator.addClickListener(event -> {
        if (!addCoordPanel.isVisible()) {
            delCoordPanel.setVisible(false);
            addCoordPanel.setVisible(true);
            idCoordAdd.focus();
        } else
            addCoordPanel.setVisible(false);
    });

    deleteCoordinator.addClickListener(event -> {
        if (!delCoordPanel.isVisible()) {
            addCoordPanel.setVisible(false);
            delCoordPanel.setVisible(true);
            idCoordDel.focus();
        } else
            delCoordPanel.setVisible(false);
    });

    /************************************************* MAIN BUTTONS LOGIC END *************************************************/

    /************************************************* ADD COORDINATOR FORM LOGIC BEGIN *************************************************/
    validateNewCoord.addClickListener(event -> {

        String currentURL = Page.getCurrent().getLocation().toString();
        int strIndexCreator = currentURL.lastIndexOf(AdministratorLauncher.adminPageName);
        String iCrashURL = currentURL.substring(0, strIndexCreator);
        String googleShebang = "#!";
        String coordURL = iCrashURL + CoordinatorServlet.coordinatorsName + googleShebang;

        try {
            sys.oeAddCoordinator(new DtCoordinatorID(new PtString(idCoordAdd.getValue())),
                    new DtLogin(new PtString(loginCoord.getValue())),
                    new DtPassword(new PtString(pwdCoord.getValue())));

            // open new browser tab with the newly created coordinator console...
            // "_blank" instructs the browser to open a new tab instead of a new window...
            // unhappily not all browsers interpret it correctly,
            // some versions of some browsers might still open a new window instead (notably Firefox)!
            Page.getCurrent().open(coordURL + idCoordAdd.getValue(), "_blank");

        } catch (Exception e) {
            e.printStackTrace();
        }

        idCoordAdd.setValue("");
        loginCoord.setValue("");
        pwdCoord.setValue("");

        idCoordAdd.focus();
    });
    /************************************************* ADD COORDINATOR FORM LOGIC END *************************************************/
    /************************************************* DELETE COORDINATOR FORM LOGIC BEGIN *************************************************/
    deleteCoordBtn.addClickListener(event -> {
        IcrashSystem sys = IcrashSystem.getInstance();

        try {
            sys.oeDeleteCoordinator(new DtCoordinatorID(new PtString(idCoordDel.getValue())));
        } catch (Exception e) {
            e.printStackTrace();
        }

        idCoordDel.setValue("");
        idCoordDel.focus();
    });
    /************************************************* DELETE COORDINATOR FORM LOGIC END *************************************************/
}

From source file:lu.uni.lassy.excalibur.examples.icrash.dev.web.java.views.CoordMobileAuthView.java

License:Open Source License

public CoordMobileAuthView(String CoordID) {

    CtCoordinator ctCoordinator = (CtCoordinator) sys
            .getCtCoordinator(new DtCoordinatorID(new PtString(CoordID)));
    ActCoordinator actCoordinator = sys.getActCoordinator(ctCoordinator);

    actCoordinator.setActorUI(UI.getCurrent());
    env.setActCoordinator(actCoordinator.getName(), actCoordinator);

    IcrashSystem.assCtAuthenticatedActAuthenticated.replace(ctCoordinator, actCoordinator);
    IcrashSystem.assCtCoordinatorActCoordinator.replace(ctCoordinator, actCoordinator);

    thisCoordID = CoordID;/*  w  w w  . j  a  v a2s . co m*/

    setResponsive(true);
    setWidth("100%");

    NavigationBar alertsBar = new NavigationBar();
    VerticalComponentGroup alertsContent = new VerticalComponentGroup();
    alertsContent.setWidth("100%");
    alertsContent.setResponsive(true);

    HorizontalLayout alertButtons1 = new HorizontalLayout();
    HorizontalLayout alertButtons2 = new HorizontalLayout();
    //alertButtons.setMargin(true);
    //alertButtons.setSpacing(true);

    alertsBar.setCaption("Coordinator " + ctCoordinator.login.toString());
    // NavigationButton logoutBtn1 = new NavigationButton("Logout");
    Button logoutBtn1 = new Button("Logout");
    alertsBar.setRightComponent(logoutBtn1);

    alertsTable = new Grid();
    alertsTable.setContainerDataSource(actCoordinator.getAlertsContainer());
    alertsTable.setColumnOrder("ID", "date", "time", "longitude", "latitude", "comment", "status");
    alertsTable.setSelectionMode(SelectionMode.SINGLE);

    alertsTable.setWidth("100%");
    alertsTable.setResponsive(true);
    //alertsTable.setSizeUndefined();

    alertsTable.setImmediate(true);

    Grid inputEventsTable1 = new Grid();
    inputEventsTable1.setContainerDataSource(actCoordinator.getMessagesDataSource());
    inputEventsTable1.setWidth("100%");
    inputEventsTable1.setResponsive(true);

    alertsContent.addComponents(alertsBar, alertButtons1, alertButtons2, alertsTable, inputEventsTable1);

    Tab alertsTab = this.addTab(alertsContent);
    alertsTab.setCaption("Alerts");

    alertStatus = new NativeSelect();
    alertStatus.setNullSelectionAllowed(false);
    alertStatus.addItems("Pending", "Valid", "Invalid");
    alertStatus.setImmediate(true);

    alertStatus.select("Pending");

    Button validateAlertBtn = new Button("Validate");
    Button invalidateAlertBtn = new Button("Invalidate");
    Button getAlertsSetBtn = new Button("Get alerts set");

    validateAlertBtn.setImmediate(true);
    invalidateAlertBtn.setImmediate(true);

    validateAlertBtn.addClickListener(event -> {
        AlertBean selectedAlertBean = (AlertBean) alertsTable.getSelectedRow();

        Integer thisAlertID = new Integer(selectedAlertBean.getID());
        PtBoolean res;
        res = sys.oeValidateAlert(new DtAlertID(new PtString(thisAlertID.toString())));
    });

    invalidateAlertBtn.addClickListener(event -> {
        AlertBean selectedAlertBean = (AlertBean) alertsTable.getSelectedRow();
        Integer thisAlertID = new Integer(selectedAlertBean.getID());
        PtBoolean res;
        res = sys.oeInvalidateAlert(new DtAlertID(new PtString(thisAlertID.toString())));
    });

    getAlertsSetBtn.addClickListener(event -> {
        if (alertStatus.getValue().toString().equals("Pending"))
            actCoordinator.oeGetAlertsSet(EtAlertStatus.pending);
        else if (alertStatus.getValue().toString().equals("Valid"))
            actCoordinator.oeGetAlertsSet(EtAlertStatus.valid);
        else if (alertStatus.getValue().toString().equals("Invalid"))
            actCoordinator.oeGetAlertsSet(EtAlertStatus.invalid);
    });

    alertButtons1.addComponents(validateAlertBtn, invalidateAlertBtn);
    alertButtons2.addComponents(getAlertsSetBtn, alertStatus);

    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////

    NavigationBar crisesBar = new NavigationBar();
    VerticalComponentGroup crisesContent = new VerticalComponentGroup();
    crisesContent.setWidth("100%");
    crisesContent.setResponsive(true);

    HorizontalLayout crisesButtons1 = new HorizontalLayout();
    HorizontalLayout crisesButtons2 = new HorizontalLayout();
    crisesBar.setCaption("Coordinator " + ctCoordinator.login.toString());
    //NavigationButton logoutBtn2 = new NavigationButton("Logout");
    Button logoutBtn2 = new Button("Logout");
    crisesBar.setRightComponent(logoutBtn2);

    crisesTable = new Grid();
    crisesTable.setContainerDataSource(actCoordinator.getCrisesContainer());
    crisesTable.setColumnOrder("ID", "date", "time", "type", "longitude", "latitude", "comment", "status");
    crisesTable.setSelectionMode(SelectionMode.SINGLE);

    crisesTable.setWidth("100%");
    //crisesTable.setSizeUndefined();

    crisesTable.setImmediate(true);
    crisesTable.setResponsive(true);

    Grid inputEventsTable2 = new Grid();
    inputEventsTable2.setContainerDataSource(actCoordinator.getMessagesDataSource());
    inputEventsTable2.setWidth("100%");
    inputEventsTable2.setResponsive(true);

    crisesContent.addComponents(crisesBar, crisesButtons1, crisesButtons2, crisesTable, inputEventsTable2);

    Tab crisesTab = this.addTab(crisesContent);
    crisesTab.setCaption("Crises");

    Button handleCrisesBtn = new Button("Handle");
    Button reportOnCrisisBtn = new Button("Report");
    Button changeCrisisStatusBtn = new Button("Status");
    Button closeCrisisBtn = new Button("Close");
    Button getCrisesSetBtn = new Button("Get crises set");
    crisesStatus = new NativeSelect();

    handleCrisesBtn.setImmediate(true);
    reportOnCrisisBtn.setImmediate(true);
    changeCrisisStatusBtn.setImmediate(true);
    closeCrisisBtn.setImmediate(true);
    getCrisesSetBtn.setImmediate(true);
    crisesStatus.setImmediate(true);

    crisesStatus.addItems("Pending", "Handled", "Solved", "Closed");
    crisesStatus.setNullSelectionAllowed(false);
    crisesStatus.select("Pending");

    crisesButtons1.addComponents(handleCrisesBtn, reportOnCrisisBtn, changeCrisisStatusBtn);
    crisesButtons2.addComponents(closeCrisisBtn, getCrisesSetBtn, crisesStatus);

    ////////////////////////////////////////

    Window reportCrisisSubWindow = new Window();
    reportCrisisSubWindow.setClosable(false);
    reportCrisisSubWindow.setResizable(false);
    reportCrisisSubWindow.setResponsive(true);
    VerticalLayout reportLayout = new VerticalLayout();
    reportLayout.setMargin(true);
    reportLayout.setSpacing(true);
    reportCrisisSubWindow.setContent(reportLayout);
    TextField crisisID = new TextField();
    TextField reportText = new TextField();
    HorizontalLayout buttonsLayout = new HorizontalLayout();
    Button reportCrisisBtn = new Button("Report");
    reportCrisisBtn.setClickShortcut(KeyCode.ENTER);
    reportCrisisBtn.addStyleName(ValoTheme.BUTTON_PRIMARY);
    Button cancelBtn = new Button("Cancel");
    buttonsLayout.addComponents(reportCrisisBtn, cancelBtn);
    buttonsLayout.setSpacing(true);
    reportLayout.addComponents(crisisID, reportText, buttonsLayout);

    cancelBtn.addClickListener(event -> {
        reportCrisisSubWindow.close();
        reportText.clear();
    });

    reportCrisisBtn.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());
        actCoordinator.oeReportOnCrisis(new DtCrisisID(new PtString(thisCrisisID.toString())),
                new DtComment(new PtString(reportText.getValue())));

        reportCrisisSubWindow.close();
        reportText.clear();
    });

    ////////////////////////////////////////

    Window changeCrisisStatusSubWindow = new Window();
    changeCrisisStatusSubWindow.setClosable(false);
    changeCrisisStatusSubWindow.setResizable(false);
    changeCrisisStatusSubWindow.setResponsive(true);
    VerticalLayout statusLayout = new VerticalLayout();
    statusLayout.setMargin(true);
    statusLayout.setSpacing(true);
    changeCrisisStatusSubWindow.setContent(statusLayout);
    TextField crisisID1 = new TextField();

    NativeSelect crisisStatus = new NativeSelect("crisis status");
    crisisStatus.addItems("Pending", "Handled", "Solved", "Closed");
    crisisStatus.setNullSelectionAllowed(false);
    crisisStatus.select("Pending");

    HorizontalLayout buttonsLayout1 = new HorizontalLayout();
    Button changeCrisisStatusBtn1 = new Button("Change status");
    changeCrisisStatusBtn1.setClickShortcut(KeyCode.ENTER);
    changeCrisisStatusBtn1.addStyleName(ValoTheme.BUTTON_PRIMARY);
    Button cancelBtn1 = new Button("Cancel");
    buttonsLayout1.addComponents(changeCrisisStatusBtn1, cancelBtn1);
    buttonsLayout1.setSpacing(true);
    statusLayout.addComponents(crisisID1, crisisStatus, buttonsLayout1);

    cancelBtn1.addClickListener(event -> changeCrisisStatusSubWindow.close());

    changeCrisisStatusBtn1.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());

        EtCrisisStatus statusToPut = null;

        if (crisisStatus.getValue().toString().equals("Pending"))
            statusToPut = EtCrisisStatus.pending;
        if (crisisStatus.getValue().toString().equals("Handled"))
            statusToPut = EtCrisisStatus.handled;
        if (crisisStatus.getValue().toString().equals("Solved"))
            statusToPut = EtCrisisStatus.solved;
        if (crisisStatus.getValue().toString().equals("Closed"))
            statusToPut = EtCrisisStatus.closed;

        PtBoolean res = actCoordinator.oeSetCrisisStatus(new DtCrisisID(new PtString(thisCrisisID.toString())),
                statusToPut);

        changeCrisisStatusSubWindow.close();
    });

    ////////////////////////////////////////

    handleCrisesBtn.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());
        PtBoolean res = actCoordinator
                .oeSetCrisisHandler(new DtCrisisID(new PtString(thisCrisisID.toString())));
    });

    reportOnCrisisBtn.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());
        reportCrisisSubWindow.center();
        crisisID.setValue(thisCrisisID.toString());
        crisisID.setEnabled(false);
        reportText.focus();
        UI.getCurrent().addWindow(reportCrisisSubWindow);
    });

    changeCrisisStatusBtn.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());
        changeCrisisStatusSubWindow.center();
        crisisID1.setValue(thisCrisisID.toString());
        crisisID1.setEnabled(false);
        crisisStatus.focus();
        UI.getCurrent().addWindow(changeCrisisStatusSubWindow);
    });

    closeCrisisBtn.addClickListener(event -> {
        CrisisBean selectedCrisisBean = (CrisisBean) crisesTable.getSelectedRow();
        Integer thisCrisisID = new Integer(selectedCrisisBean.getID());
        PtBoolean res = actCoordinator.oeCloseCrisis(new DtCrisisID(new PtString(thisCrisisID.toString())));
    });

    getCrisesSetBtn.addClickListener(event -> {
        if (crisesStatus.getValue().toString().equals("Closed"))
            actCoordinator.oeGetCrisisSet(EtCrisisStatus.closed);
        if (crisesStatus.getValue().toString().equals("Handled"))
            actCoordinator.oeGetCrisisSet(EtCrisisStatus.handled);
        if (crisesStatus.getValue().toString().equals("Solved"))
            actCoordinator.oeGetCrisisSet(EtCrisisStatus.solved);
        if (crisesStatus.getValue().toString().equals("Pending"))
            actCoordinator.oeGetCrisisSet(EtCrisisStatus.pending);
    });

    ClickListener logoutAction = event -> {
        PtBoolean res;
        try {
            res = actCoordinator.oeLogout();
            if (res.getValue()) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page.getCurrent().reload();
    };

    logoutBtn1.addClickListener(logoutAction);
    logoutBtn2.addClickListener(logoutAction);
}

From source file:module.pandabox.presentation.PandaBox.java

License:Open Source License

private static Layout getSystemErrorTester() {
    VerticalLayout layout = new VerticalLayout();
    layout.setSpacing(true);/*from  w w  w  .  j a  va 2s  .  c  om*/

    Button button = new Button("click me to show error", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            throw new Error("badabum");
        }
    });
    layout.addComponent(button);

    final TextField txtCaption = new TextField("caption");
    txtCaption.setValue("Notification Caption");

    final TextField txtMessage = new TextField("message");
    txtMessage.setValue("Notification Message");

    final TextField txtDelay = new TextField("delay (msec)");
    txtDelay.setValue("2000");

    final Select position = new Select("Position");
    position.setNullSelectionAllowed(false);

    final int[] positions = { Window.Notification.POSITION_BOTTOM_LEFT,
            Window.Notification.POSITION_BOTTOM_RIGHT, Window.Notification.POSITION_CENTERED,
            Window.Notification.POSITION_CENTERED_BOTTOM, Window.Notification.POSITION_CENTERED_TOP,
            Window.Notification.POSITION_TOP_LEFT, Window.Notification.POSITION_TOP_RIGHT };

    final String[] posLabels = { "BOTTOM_LEFT", " BOTTOM_RIGHT", "CENTERED", "CENTERED_BOTTOM", "CENTERED_TOP",
            "TOP_LEFT", "TOP_RIGHT" };

    for (int i = 0; i < positions.length; i++) {
        int pos = positions[i];
        position.addItem(pos);
        position.setItemCaption(pos, posLabels[i]);
    }

    position.select(position.getContainerDataSource().getItem(0));

    layout.addComponent(txtCaption);
    layout.addComponent(txtMessage);
    layout.addComponent(txtDelay);
    layout.addComponent(position);

    HorizontalLayout hl = new HorizontalLayout();
    hl.setSpacing(true);

    final int[] types = { Window.Notification.TYPE_ERROR_MESSAGE, Window.Notification.TYPE_HUMANIZED_MESSAGE,
            Window.Notification.TYPE_TRAY_NOTIFICATION, Window.Notification.TYPE_WARNING_MESSAGE };
    final String[] labels = { "error", "humanized", "tray", "warning" };
    for (int i = 0; i < types.length; i++) {
        final int type = types[i];
        Button btNotif = new Button(labels[i], new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                Window.Notification notif = new Window.Notification((String) txtCaption.getValue(),
                        (String) txtMessage.getValue(), type);
                notif.setPosition((Integer) position.getValue());
                notif.setDelayMsec(Integer.parseInt((String) txtDelay.getValue()));
                event.getButton().getApplication().getMainWindow().showNotification(notif);
            }
        });
        hl.addComponent(btNotif);
    }

    layout.addComponent(hl);
    return layout;
}

From source file:module.pandabox.presentation.StyleController.java

License:Open Source License

public StyleController(final Component component, String... styles) {
    super();/*from  w  w w  .jav a 2 s  . com*/
    setCaption("Style");
    setSpacing(true);

    OptionGroup options = new OptionGroup();
    addComponent(options);
    options.setImmediate(true);
    options.setMultiSelect(true);
    for (String style : styles) {
        options.addItem(style);
    }
    options.addListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent event) {
            Set<String> value = (Set<String>) event.getProperty().getValue();
            List<String> current = Arrays.asList(component.getStyleName().split(" "));
            for (String style : value) {
                if (!current.contains(style)) {
                    component.addStyleName(style);
                }
            }
            for (String style : current) {
                if (!value.contains(style)) {
                    component.removeStyleName(style);
                }
            }
        }
    });

    HorizontalLayout custom = new HorizontalLayout();
    addComponent(custom);
    custom.setSpacing(true);
    final TextField txtStyle = new TextField();
    custom.addComponent(txtStyle);
    Button btApplyStyle = new Button("Apply Style", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            final String value = (String) txtStyle.getValue();
            if (value != null) {
                component.addStyleName(value);
            }
        }
    });
    custom.addComponent(btApplyStyle);
}

From source file:net.antoinecomte.regex.RegExTesterApplication.java

License:Apache License

@Override
public void init() {
    setTheme("chameleon");
    final TextField text = new TextField();

    final TextField regex = new TextField();

    Panel mainPanel = new Panel("Simple Java regular expression tool ");
    mainPanel.setWidth("460px");
    VerticalLayout mainPanelLayout = new VerticalLayout();
    mainPanelLayout.setSpacing(true);/*from w  ww  . ja  v a2s.  co m*/
    mainPanelLayout.setMargin(true);
    mainPanel.setContent(mainPanelLayout);
    regex.setCaption("Regular Expression");
    regex.setWidth("400px");
    regex.addStyleName("big");
    regex.setInputPrompt("enter a regular expression here");
    regex.setTextChangeEventMode(TextChangeEventMode.TIMEOUT);
    regex.setImmediate(true);

    text.setCaption("Test input");
    text.setInputPrompt("Enter a test string here");
    text.setTextChangeEventMode(TextChangeEventMode.TIMEOUT);
    text.setImmediate(true);
    text.setWidth("400px");
    text.addStyleName("big");
    result.setSizeUndefined();
    result.setWidth("460px");
    result.setStyleName("light");
    result.setVisible(false);

    regex.addListener(new TextChangeListener() {
        private static final long serialVersionUID = 7783333579512074097L;

        @Override
        public void textChange(TextChangeEvent event) {
            showResult(event.getText(), text.getValue().toString());

        }
    });
    text.addListener(new TextChangeListener() {
        private static final long serialVersionUID = -2294521048305268959L;

        @Override
        public void textChange(TextChangeEvent event) {
            showResult(regex.getValue().toString(), event.getText());
        }
    });
    Window mainWindow = new Window();
    VerticalLayout mainLayout = new VerticalLayout();
    mainLayout.setSpacing(true);
    mainLayout.setMargin(true);
    mainWindow.setContent(mainLayout);
    mainWindow.addComponent(mainPanel);
    mainPanel.addComponent(regex);
    mainPanel.addComponent(text);
    mainWindow.addComponent(result);
    setMainWindow(mainWindow);
}

From source file:net.larbig.ScriptRunnerApplication.java

License:Apache License

@Override
public void init() {
    window = new Window("Scriptrunner");
    setMainWindow(window);/*from w w w  .  j  a  va 2 s . c  o m*/

    VerticalLayout layout = new VerticalLayout();
    final TextField tfDriver = new TextField("Driver");
    tfDriver.setWidth(300, Sizeable.UNITS_PIXELS);
    tfDriver.setValue("com.mysql.jdbc.Driver");
    final TextField tfURL = new TextField("URL");
    tfURL.setWidth(300, Sizeable.UNITS_PIXELS);
    tfURL.setValue("jdbc:mysql://mysql.host.net:3306/datenbank");
    final TextField tfUser = new TextField("User");
    tfUser.setWidth(300, Sizeable.UNITS_PIXELS);
    final TextField tfPasswort = new TextField("Password");
    tfPasswort.setWidth(300, Sizeable.UNITS_PIXELS);
    final TextArea taSQL = new TextArea("SQL");
    taSQL.setWidth(300, Sizeable.UNITS_PIXELS);
    taSQL.setHeight(150, Sizeable.UNITS_PIXELS);

    Button button = new Button("Execute");
    button.addListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {

            try {
                Class.forName((String) tfDriver.getValue()).newInstance();
                Connection con = DriverManager.getConnection(tfURL.getValue().toString(),
                        tfUser.getValue().toString(), tfPasswort.getValue().toString());
                ScriptRunner runner = new ScriptRunner(con, false, true);
                Reader r = new StringReader(taSQL.getValue().toString());
                runner.runScript(r);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

    layout.addComponent(tfDriver);
    layout.addComponent(tfURL);
    layout.addComponent(tfUser);
    layout.addComponent(tfPasswort);
    layout.addComponent(taSQL);
    layout.addComponent(button);
    window.addComponent(layout);

}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.admin.AdminScreenProvider.java

License:Apache License

private Component getEmailSettingTab() {
    VerticalLayout s2 = new VerticalLayout();
    HorizontalSplitPanel split2 = new HorizontalSplitPanel();
    s2.addComponent(split2);/*www .ja v  a 2  s .c  o  m*/
    Tree sTree2 = new Tree(TRANSLATOR.translate("general.email.settings"));
    sTree2.addValueChangeListener((Property.ValueChangeEvent event) -> {
        if (sTree2.getValue() instanceof VmSetting) {
            VmSetting vmSetting = (VmSetting) sTree2.getValue();
            split2.setSecondComponent(displaySetting(vmSetting, !vmSetting.getSetting().equals("mail.enable")));
        }
    });
    split2.setFirstComponent(sTree2);
    VMSettingServer.getSettings().forEach(s -> {
        if (s.getSetting().startsWith("mail")) {
            sTree2.addItem(s);
            sTree2.setChildrenAllowed(s, false);
            sTree2.setItemCaption(s, TRANSLATOR.translate(s.getSetting()));
        }
    });
    Button testEmail = new Button(TRANSLATOR.translate("general.email.settings.test"), listener -> {
        //Show a window to test email settings
        VMWindow w = new VMWindow(TRANSLATOR.translate("general.email.settings.test"));
        VerticalLayout vl = new VerticalLayout();
        TextField to = new TextField(TRANSLATOR.translate("general.email.to"));
        TextField from = new TextField(TRANSLATOR.translate("general.email.from"));
        TextField subject = new TextField(TRANSLATOR.translate("general.email.subject"));
        TextArea mess = new TextArea(TRANSLATOR.translate("general.email.message"));
        mess.setSizeFull();
        TextArea output = new TextArea(TRANSLATOR.translate("general.output"));
        output.setReadOnly(true);
        output.setSizeFull();
        Button send = new Button(TRANSLATOR.translate("general.email.send"), l -> {
            try {
                Lookup.getDefault().lookup(IEmailManager.class).sendEmail(to.getValue(), null, from.getValue(),
                        subject.getValue(), mess.getValue());
                output.setValue(TRANSLATOR.translate("general.email.settings.test.success"));
                //Successful, update the enable setting.
                VMSettingServer enable = new VMSettingServer("mail.enable");
                enable.setBoolVal(true);
                enable.write2DB();
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, null, ex);
                StringWriter sw = new StringWriter();
                ex.printStackTrace(new PrintWriter(sw));
                output.setReadOnly(false);
                output.setValue(sw.toString());
                output.setReadOnly(true);
            }
        });
        vl.addComponent(to);
        vl.addComponent(from);
        vl.addComponent(subject);
        vl.addComponent(mess);
        vl.addComponent(send);
        vl.addComponent(output);
        w.setContent(vl);
        w.setHeight(75, Sizeable.Unit.PERCENTAGE);
        w.setWidth(75, Sizeable.Unit.PERCENTAGE);
        ValidationManagerUI.getInstance().addWindow(w);
    });
    s2.addComponent(testEmail);
    return s2;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.component.RequirementComponent.java

License:Apache License

private void init() {
    FormLayout layout = new FormLayout();
    setContent(layout);//from  w  ww  . j a  va  2s. com
    addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
    BeanFieldGroup binder = new BeanFieldGroup(req.getClass());
    binder.setItemDataSource(req);
    TextField id = (TextField) binder.buildAndBind(TRANSLATOR.translate("requirement.id"), "uniqueId",
            TextField.class);
    id.setNullRepresentation("");
    layout.addComponent(id);
    TextArea desc = (TextArea) binder.buildAndBind(TRANSLATOR.translate("general.description"), "description",
            TextArea.class);
    desc.setNullRepresentation("");
    desc.setSizeFull();
    layout.addComponent(desc);
    TextArea notes = (TextArea) binder.buildAndBind(TRANSLATOR.translate("general.notes"), "notes",
            TextArea.class);
    notes.setNullRepresentation("");
    notes.setSizeFull();
    layout.addComponent(notes);
    if (req.getParentRequirementId() != null) {
        TextField tf = new TextField(TRANSLATOR.translate("general.parent"));
        tf.setValue(req.getParentRequirementId().getUniqueId());
        tf.setReadOnly(true);
        layout.addComponent(tf);
    }
    if (req.getRequirementList() == null) {
        req.setRequirementList(new ArrayList<>());
    }
    if (!req.getRequirementList().isEmpty() && !edit) {
        layout.addComponent(((VMUI) UI.getCurrent()).getDisplayRequirementList(
                TRANSLATOR.translate("related.requirements"), req.getRequirementList()));
    } else if (edit) {
        //Allow user to add children
        AbstractSelect as = ((VMUI) UI.getCurrent()).getRequirementSelectionComponent();
        req.getRequirementList().forEach(sub -> {
            as.select(sub);
        });
        as.addValueChangeListener(event -> {
            Set<Requirement> selected = (Set<Requirement>) event.getProperty().getValue();
            req.getRequirementList().clear();
            selected.forEach(r -> {
                req.getRequirementList().add(r);
            });
        });
        layout.addComponent(as);
    }
    Button cancel = new Button(TRANSLATOR.translate("general.cancel"));
    cancel.addClickListener((Button.ClickEvent event) -> {
        binder.discard();
        if (req.getId() == null) {
            ((VMUI) UI.getCurrent()).displayObject(req.getRequirementSpecNode());
        } else {
            ((VMUI) UI.getCurrent()).displayObject(req, false);
        }
    });
    if (edit) {
        if (req.getId() == null) {
            //Creating a new one
            Button save = new Button(TRANSLATOR.translate("general.save"));
            save.addClickListener((Button.ClickEvent event) -> {
                req.setUniqueId(id.getValue().toString());
                req.setNotes(notes.getValue().toString());
                req.setDescription(desc.getValue().toString());
                req.setRequirementSpecNode((RequirementSpecNode) ((VMUI) UI.getCurrent()).getSelectdValue());
                new RequirementJpaController(DataBaseManager.getEntityManagerFactory()).create(req);
                setVisible(false);
                //Recreate the tree to show the addition
                ((VMUI) UI.getCurrent()).buildProjectTree(req);
                ((VMUI) UI.getCurrent()).displayObject(req, true);
            });
            HorizontalLayout hl = new HorizontalLayout();
            hl.addComponent(save);
            hl.addComponent(cancel);
            layout.addComponent(hl);
        } else {
            //Editing existing one
            Button update = new Button(TRANSLATOR.translate("general.update"));
            update.addClickListener((Button.ClickEvent event) -> {
                try {
                    RequirementServer rs = new RequirementServer(req);
                    rs.setDescription(((TextArea) desc).getValue());
                    rs.setNotes(((TextArea) notes).getValue());
                    rs.setUniqueId(((TextField) id).getValue());
                    ((VMUI) UI.getCurrent()).handleVersioning(rs, () -> {
                        try {
                            rs.write2DB();
                            //Recreate the tree to show the addition
                            ((VMUI) UI.getCurrent()).buildProjectTree(rs.getEntity());
                            ((VMUI) UI.getCurrent()).displayObject(rs.getEntity(), false);
                        } catch (NonexistentEntityException ex) {
                            LOG.log(Level.SEVERE, null, ex);
                            Notification.show(TRANSLATOR.translate("general.error.record.update"),
                                    ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                        } catch (Exception ex) {
                            LOG.log(Level.SEVERE, null, ex);
                            Notification.show(TRANSLATOR.translate("general.error.record.update"),
                                    ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                        }
                    });
                    setVisible(false);
                } catch (VMException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                    Notification.show(TRANSLATOR.translate("general.error.record.update"),
                            ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                }
            });
            HorizontalLayout hl = new HorizontalLayout();
            hl.addComponent(update);
            hl.addComponent(cancel);
            layout.addComponent(hl);
        }
    }
    try {
        //Add a history section
        if (req.getId() != null) {
            List<History> versions = new RequirementServer(req).getHistoryList();
            if (!versions.isEmpty()) {
                layout.addComponent(((VMUI) UI.getCurrent()).createRequirementHistoryTable(
                        TRANSLATOR.translate("general.history"), versions, true));
            }
        }
    } catch (VMException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    binder.setBuffered(true);
    binder.setReadOnly(!edit);
    binder.bindMemberFields(this);
    setSizeFull();
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.component.StepComponent.java

License:Apache License

private void init() {
    FormLayout layout = new FormLayout();
    setContent(layout);/*from   w w  w  .j a v  a  2  s .  c  o m*/
    addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
    BeanFieldGroup binder = new BeanFieldGroup(s.getClass());
    binder.setItemDataSource(s);
    Field<?> sequence = binder.buildAndBind(TRANSLATOR.translate("general.sequence"), "stepSequence");
    layout.addComponent(sequence);
    TextArea text = new TextArea(TRANSLATOR.translate("general.text"));
    text.setConverter(new ByteToStringConverter());
    binder.bind(text, "text");
    layout.addComponent(text);
    TextArea result = new TextArea(TRANSLATOR.translate("expected.result"));
    result.setConverter(new ByteToStringConverter());
    binder.bind(result, "expectedResult");
    layout.addComponent(result);
    Field notes = binder.buildAndBind(TRANSLATOR.translate("general.notes"), "notes", TextArea.class);
    notes.setSizeFull();
    layout.addComponent(notes);
    if (!s.getRequirementList().isEmpty() && !edit) {
        layout.addComponent(((ValidationManagerUI) UI.getCurrent()).getDisplayRequirementList(
                TRANSLATOR.translate("related.requirements"), s.getRequirementList()));
    } else {
        AbstractSelect requirements = ((ValidationManagerUI) UI.getCurrent())
                .getRequirementSelectionComponent();
        //Select the exisitng ones.
        if (s.getRequirementList() != null) {
            s.getRequirementList().forEach((r) -> {
                requirements.select(r);
            });
        }
        requirements.addValueChangeListener(event -> {
            Set<Requirement> selected = (Set<Requirement>) event.getProperty().getValue();
            s.getRequirementList().clear();
            selected.forEach(r -> {
                s.getRequirementList().add(r);
            });
        });
        layout.addComponent(requirements);
    }
    DataEntryComponent fields = new DataEntryComponent(edit);
    binder.bind(fields, "dataEntryList");
    layout.addComponent(fields);
    binder.setReadOnly(edit);
    Button cancel = new Button(TRANSLATOR.translate("general.cancel"));
    cancel.addClickListener((Button.ClickEvent event) -> {
        binder.discard();
        if (s.getStepPK() == null) {
            ((ValidationManagerUI) UI.getCurrent())
                    .displayObject(((ValidationManagerUI) UI.getCurrent()).getTree().getValue());
        } else {
            ((ValidationManagerUI) UI.getCurrent()).displayObject(s, false);
        }
    });
    if (edit) {
        Button add = new Button(TRANSLATOR.translate("add.field"));
        add.addClickListener(listener -> {
            VMWindow w = new VMWindow();
            FormLayout fl = new FormLayout();
            ComboBox newType = new ComboBox(TRANSLATOR.translate("general.type"));
            newType.setNewItemsAllowed(false);
            newType.setTextInputAllowed(false);
            newType.addValidator(new NullValidator(TRANSLATOR.translate("message.required.field.missing")
                    .replaceAll("%f", TRANSLATOR.translate("general.type")), false));
            BeanItemContainer<DataEntryType> container = new BeanItemContainer<>(DataEntryType.class,
                    new DataEntryTypeJpaController(DataBaseManager.getEntityManagerFactory())
                            .findDataEntryTypeEntities());
            newType.setContainerDataSource(container);
            newType.getItemIds().forEach(id -> {
                DataEntryType temp = ((DataEntryType) id);
                newType.setItemCaption(id, TRANSLATOR.translate(temp.getTypeName()));
            });
            fl.addComponent(newType);
            TextField tf = new TextField(TRANSLATOR.translate("general.name"));
            fl.addComponent(tf);
            HorizontalLayout hl = new HorizontalLayout();
            Button a = new Button(TRANSLATOR.translate("general.add"));
            a.addClickListener(l -> {
                DataEntryType det = (DataEntryType) newType.getValue();
                DataEntry de = null;
                switch (det.getId()) {
                case 1:
                    de = DataEntryServer.getStringField(tf.getValue());
                    break;
                case 2:
                    de = DataEntryServer.getNumericField(tf.getValue(), null, null);
                    break;
                case 3:
                    de = DataEntryServer.getBooleanField(tf.getValue());
                    break;
                case 4:
                    de = DataEntryServer.getAttachmentField(tf.getValue());
                    break;
                }
                if (de != null) {
                    s.getDataEntryList().add(de);
                    ((ValidationManagerUI) UI.getCurrent()).displayObject(s);
                }
                UI.getCurrent().removeWindow(w);
            });
            hl.addComponent(a);
            Button c = new Button(TRANSLATOR.translate("general.cancel"));
            c.addClickListener(l -> {
                UI.getCurrent().removeWindow(w);
            });
            hl.addComponent(c);
            fl.addComponent(hl);
            w.setContent(fl);
            UI.getCurrent().addWindow(w);
        });
        if (s.getStepPK() == null) {
            //Creating a new one
            Button save = new Button(TRANSLATOR.translate("general.save"));
            save.addClickListener(listener -> {
                try {
                    s.setExpectedResult(((TextArea) result).getValue().getBytes(encoding));
                    s.setNotes(notes.getValue() == null ? "" : notes.getValue().toString());
                    s.setStepSequence(Integer.parseInt(sequence.getValue().toString()));
                    s.setTestCase((TestCase) ((ValidationManagerUI) UI.getCurrent()).getTree().getValue());
                    s.setText(text.getValue().getBytes(encoding));
                    if (s.getRequirementList() == null) {
                        s.setRequirementList(new ArrayList<>());
                    }
                    new StepJpaController(DataBaseManager.getEntityManagerFactory()).create(s);
                    setVisible(false);
                    //Recreate the tree to show the addition
                    ((ValidationManagerUI) UI.getCurrent()).updateProjectList();
                    ((ValidationManagerUI) UI.getCurrent()).updateScreen();
                    ((ValidationManagerUI) UI.getCurrent()).displayObject(s);
                    ((ValidationManagerUI) UI.getCurrent()).buildProjectTree(s);
                } catch (Exception ex) {
                    LOG.log(Level.SEVERE, null, ex);
                    Notification.show(TRANSLATOR.translate("general.error.record.creation"),
                            ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                }
            });
            HorizontalLayout hl = new HorizontalLayout();
            hl.addComponent(save);
            hl.addComponent(add);
            hl.addComponent(cancel);
            layout.addComponent(hl);
        } else {
            //Editing existing one
            Button update = new Button(TRANSLATOR.translate("general.update"));
            update.addClickListener((Button.ClickEvent event) -> {
                try {
                    s.setExpectedResult(((TextArea) result).getValue().getBytes(encoding));
                    s.setNotes(notes.getValue().toString());
                    s.setStepSequence(Integer.parseInt(sequence.getValue().toString()));
                    s.setText(text.getValue().getBytes(encoding));
                    if (s.getRequirementList() == null) {
                        s.setRequirementList(new ArrayList<>());
                    }
                    ((ValidationManagerUI) UI.getCurrent()).handleVersioning(s, () -> {
                        try {
                            new StepJpaController(DataBaseManager.getEntityManagerFactory()).edit(s);
                        } catch (NonexistentEntityException ex) {
                            LOG.log(Level.SEVERE, null, ex);
                            Notification.show(TRANSLATOR.translate("general.error.record.update"),
                                    ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                        } catch (Exception ex) {
                            LOG.log(Level.SEVERE, null, ex);
                            Notification.show(TRANSLATOR.translate("general.error.record.update"),
                                    ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                        }
                    });
                    ((ValidationManagerUI) UI.getCurrent()).displayObject(s);
                } catch (UnsupportedEncodingException | NumberFormatException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                    Notification.show(TRANSLATOR.translate("general.error.record.creation"),
                            ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
                }
            });
            HorizontalLayout hl = new HorizontalLayout();
            hl.addComponent(update);
            hl.addComponent(add);
            hl.addComponent(cancel);
            layout.addComponent(hl);
        }
    }
    binder.setReadOnly(!edit);
    binder.bindMemberFields(this);
    layout.setSizeFull();
    setSizeFull();
}