Example usage for com.vaadin.ui Button setEnabled

List of usage examples for com.vaadin.ui Button setEnabled

Introduction

In this page you can find the example usage for com.vaadin.ui Button setEnabled.

Prototype

@Override
    public void setEnabled(boolean enabled) 

Source Link

Usage

From source file:org.opennms.features.vaadin.dashboard.dashlets.KscDashletConfigurationWindow.java

License:Open Source License

/**
 * Constructor for instantiating new objects of this class.
 *
 * @param dashletSpec the {@link org.opennms.features.vaadin.dashboard.model.DashletSpec} to be edited
 *//*from   w w  w .  j av  a 2 s  .  co  m*/
public KscDashletConfigurationWindow(DashletSpec dashletSpec) {
    /**
     * Setting the members
     */
    m_dashletSpec = dashletSpec;

    setHeight(210, Unit.PIXELS);
    setWidth(40, Unit.PERCENTAGE);

    HorizontalLayout horizontalLayout = new HorizontalLayout();
    horizontalLayout.setWidth(100, Unit.PERCENTAGE);
    horizontalLayout.setSpacing(true);
    horizontalLayout.setMargin(true);

    FormLayout formLayout = new FormLayout();
    formLayout.setWidth(100, Unit.PERCENTAGE);
    formLayout.setSpacing(true);
    formLayout.setMargin(true);

    m_kscSelect = new NativeSelect();
    m_kscSelect.setDescription("Select KSC-report to be displayed");
    m_kscSelect.setCaption("KSC-Report");
    m_kscSelect.setImmediate(true);
    m_kscSelect.setNewItemsAllowed(false);
    m_kscSelect.setMultiSelect(false);
    m_kscSelect.setInvalidAllowed(false);
    m_kscSelect.setNullSelectionAllowed(false);
    m_kscSelect.setImmediate(true);

    final KSC_PerformanceReportFactory kscPerformanceReportFactory = KSC_PerformanceReportFactory.getInstance();

    Map<Integer, String> reportsMap = kscPerformanceReportFactory.getReportList();

    for (Map.Entry<Integer, String> entry : reportsMap.entrySet()) {
        m_kscSelect.addItem(entry.getKey());
        m_kscSelect.setItemCaption(entry.getKey(), entry.getValue());
        if (m_kscSelect.getValue() == null) {
            m_kscSelect.setValue(entry.getKey());
        }
    }

    String chartName = m_dashletSpec.getParameters().get("kscReport");

    if (chartName != null) {
        if (reportsMap.values().contains(chartName)) {
            m_kscSelect.setValue(chartName);
        }
    }

    formLayout.addComponent(m_kscSelect);

    m_kscSelect.setValue(chartName);
    m_kscSelect.setImmediate(true);

    horizontalLayout.addComponent(formLayout);

    /**
     * Using an additional {@link com.vaadin.ui.HorizontalLayout} for layouting the buttons
     */
    HorizontalLayout buttonLayout = new HorizontalLayout();

    buttonLayout.setMargin(true);
    buttonLayout.setSpacing(true);
    buttonLayout.setWidth("100%");
    /**
     * Adding the cancel button...
     */
    Button cancel = new Button("Cancel");
    cancel.setDescription("Cancel editing");
    cancel.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            close();
        }
    });

    cancel.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    buttonLayout.addComponent(cancel);
    buttonLayout.setExpandRatio(cancel, 1.0f);
    buttonLayout.setComponentAlignment(cancel, Alignment.TOP_RIGHT);

    /**
     * ...and the OK button
     */
    Button ok = new Button("Save");
    ok.setDescription("Save properties and close");
    ok.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            Map<Integer, String> reportsMap = kscPerformanceReportFactory.getReportList();

            m_dashletSpec.getParameters().put("kscReport", reportsMap.get(m_kscSelect.getValue()));

            WallboardProvider.getInstance().save();
            ((WallboardConfigUI) getUI()).notifyMessage("Data saved", "Properties");

            close();
        }
    });

    ok.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
    buttonLayout.addComponent(ok);

    if (reportsMap.size() == 0) {
        m_kscSelect.setEnabled(false);
        ok.setEnabled(false);
    }

    /**
     * Adding the layout and setting the content
     */

    VerticalLayout verticalLayout = new VerticalLayout();

    verticalLayout.addComponent(horizontalLayout);
    verticalLayout.addComponent(buttonLayout);

    setContent(verticalLayout);
}

From source file:org.opennms.features.vaadin.dashboard.dashlets.RrdDashletConfigurationWindow.java

License:Open Source License

/**
 * Constructor for instantiating new objects of this class.
 *
 * @param dashletSpec the {@link DashletSpec} to be edited
 *///from  www  .j  a va 2  s. c o m
public RrdDashletConfigurationWindow(DashletSpec dashletSpec, RrdGraphHelper rrdGraphHelper, NodeDao nodeDao) {
    /**
     * Setting the members
     */
    m_dashletSpec = dashletSpec;
    m_nodeDao = nodeDao;
    m_rrdGraphHelper = rrdGraphHelper;

    /**
     * creating the grid layout
     */
    m_gridLayout = new GridLayout();
    m_gridLayout.setSizeFull();
    m_gridLayout.setColumns(1);
    m_gridLayout.setRows(1);

    /**
     * setting up the layouts
     */
    FormLayout leftFormLayout = new FormLayout();
    FormLayout middleFormLayout = new FormLayout();
    FormLayout rightFormLayout = new FormLayout();

    /**
     * creating the columns and rows selection fields
     */
    m_columnsSelect = new NativeSelect();
    m_columnsSelect.setCaption("Columns");
    m_columnsSelect.setDescription("Number of columns");
    m_columnsSelect.setImmediate(true);
    m_columnsSelect.setNewItemsAllowed(false);
    m_columnsSelect.setMultiSelect(false);
    m_columnsSelect.setInvalidAllowed(false);
    m_columnsSelect.setNullSelectionAllowed(false);

    m_rowsSelect = new NativeSelect();
    m_rowsSelect.setCaption("Rows");
    m_rowsSelect.setDescription("Number of rows");
    m_rowsSelect.setImmediate(true);
    m_rowsSelect.setNewItemsAllowed(false);
    m_rowsSelect.setMultiSelect(false);
    m_rowsSelect.setInvalidAllowed(false);
    m_rowsSelect.setNullSelectionAllowed(false);

    for (int i = 1; i < 5; i++) {
        m_columnsSelect.addItem(i);
        m_rowsSelect.addItem(i);
    }

    /**
     * setting the values/defaults
     */
    int columns;
    int rows;

    try {
        columns = Integer.parseInt(m_dashletSpec.getParameters().get("columns"));
    } catch (NumberFormatException numberFormatException) {
        columns = 1;
    }

    try {
        rows = Integer.parseInt(m_dashletSpec.getParameters().get("rows"));
    } catch (NumberFormatException numberFormatException) {
        rows = 1;
    }

    m_columnsSelect.setValue(columns);
    m_rowsSelect.setValue(rows);

    /**
     * width and height fields
     */
    m_widthField = new TextField();
    m_widthField.setCaption("Graph Width");
    m_widthField.setDescription("Width of graphs");
    m_widthField.setValue(m_dashletSpec.getParameters().get("width"));

    m_heightField = new TextField();
    m_heightField.setCaption("Graph Height");
    m_heightField.setDescription("Height of graphs");
    m_heightField.setValue(m_dashletSpec.getParameters().get("height"));

    m_timeFrameValue = new TextField("Timeframe value");
    m_timeFrameValue.setDescription("Timeframe value");
    m_timeFrameValue.setValue(m_dashletSpec.getParameters().get("timeFrameValue"));

    m_timeFrameType = new NativeSelect("Timeframe type");
    m_timeFrameType.setDescription("Timeframe type");
    m_timeFrameType.setNullSelectionAllowed(false);
    m_timeFrameType.setMultiSelect(false);
    m_timeFrameType.setNewItemsAllowed(false);

    m_timeFrameType.setItemCaptionMode(AbstractSelect.ItemCaptionMode.EXPLICIT);
    m_timeFrameType.addItem(String.valueOf(Calendar.MINUTE));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.MINUTE), "Minute");

    m_timeFrameType.addItem(String.valueOf(Calendar.HOUR_OF_DAY));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.HOUR_OF_DAY), "Hour");

    m_timeFrameType.addItem(String.valueOf(Calendar.DAY_OF_YEAR));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.DAY_OF_YEAR), "Day");

    m_timeFrameType.addItem(String.valueOf(Calendar.WEEK_OF_YEAR));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.WEEK_OF_YEAR), "Week");

    m_timeFrameType.addItem(String.valueOf(Calendar.MONTH));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.MONTH), "Month");

    m_timeFrameType.addItem(String.valueOf(Calendar.YEAR));
    m_timeFrameType.setItemCaption(String.valueOf(Calendar.YEAR), "Year");

    m_timeFrameType.setValue(m_dashletSpec.getParameters().get("timeFrameType"));

    m_timeFrameType.setImmediate(true);
    m_timeFrameValue.setImmediate(true);

    m_timeFrameType.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            updatePreview();
        }
    });

    m_timeFrameValue.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            updatePreview();
        }
    });

    /**
     * initial creation of the grid
     */
    recreateCells(columns, rows);

    /**
     * creating the value listeners for columns/rows
     */
    m_columnsSelect.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            recreateCells(Integer.valueOf(valueChangeEvent.getProperty().getValue().toString()),
                    m_gridLayout.getRows());
        }
    });

    m_rowsSelect.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            recreateCells(m_gridLayout.getColumns(),
                    Integer.valueOf(valueChangeEvent.getProperty().getValue().toString()));
        }
    });

    leftFormLayout.addComponent(m_columnsSelect);
    leftFormLayout.addComponent(m_widthField);
    leftFormLayout.addComponent(m_timeFrameValue);
    middleFormLayout.addComponent(m_rowsSelect);
    middleFormLayout.addComponent(m_heightField);
    middleFormLayout.addComponent(m_timeFrameType);

    /**
     * KSC import stuff
     */
    Button importButton = new Button("KSC Import");
    importButton.setDescription("Import KSC-report");
    final NativeSelect selectKSCReport = new NativeSelect();
    selectKSCReport.setDescription("KSC-report selection");
    selectKSCReport.setCaption("KSC Report");
    selectKSCReport.setImmediate(true);
    selectKSCReport.setNewItemsAllowed(false);
    selectKSCReport.setMultiSelect(false);
    selectKSCReport.setInvalidAllowed(false);
    selectKSCReport.setNullSelectionAllowed(false);
    selectKSCReport.setImmediate(true);

    kscPerformanceReportFactory = KSC_PerformanceReportFactory.getInstance();

    Map<Integer, String> mapOfKscReports = kscPerformanceReportFactory.getReportList();

    if (mapOfKscReports.size() == 0) {
        importButton.setEnabled(false);
    }

    for (Map.Entry<Integer, String> entry : mapOfKscReports.entrySet()) {
        selectKSCReport.addItem(entry.getKey());

        selectKSCReport.setItemCaption(entry.getKey(), entry.getValue());

        if (selectKSCReport.getValue() == null) {
            selectKSCReport.setValue(entry.getKey());
        }
    }

    importButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            importKscReport(Integer.valueOf(selectKSCReport.getValue().toString()));
        }
    });

    rightFormLayout.addComponent(selectKSCReport);
    rightFormLayout.addComponent(importButton);

    /**
     * setting up the layout
     */
    HorizontalLayout horizontalLayout = new HorizontalLayout();
    horizontalLayout.setMargin(true);

    horizontalLayout.addComponent(leftFormLayout);
    horizontalLayout.addComponent(middleFormLayout);
    horizontalLayout.addComponent(rightFormLayout);

    /**
     * Using an additional {@link com.vaadin.ui.HorizontalLayout} for layouting the buttons
     */
    HorizontalLayout buttonLayout = new HorizontalLayout();

    buttonLayout.setMargin(true);
    buttonLayout.setSpacing(true);
    buttonLayout.setWidth("100%");

    /**
     * Adding the cancel button...
     */
    Button cancel = new Button("Cancel");
    cancel.setDescription("Cancel editing");
    cancel.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            close();
        }
    });

    cancel.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    buttonLayout.addComponent(cancel);
    buttonLayout.setExpandRatio(cancel, 1.0f);
    buttonLayout.setComponentAlignment(cancel, Alignment.TOP_RIGHT);

    /**
     * ...and the OK button
     */
    Button ok = new Button("Save");
    ok.setDescription("Save properties and close");

    ok.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            /**
             * saving the data
             */
            m_dashletSpec.getParameters().put("width", m_widthField.getValue().toString());
            m_dashletSpec.getParameters().put("height", m_heightField.getValue().toString());
            m_dashletSpec.getParameters().put("columns", m_columnsSelect.getValue().toString());
            m_dashletSpec.getParameters().put("rows", m_rowsSelect.getValue().toString());

            int timeFrameValue;
            int timeFrameType;

            try {
                timeFrameValue = Integer.parseInt(m_timeFrameValue.getValue().toString());
            } catch (NumberFormatException numberFormatException) {
                timeFrameValue = 1;
            }

            try {
                timeFrameType = Integer.parseInt(m_timeFrameType.getValue().toString());
            } catch (NumberFormatException numberFormatException) {
                timeFrameType = Calendar.HOUR;
            }

            m_dashletSpec.getParameters().put("timeFrameType", String.valueOf(timeFrameType));
            m_dashletSpec.getParameters().put("timeFrameValue", String.valueOf(timeFrameValue));

            int i = 0;

            for (int y = 0; y < m_gridLayout.getRows(); y++) {
                for (int x = 0; x < m_gridLayout.getColumns(); x++) {
                    RrdGraphEntry rrdGraphEntry = (RrdGraphEntry) m_gridLayout.getComponent(x, y);
                    m_dashletSpec.getParameters().put("nodeLabel" + i, rrdGraphEntry.getNodeLabel());
                    m_dashletSpec.getParameters().put("nodeId" + i, rrdGraphEntry.getNodeId());
                    m_dashletSpec.getParameters().put("resourceTypeLabel" + i,
                            rrdGraphEntry.getResourceTypeLabel());
                    m_dashletSpec.getParameters().put("resourceTypeId" + i, rrdGraphEntry.getResourceTypeId());
                    m_dashletSpec.getParameters().put("resourceId" + i, rrdGraphEntry.getResourceId());
                    m_dashletSpec.getParameters().put("resourceLabel" + i, rrdGraphEntry.getResourceLabel());
                    m_dashletSpec.getParameters().put("graphLabel" + i, rrdGraphEntry.getGraphLabel());
                    m_dashletSpec.getParameters().put("graphId" + i, rrdGraphEntry.getGraphId());
                    m_dashletSpec.getParameters().put("graphUrl" + i, rrdGraphEntry.getGraphUrl());

                    i++;
                }
            }

            WallboardProvider.getInstance().save();
            ((WallboardConfigUI) getUI()).notifyMessage("Data saved", "Properties");

            close();
        }
    });

    ok.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
    buttonLayout.addComponent(ok);

    /**
     * Adding the layout and setting the content
     */

    VerticalLayout verticalLayout = new VerticalLayout();
    verticalLayout.setMargin(true);

    verticalLayout.addComponent(horizontalLayout);
    verticalLayout.addComponent(m_gridLayout);
    verticalLayout.addComponent(buttonLayout);
    verticalLayout.setExpandRatio(m_gridLayout, 2.0f);
    verticalLayout.setSizeFull();

    setContent(verticalLayout);
}

From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewAlarmTable.java

License:Open Source License

/**
 * Constructor for instantiating this component.
 *
 * @param surveillanceViewService the surveillance view service to be used
 * @param enabled                 the flag should links be enabled?
 *//*from  w w w . j a  v a 2 s .  c om*/
public SurveillanceViewAlarmTable(SurveillanceViewService surveillanceViewService, boolean enabled) {
    /**
     * calling the super constructor
     */
    super("Alarms", surveillanceViewService, enabled);

    /**
     * set the datasource
     */
    setContainerDataSource(m_beanItemContainer);

    /**
     * the base stylename
     */
    addStyleName("surveillance-view");

    /**
     * add node column
     */
    addGeneratedColumn("nodeLabel", new ColumnGenerator() {
        @Override
        public Object generateCell(final Table table, final Object itemId, final Object propertyId) {
            final Alarm alarm = (Alarm) itemId;

            Button icon = getClickableIcon("glyphicon glyphicon-warning-sign", new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent clickEvent) {
                    final URI currentLocation = Page.getCurrent().getLocation();
                    final String contextRoot = VaadinServlet.getCurrent().getServletContext().getContextPath();
                    final String redirectFragment = contextRoot + "/alarm/detail.htm?quiet=true&id="
                            + alarm.getId();

                    LOG.debug("alarm {} clicked, current location = {}, uri = {}", alarm.getId(),
                            currentLocation, redirectFragment);

                    try {
                        SurveillanceViewAlarmTable.this.getUI()
                                .addWindow(new InfoWindow(new URL(currentLocation.toURL(), redirectFragment),
                                        new InfoWindow.LabelCreator() {
                                            @Override
                                            public String getLabel() {
                                                return "Alarm Info " + alarm.getId();
                                            }
                                        }));
                    } catch (MalformedURLException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            });

            Button button = new Button(alarm.getNodeLabel());
            button.setPrimaryStyleName(BaseTheme.BUTTON_LINK);
            button.setEnabled(m_enabled);

            button.addClickListener(new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent clickEvent) {
                    final URI currentLocation = Page.getCurrent().getLocation();
                    final String contextRoot = VaadinServlet.getCurrent().getServletContext().getContextPath();
                    final String redirectFragment = contextRoot + "/element/node.jsp?quiet=true&node="
                            + alarm.getNodeId();

                    LOG.debug("node {} clicked, current location = {}, uri = {}", alarm.getNodeId(),
                            currentLocation, redirectFragment);

                    try {
                        SurveillanceViewAlarmTable.this.getUI()
                                .addWindow(new InfoWindow(new URL(currentLocation.toURL(), redirectFragment),
                                        new InfoWindow.LabelCreator() {
                                            @Override
                                            public String getLabel() {
                                                return "Node Info " + alarm.getNodeId();
                                            }
                                        }));
                    } catch (MalformedURLException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            });

            HorizontalLayout horizontalLayout = new HorizontalLayout();

            horizontalLayout.addComponent(icon);
            horizontalLayout.addComponent(button);

            horizontalLayout.setSpacing(true);

            return horizontalLayout;
        }
    });

    /**
     * add severity column
     */
    addGeneratedColumn("severity", new ColumnGenerator() {
        @Override
        public Object generateCell(Table table, Object itemId, Object propertyId) {
            Alarm alarm = (Alarm) itemId;
            return getImageSeverityLayout(alarm.getSeverity());
        }
    });

    /**
     * set a cell style generator that handles the severity column
     */
    setCellStyleGenerator(new CellStyleGenerator() {
        @Override
        public String getStyle(final Table source, final Object itemId, final Object propertyId) {
            Alarm alarm = ((Alarm) itemId);

            String style = alarm.getSeverity().toLowerCase();

            if ("severity".equals(propertyId)) {
                style += "-image";
            }

            return style;
        }
    });

    /**
     * set column headers
     */
    setColumnHeader("nodeLabel", "Node");
    setColumnHeader("severity", "Severity");
    setColumnHeader("uei", "UEI");
    setColumnHeader("counter", "Count");
    setColumnHeader("lastEventTime", "Last Time");
    setColumnHeader("logMsg", "Log Msg");

    setColumnExpandRatio("nodeLabel", 2.25f);
    setColumnExpandRatio("severity", 1.0f);
    setColumnExpandRatio("uei", 3.0f);
    setColumnExpandRatio("counter", 0.5f);
    setColumnExpandRatio("lastEventTime", 1.5f);
    setColumnExpandRatio("logMsg", 4.0f);

    /**
     * set visible columns
     */
    setVisibleColumns("nodeLabel", "severity", "uei", "counter", "lastEventTime", "logMsg");
}

From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewDetailTable.java

License:Open Source License

/**
 * Returns a clickable glyph icon with the given {@link com.vaadin.ui.Button.ClickListener}.
 *
 * @param glyphIcon     the icon to be used
 * @param clickListener the listener//from  ww  w .j ava 2s  .  c o m
 * @return the button instance
 */
protected Button getClickableIcon(String glyphIcon, Button.ClickListener clickListener) {
    Button button = new Button("<span class=\"" + glyphIcon + "\" aria-hidden=\"true\"></span>");
    button.setHtmlContentAllowed(true);
    button.setStyleName(BaseTheme.BUTTON_LINK);
    button.addStyleName("icon");
    button.setEnabled(m_enabled);
    button.addClickListener(clickListener);
    return button;
}

From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewNodeRtcTable.java

License:Open Source License

/**
 * Constructor for instantiating this component.
 *
 * @param surveillanceViewService the surveillance view service to be used
 * @param enabled                 the flag should links be enabled?
 *//*from w w w  . j ava2  s .com*/
public SurveillanceViewNodeRtcTable(SurveillanceViewService surveillanceViewService, boolean enabled) {
    /**
     * call the super constructor
     */
    super("Outages", surveillanceViewService, enabled);

    /**
     * set the datasource
     */
    setContainerDataSource(m_beanItemContainer);

    /**
     * set the base style name
     */
    addStyleName("surveillance-view");

    /**
     * add node column
     */
    addGeneratedColumn("node", new ColumnGenerator() {
        @Override
        public Object generateCell(Table table, Object itemId, Object propertyId) {
            final SurveillanceViewService.NodeRtc nodeRtc = (SurveillanceViewService.NodeRtc) itemId;

            Button button = new Button(nodeRtc.getNode().getLabel());
            button.setPrimaryStyleName(BaseTheme.BUTTON_LINK);
            button.setEnabled(m_enabled);
            button.addStyleName("white");

            button.addClickListener(new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent clickEvent) {
                    final URI currentLocation = Page.getCurrent().getLocation();
                    final String contextRoot = VaadinServlet.getCurrent().getServletContext().getContextPath();
                    final String redirectFragment = contextRoot + "/element/node.jsp?quiet=true&node="
                            + nodeRtc.getNode().getId();

                    LOG.debug("node {} clicked, current location = {}, uri = {}", nodeRtc.getNode().getId(),
                            currentLocation, redirectFragment);

                    try {
                        SurveillanceViewNodeRtcTable.this.getUI()
                                .addWindow(new InfoWindow(new URL(currentLocation.toURL(), redirectFragment),
                                        new InfoWindow.LabelCreator() {
                                            @Override
                                            public String getLabel() {
                                                return "Node Info " + nodeRtc.getNode().getId();
                                            }
                                        }));
                    } catch (MalformedURLException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            });

            return button;
        }
    });

    /**
     * add currentOutages column
     */
    addGeneratedColumn("currentOutages", new ColumnGenerator() {
        @Override
        public Object generateCell(Table table, final Object itemId, Object columnId) {
            SurveillanceViewService.NodeRtc nodeRtc = (SurveillanceViewService.NodeRtc) itemId;
            return getImageSeverityLayout(nodeRtc.getDownServiceCount() + " of " + nodeRtc.getServiceCount());
        }
    });

    /**
     * add availability column
     */
    addGeneratedColumn("availability", new ColumnGenerator() {
        @Override
        public Object generateCell(Table table, final Object itemId, Object propertyId) {
            SurveillanceViewService.NodeRtc nodeRtc = (SurveillanceViewService.NodeRtc) itemId;
            return getImageSeverityLayout(nodeRtc.getAvailabilityAsString());
        }
    });

    /**
     * set cell style generator that handles the two severities for RTC calculations
     */
    setCellStyleGenerator(new CellStyleGenerator() {
        @Override
        public String getStyle(Table table, Object itemId, Object propertyId) {
            String style = null;
            SurveillanceViewService.NodeRtc nodeRtc = (SurveillanceViewService.NodeRtc) itemId;

            if (!"node".equals(propertyId)) {
                if (nodeRtc.getAvailability() == 1.0) {
                    style = "rtc-normal";
                } else {
                    style = "rtc-critical";
                }
            }
            return style;
        }
    });

    /**
     * set the column headers
     */
    setColumnHeader("node", "Node");
    setColumnHeader("currentOutages", "Current Outages");
    setColumnHeader("availability", "24 Hour Availability");

    setColumnExpandRatio("node", 1.0f);
    setColumnExpandRatio("currentOutages", 1.0f);
    setColumnExpandRatio("availability", 1.0f);

    /**
     * define the visible columns
     */
    setVisibleColumns(new Object[] { "node", "currentOutages", "availability" });
}

From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewNotificationTable.java

License:Open Source License

/**
 * Constructor for instantiating this component.
 *
 * @param surveillanceViewService the surveillance view service to be used
 * @param enabled                 the flag should links be enabled?
 *//* w  ww.  ja  v a2 s. c o  m*/
public SurveillanceViewNotificationTable(SurveillanceViewService surveillanceViewService, boolean enabled) {
    /**
     * calling the super constructor
     */
    super("Notifications", surveillanceViewService, enabled);

    /**
     * set the datasource
     */
    setContainerDataSource(m_beanItemContainer);

    /**
     * set the base style name
     */
    addStyleName("surveillance-view");

    /**
     * add node column
     */
    addGeneratedColumn("nodeLabel", new ColumnGenerator() {
        @Override
        public Object generateCell(final Table table, final Object itemId, final Object propertyId) {
            final Notification notification = (Notification) itemId;

            Button icon = getClickableIcon("glyphicon glyphicon-bell", new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent clickEvent) {
                    final URI currentLocation = Page.getCurrent().getLocation();
                    final String contextRoot = VaadinServlet.getCurrent().getServletContext().getContextPath();
                    final String redirectFragment = contextRoot + "/notification/detail.jsp?quiet=true&notice="
                            + notification.getId();

                    LOG.debug("notification {} clicked, current location = {}, uri = {}", notification.getId(),
                            currentLocation, redirectFragment);

                    try {
                        SurveillanceViewNotificationTable.this.getUI()
                                .addWindow(new InfoWindow(new URL(currentLocation.toURL(), redirectFragment),
                                        new InfoWindow.LabelCreator() {
                                            @Override
                                            public String getLabel() {
                                                return "Notification Info " + notification.getId();
                                            }
                                        }));
                    } catch (MalformedURLException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            });

            Button button = new Button(notification.getNodeLabel());
            button.setPrimaryStyleName(BaseTheme.BUTTON_LINK);
            button.setEnabled(m_enabled);

            button.addClickListener(new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent clickEvent) {
                    final URI currentLocation = Page.getCurrent().getLocation();
                    final String contextRoot = VaadinServlet.getCurrent().getServletContext().getContextPath();
                    final String redirectFragment = contextRoot + "/element/node.jsp?quiet=true&node="
                            + notification.getNodeId();
                    ;

                    LOG.debug("node {} clicked, current location = {}, uri = {}", notification.getNodeId(),
                            currentLocation, redirectFragment);

                    try {
                        SurveillanceViewNotificationTable.this.getUI()
                                .addWindow(new InfoWindow(new URL(currentLocation.toURL(), redirectFragment),
                                        new InfoWindow.LabelCreator() {
                                            @Override
                                            public String getLabel() {
                                                return "Node Info " + notification.getNodeId();
                                            }
                                        }));
                    } catch (MalformedURLException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            });

            HorizontalLayout horizontalLayout = new HorizontalLayout();

            horizontalLayout.addComponent(icon);
            horizontalLayout.addComponent(button);

            horizontalLayout.setSpacing(true);

            return horizontalLayout;
        }
    });

    /**
     * set the cell style generator
     */
    setCellStyleGenerator(new CellStyleGenerator() {
        @Override
        public String getStyle(final Table source, final Object itemId, final Object propertyId) {
            Notification notification = ((Notification) itemId);
            return notification.getSeverity().toLowerCase();
        }
    });

    /**
     * set column headers
     */
    setColumnHeader("nodeLabel", "Node");
    setColumnHeader("serviceType", "Service");
    setColumnHeader("textMsg", "Message");
    setColumnHeader("pageTime", "Sent Time");
    setColumnHeader("answeredBy", "Responder");
    setColumnHeader("respondTime", "Respond Time");

    setColumnExpandRatio("nodeLabel", 2.0f);
    setColumnExpandRatio("serviceType", 1.0f);
    setColumnExpandRatio("textMsg", 4.0f);
    setColumnExpandRatio("pageTime", 2.0f);
    setColumnExpandRatio("answeredBy", 1.0f);
    setColumnExpandRatio("respondTime", 2.0f);

    /**
     * define visible columns
     */
    setVisibleColumns("nodeLabel", "serviceType", "textMsg", "pageTime", "answeredBy", "respondTime");
}

From source file:org.opennms.features.vaadin.surveillanceviews.ui.SurveillanceViewConfigurationWindow.java

License:Open Source License

/**
 * The constructor for instantiating this component.
 *
 * @param surveillanceViewService the surveillance view service to be used
 * @param view                    the view to edit
 * @param saveActionListener      the save action listener
 *///from   w  ww.j  a  v a 2  s.co  m
public SurveillanceViewConfigurationWindow(final SurveillanceViewService surveillanceViewService,
        final View view, final SaveActionListener saveActionListener) {
    /**
     * Setting the title
     */
    super("Surveillance view configuration");

    /**
     * Setting the modal and size properties
     */
    setModal(true);
    setClosable(false);
    setResizable(false);
    setWidth(80, Sizeable.Unit.PERCENTAGE);
    setHeight(75, Sizeable.Unit.PERCENTAGE);

    /**
     * Title field
     */
    final TextField titleField = new TextField();
    titleField.setValue(view.getName());
    titleField.setImmediate(true);
    titleField.setCaption("Title");
    titleField.setDescription("Title of this surveillance view");
    titleField.setWidth(25, Unit.PERCENTAGE);

    /**
     * Adding simple validator
     */
    titleField.addValidator(new AbstractStringValidator("Please use an unique name for the surveillance view") {
        @Override
        protected boolean isValidValue(String string) {
            if ("".equals(string.trim())) {
                return false;
            }
            if (SurveillanceViewProvider.getInstance().containsView(string) && !view.getName().equals(string)) {
                return false;
            }
            return true;
        }
    });

    /**
     * Refresh seconds field setup and validator
     */
    final TextField refreshSecondsField = new TextField();
    refreshSecondsField.setValue(String.valueOf(view.getRefreshSeconds()));
    refreshSecondsField.setImmediate(true);
    refreshSecondsField.setCaption("Refresh seconds");
    refreshSecondsField.setDescription("Refresh duration in seconds");

    refreshSecondsField.addValidator(new AbstractStringValidator("Only numbers allowed here") {
        @Override
        protected boolean isValidValue(String s) {
            int number;
            try {
                number = Integer.parseInt(s);
            } catch (NumberFormatException numberFormatException) {
                return false;
            }
            return (number >= 0);
        }
    });

    /**
     * Columns table
     */
    final Table columnsTable = new Table();

    columnsTable.setSortEnabled(false);
    columnsTable.setWidth(25, Unit.PERCENTAGE);

    final BeanItemContainer<ColumnDef> columns = new BeanItemContainer<ColumnDef>(ColumnDef.class,
            view.getColumns());

    final Map<ColumnDef, Integer> columnOrder = new HashMap<>();

    int c = 0;
    for (ColumnDef columnDef : view.getColumns()) {
        columnOrder.put(columnDef, c++);
    }

    columnsTable.setContainerDataSource(columns);

    columnsTable.setVisibleColumns("label");
    columnsTable.setColumnHeader("label", "Columns");
    columnsTable.setColumnExpandRatio("label", 1.0f);
    columnsTable.setSelectable(true);
    columnsTable.setMultiSelect(false);

    /**
     * Create custom sorter
     */
    columns.setItemSorter(new DefaultItemSorter() {
        @Override
        public int compare(Object o1, Object o2) {
            if (o1 == null) {
                if (o2 == null) {
                    return 0;
                } else {
                    return -1;
                }
            }
            if (o2 == null) {
                return 1;
            }

            if (columnOrder.get(o1).intValue() == columnOrder.get(o2).intValue()) {
                return 0;
            } else {
                if (columnOrder.get(o1).intValue() > columnOrder.get(o2).intValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        }
    });

    /**
     * Adding the buttons...
     */
    final Button columnsAddButton = new Button("Add");
    columnsAddButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            getUI().addWindow(new SurveillanceViewConfigurationCategoryWindow(surveillanceViewService,
                    columnsTable.getItemIds(), new ColumnDef(),
                    new SurveillanceViewConfigurationCategoryWindow.SaveActionListener() {
                        @Override
                        public void save(Def def) {
                            columns.addItem((ColumnDef) def);
                            columnOrder.put((ColumnDef) def, columnOrder.size());

                            columns.sort(new Object[] { "label" }, new boolean[] { true });
                            columnsTable.refreshRowCache();
                        }
                    }));
        }
    });

    columnsAddButton.setEnabled(true);
    columnsAddButton.setStyleName("small");
    columnsAddButton.setDescription("Add column");
    columnsAddButton.setEnabled(true);

    final Button columnsEditButton = new Button("Edit");
    columnsEditButton.setEnabled(true);
    columnsEditButton.setStyleName("small");
    columnsEditButton.setDescription("Edit column");
    columnsEditButton.setEnabled(false);

    columnsEditButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            getUI().addWindow(new SurveillanceViewConfigurationCategoryWindow(surveillanceViewService,
                    columnsTable.getItemIds(), (ColumnDef) columnsTable.getValue(),
                    new SurveillanceViewConfigurationCategoryWindow.SaveActionListener() {
                        @Override
                        public void save(Def def) {
                            ColumnDef columnToBeReplaced = (ColumnDef) columnsTable.getValue();
                            int index = columnOrder.get(columnToBeReplaced);

                            columns.removeItem(columnToBeReplaced);
                            columnOrder.remove(columnToBeReplaced);

                            columns.addItem((ColumnDef) def);
                            columnOrder.put((ColumnDef) def, index);

                            columns.sort(new Object[] { "label" }, new boolean[] { true });
                            columnsTable.refreshRowCache();
                        }
                    }));
        }
    });

    final Button columnsRemoveButton = new Button("Remove");
    columnsRemoveButton.setEnabled(true);
    columnsRemoveButton.setStyleName("small");
    columnsRemoveButton.setDescription("Remove column");
    columnsRemoveButton.setEnabled(false);

    columnsRemoveButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            ColumnDef columnDef = (ColumnDef) columnsTable.getValue();
            if (columnDef != null) {
                columnsTable.unselect(columnDef);
                columns.removeItem(columnDef);
            }

            columnsTable.refreshRowCache();
        }
    });

    final Button columnUpButton = new Button();
    columnUpButton.setStyleName("small");
    columnUpButton.setIcon(new ThemeResource("../runo/icons/16/arrow-up.png"));
    columnUpButton.setDescription("Move this a column entry one position up");
    columnUpButton.setEnabled(false);

    columnUpButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            ColumnDef columnDef = (ColumnDef) columnsTable.getValue();
            if (columnDef != null) {
                int columnDefIndex = columnOrder.get(columnDef);

                ColumnDef columnDefToSwap = null;

                for (Map.Entry<ColumnDef, Integer> entry : columnOrder.entrySet()) {
                    if (entry.getValue().intValue() == columnDefIndex - 1) {
                        columnDefToSwap = entry.getKey();
                        break;
                    }
                }

                if (columnDefToSwap != null) {
                    columnsTable.unselect(columnDef);
                    columnOrder.remove(columnDef);
                    columnOrder.remove(columnDefToSwap);
                    columnOrder.put(columnDef, columnDefIndex - 1);
                    columnOrder.put(columnDefToSwap, columnDefIndex);

                    columns.sort(new Object[] { "label" }, new boolean[] { true });
                    columnsTable.refreshRowCache();
                    columnsTable.select(columnDef);
                }

            }
        }
    });

    final Button columnDownButton = new Button();
    columnDownButton.setStyleName("small");
    columnDownButton.setIcon(new ThemeResource("../runo/icons/16/arrow-down.png"));
    columnDownButton.setDescription("Move this a column entry one position down");
    columnDownButton.setEnabled(false);

    columnDownButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            ColumnDef columnDef = (ColumnDef) columnsTable.getValue();
            if (columnDef != null) {
                int columnDefIndex = columnOrder.get(columnDef);

                ColumnDef columnDefToSwap = null;

                for (Map.Entry<ColumnDef, Integer> entry : columnOrder.entrySet()) {
                    if (entry.getValue().intValue() == columnDefIndex + 1) {
                        columnDefToSwap = entry.getKey();
                        break;
                    }
                }

                if (columnDefToSwap != null) {
                    columnsTable.unselect(columnDef);
                    columnOrder.remove(columnDef);
                    columnOrder.remove(columnDefToSwap);
                    columnOrder.put(columnDef, columnDefIndex + 1);
                    columnOrder.put(columnDefToSwap, columnDefIndex);

                    columns.sort(new Object[] { "label" }, new boolean[] { true });
                    columnsTable.refreshRowCache();
                    columnsTable.select(columnDef);
                }
            }
        }
    });

    columnsTable.setSizeFull();

    columnUpButton.setSizeFull();
    columnDownButton.setSizeFull();
    columnsAddButton.setSizeFull();
    columnsEditButton.setSizeFull();
    columnsRemoveButton.setSizeFull();

    columnsTable.setImmediate(true);

    /**
     * ...and a listener
     */
    columnsTable.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            boolean somethingSelected = (columnsTable.getValue() != null);
            columnsRemoveButton.setEnabled(somethingSelected);
            columnsEditButton.setEnabled(somethingSelected);
            columnsAddButton.setEnabled(true);
            columnUpButton
                    .setEnabled(somethingSelected && columnOrder.get(columnsTable.getValue()).intValue() > 0);
            columnDownButton.setEnabled(somethingSelected
                    && columnOrder.get(columnsTable.getValue()).intValue() < columnOrder.size() - 1);
        }
    });

    /**
     * Rows table
     */
    final Table rowsTable = new Table();

    rowsTable.setSortEnabled(false);
    rowsTable.setWidth(25, Unit.PERCENTAGE);

    final BeanItemContainer<RowDef> rows = new BeanItemContainer<RowDef>(RowDef.class, view.getRows());

    final Map<RowDef, Integer> rowOrder = new HashMap<>();

    int r = 0;
    for (RowDef rowDef : view.getRows()) {
        rowOrder.put(rowDef, r++);
    }

    rowsTable.setContainerDataSource(rows);

    rowsTable.setVisibleColumns("label");
    rowsTable.setColumnHeader("label", "Rows");
    rowsTable.setColumnExpandRatio("label", 1.0f);
    rowsTable.setSelectable(true);
    rowsTable.setMultiSelect(false);

    /**
     * Create custom sorter
     */
    rows.setItemSorter(new DefaultItemSorter() {
        @Override
        public int compare(Object o1, Object o2) {
            if (o1 == null) {
                if (o2 == null) {
                    return 0;
                } else {
                    return -1;
                }
            }
            if (o2 == null) {
                return 1;
            }

            if (rowOrder.get(o1).intValue() == rowOrder.get(o2).intValue()) {
                return 0;
            } else {
                if (rowOrder.get(o1).intValue() > rowOrder.get(o2).intValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        }
    });

    /**
     * Adding the buttons...
     */
    final Button rowsAddButton = new Button("Add");
    rowsAddButton.setEnabled(true);
    rowsAddButton.setStyleName("small");
    rowsAddButton.setDescription("Add row");
    rowsAddButton.setEnabled(true);

    rowsAddButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            getUI().addWindow(new SurveillanceViewConfigurationCategoryWindow(surveillanceViewService,
                    rowsTable.getItemIds(), new RowDef(),
                    new SurveillanceViewConfigurationCategoryWindow.SaveActionListener() {
                        @Override
                        public void save(Def def) {
                            rows.addItem((RowDef) def);
                            rowOrder.put((RowDef) def, rowOrder.size());

                            rows.sort(new Object[] { "label" }, new boolean[] { true });
                            rowsTable.refreshRowCache();
                        }
                    }));
        }
    });

    final Button rowsEditButton = new Button("Edit");
    rowsEditButton.setEnabled(true);
    rowsEditButton.setStyleName("small");
    rowsEditButton.setDescription("Edit row");
    rowsEditButton.setEnabled(false);

    rowsEditButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            getUI().addWindow(new SurveillanceViewConfigurationCategoryWindow(surveillanceViewService,
                    rowsTable.getItemIds(), (RowDef) rowsTable.getValue(),
                    new SurveillanceViewConfigurationCategoryWindow.SaveActionListener() {
                        @Override
                        public void save(Def def) {
                            RowDef rowToBeReplaced = (RowDef) rowsTable.getValue();
                            int index = rowOrder.get(rowToBeReplaced);

                            rows.removeItem(rowToBeReplaced);
                            rowOrder.remove(rowToBeReplaced);

                            rows.addItem((RowDef) def);
                            rowOrder.put((RowDef) def, index);

                            rows.sort(new Object[] { "label" }, new boolean[] { true });
                            rowsTable.refreshRowCache();
                        }
                    }));
        }
    });

    final Button rowsRemoveButton = new Button("Remove");
    rowsRemoveButton.setEnabled(true);
    rowsRemoveButton.setStyleName("small");
    rowsRemoveButton.setDescription("Remove row");
    rowsRemoveButton.setEnabled(false);

    rowsRemoveButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            RowDef rowDef = (RowDef) rowsTable.getValue();
            if (rowDef != null) {
                rowsTable.unselect(rowDef);
                rows.removeItem(rowDef);
            }

            rowsTable.refreshRowCache();
        }
    });

    final Button rowUpButton = new Button();
    rowUpButton.setStyleName("small");
    rowUpButton.setIcon(new ThemeResource("../runo/icons/16/arrow-up.png"));
    rowUpButton.setDescription("Move this a row entry one position up");
    rowUpButton.setEnabled(false);

    rowUpButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            RowDef rowDef = (RowDef) rowsTable.getValue();
            if (rowDef != null) {
                int rowDefIndex = rowOrder.get(rowDef);

                RowDef rowDefToSwap = null;

                for (Map.Entry<RowDef, Integer> entry : rowOrder.entrySet()) {
                    if (entry.getValue().intValue() == rowDefIndex - 1) {
                        rowDefToSwap = entry.getKey();
                        break;
                    }
                }

                if (rowDefToSwap != null) {
                    rowsTable.unselect(rowDef);
                    rowOrder.remove(rowDef);
                    rowOrder.remove(rowDefToSwap);
                    rowOrder.put(rowDef, rowDefIndex - 1);
                    rowOrder.put(rowDefToSwap, rowDefIndex);

                    rows.sort(new Object[] { "label" }, new boolean[] { true });
                    rowsTable.refreshRowCache();
                    rowsTable.select(rowDef);
                }
            }
        }
    });

    final Button rowDownButton = new Button();
    rowDownButton.setStyleName("small");
    rowDownButton.setIcon(new ThemeResource("../runo/icons/16/arrow-down.png"));
    rowDownButton.setDescription("Move this a row entry one position down");
    rowDownButton.setEnabled(false);

    rowDownButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            RowDef rowDef = (RowDef) rowsTable.getValue();
            if (rowDef != null) {
                int rowDefIndex = rowOrder.get(rowDef);

                RowDef rowDefToSwap = null;

                for (Map.Entry<RowDef, Integer> entry : rowOrder.entrySet()) {
                    if (entry.getValue().intValue() == rowDefIndex + 1) {
                        rowDefToSwap = entry.getKey();
                        break;
                    }
                }

                if (rowDefToSwap != null) {
                    rowsTable.unselect(rowDef);
                    rowOrder.remove(rowDef);
                    rowOrder.remove(rowDefToSwap);
                    rowOrder.put(rowDef, rowDefIndex + 1);
                    rowOrder.put(rowDefToSwap, rowDefIndex);

                    rows.sort(new Object[] { "label" }, new boolean[] { true });
                    rowsTable.refreshRowCache();
                    rowsTable.select(rowDef);
                }
            }
        }
    });

    rowsTable.setSizeFull();

    rowUpButton.setSizeFull();
    rowDownButton.setSizeFull();
    rowsAddButton.setSizeFull();
    rowsEditButton.setSizeFull();
    rowsRemoveButton.setSizeFull();

    rowsTable.setImmediate(true);

    /**
     * ...and a listener
     */
    rowsTable.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            boolean somethingSelected = (rowsTable.getValue() != null);
            rowsRemoveButton.setEnabled(somethingSelected);
            rowsEditButton.setEnabled(somethingSelected);
            rowsAddButton.setEnabled(true);
            rowUpButton.setEnabled(somethingSelected && rowOrder.get(rowsTable.getValue()).intValue() > 0);
            rowDownButton.setEnabled(
                    somethingSelected && rowOrder.get(rowsTable.getValue()).intValue() < rowOrder.size() - 1);
        }
    });

    /**
     * Create form layouts...
     */
    FormLayout baseFormLayout = new FormLayout();
    baseFormLayout.addComponent(titleField);
    baseFormLayout.addComponent(refreshSecondsField);

    FormLayout columnTableFormLayout = new FormLayout();
    columnTableFormLayout.addComponent(columnsAddButton);
    columnTableFormLayout.addComponent(columnsEditButton);
    columnTableFormLayout.addComponent(columnsRemoveButton);
    columnTableFormLayout.addComponent(columnUpButton);
    columnTableFormLayout.addComponent(columnDownButton);

    FormLayout rowTableFormLayout = new FormLayout();
    rowTableFormLayout.addComponent(rowsAddButton);
    rowTableFormLayout.addComponent(rowsEditButton);
    rowTableFormLayout.addComponent(rowsRemoveButton);
    rowTableFormLayout.addComponent(rowUpButton);
    rowTableFormLayout.addComponent(rowDownButton);

    /**
     * Adding the different {@link com.vaadin.ui.FormLayout} instances to a {@link com.vaadin.ui.GridLayout}
     */
    baseFormLayout.setMargin(true);
    columnTableFormLayout.setMargin(true);
    rowTableFormLayout.setMargin(true);

    GridLayout gridLayout = new GridLayout();
    gridLayout.setSizeFull();
    gridLayout.setColumns(4);
    gridLayout.setRows(1);
    gridLayout.setMargin(true);

    gridLayout.addComponent(rowsTable);
    gridLayout.addComponent(rowTableFormLayout);
    gridLayout.addComponent(columnsTable);
    gridLayout.addComponent(columnTableFormLayout);

    gridLayout.setColumnExpandRatio(1, 0.5f);
    gridLayout.setColumnExpandRatio(2, 1.0f);
    gridLayout.setColumnExpandRatio(3, 0.5f);
    gridLayout.setColumnExpandRatio(4, 1.0f);

    /**
     * Creating the vertical layout...
     */
    VerticalLayout verticalLayout = new VerticalLayout();

    verticalLayout.addComponent(baseFormLayout);
    verticalLayout.addComponent(gridLayout);

    /**
     * Using an additional {@link com.vaadin.ui.HorizontalLayout} for layouting the buttons
     */
    HorizontalLayout horizontalLayout = new HorizontalLayout();

    horizontalLayout.setMargin(true);
    horizontalLayout.setSpacing(true);
    horizontalLayout.setWidth(100, Unit.PERCENTAGE);

    /**
     * Adding the cancel button...
     */
    Button cancel = new Button("Cancel");
    cancel.setDescription("Cancel editing properties");
    cancel.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            close();
        }
    });

    cancel.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    horizontalLayout.addComponent(cancel);
    horizontalLayout.setExpandRatio(cancel, 1);
    horizontalLayout.setComponentAlignment(cancel, Alignment.TOP_RIGHT);

    /**
     * ...and the OK button
     */
    Button ok = new Button("Save");
    ok.setDescription("Save properties and close");

    ok.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (!titleField.isValid()) {
                ((SurveillanceViewsConfigUI) getUI()).notifyMessage("Error", "Please use an unique title",
                        Notification.Type.ERROR_MESSAGE);
                return;
            }

            if (!refreshSecondsField.isValid()) {
                ((SurveillanceViewsConfigUI) getUI()).notifyMessage("Error",
                        "Please enter a valid number in the \"Refresh seconds\" field",
                        Notification.Type.ERROR_MESSAGE);
                return;
            }

            if (columns.getItemIds().isEmpty() || rows.getItemIds().isEmpty()) {
                ((SurveillanceViewsConfigUI) getUI()).notifyMessage("Error",
                        "You must define at least one row category and one column category",
                        Notification.Type.ERROR_MESSAGE);
                return;
            }

            View finalView = new View();

            for (ColumnDef columnDef : columns.getItemIds()) {
                finalView.getColumns().add(columnDef);
            }

            for (RowDef rowDef : rows.getItemIds()) {
                finalView.getRows().add(rowDef);
            }

            finalView.setName(titleField.getValue());
            finalView.setRefreshSeconds(Integer.parseInt(refreshSecondsField.getValue()));

            saveActionListener.save(finalView);

            close();
        }
    });

    ok.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
    horizontalLayout.addComponent(ok);

    verticalLayout.addComponent(horizontalLayout);

    setContent(verticalLayout);
}

From source file:org.opennms.netmgt.bsm.vaadin.adminpage.BusinessServiceEditWindow.java

License:Open Source License

/**
 * Constructor// w  w  w  .  jav  a  2 s  . c  o m
 *
 * @param businessService the Business Service DTO instance to be configured
 */
@SuppressWarnings("unchecked")
public BusinessServiceEditWindow(BusinessService businessService,
        BusinessServiceManager businessServiceManager) {
    /**
     * set window title...
     */
    super("Business Service Edit");

    m_businessService = businessService;

    /**
     * ...and basic properties
     */
    setModal(true);
    setClosable(false);
    setResizable(false);
    setWidth(650, Unit.PIXELS);
    setHeight(550, Unit.PIXELS);

    /**
     * create set for Business Service names
     */
    m_businessServiceNames = businessServiceManager.getAllBusinessServices().stream()
            .map(BusinessService::getName).collect(Collectors.toSet());

    if (m_businessService.getName() != null) {
        m_businessServiceNames.remove(m_businessService.getName());
    }

    /**
     * construct the main layout
     */
    VerticalLayout verticalLayout = new VerticalLayout();
    verticalLayout.setSizeFull();
    verticalLayout.setSpacing(true);
    verticalLayout.setMargin(true);

    /**
     * add saveBusinessService button
     */
    Button saveButton = new Button("Save");
    saveButton.setId("saveButton");
    saveButton.addClickListener(
            UIHelper.getCurrent(TransactionAwareUI.class).wrapInTransactionProxy(new Button.ClickListener() {
                private static final long serialVersionUID = -5985304347211214365L;

                @Override
                public void buttonClick(Button.ClickEvent event) {
                    if (!m_thresholdTextField.isValid() || !m_nameTextField.isValid()) {
                        return;
                    }

                    final ReductionFunction reductionFunction = getReduceFunction();
                    businessService.setName(m_nameTextField.getValue().trim());
                    businessService.setReduceFunction(reductionFunction);
                    businessService.save();
                    close();
                }

                private ReductionFunction getReduceFunction() {
                    try {
                        final ReductionFunction reductionFunction = ((Class<? extends ReductionFunction>) m_reduceFunctionNativeSelect
                                .getValue()).newInstance();
                        reductionFunction.accept(new ReduceFunctionVisitor<Void>() {
                            @Override
                            public Void visit(HighestSeverity highestSeverity) {
                                return null;
                            }

                            @Override
                            public Void visit(HighestSeverityAbove highestSeverityAbove) {
                                highestSeverityAbove.setThreshold((Status) m_thresholdStatusSelect.getValue());
                                return null;
                            }

                            @Override
                            public Void visit(Threshold threshold) {
                                threshold.setThreshold(Float.parseFloat(m_thresholdTextField.getValue()));
                                return null;
                            }
                        });
                        return reductionFunction;
                    } catch (final InstantiationException | IllegalAccessException e) {
                        throw Throwables.propagate(e);
                    }
                }
            }));

    /**
     * add the cancel button
     */
    Button cancelButton = new Button("Cancel");
    cancelButton.setId("cancelButton");
    cancelButton.addClickListener(new Button.ClickListener() {
        private static final long serialVersionUID = 5306168797758047745L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            close();
        }
    });

    /**
     * add the buttons to a HorizontalLayout
     */
    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(saveButton);
    buttonLayout.addComponent(cancelButton);

    /**
     * instantiate the input fields
     */
    m_nameTextField = new TextField("Business Service Name");
    m_nameTextField.setId("nameField");
    m_nameTextField.setNullRepresentation("");
    m_nameTextField.setNullSettingAllowed(true);
    m_nameTextField.setValue(businessService.getName());
    m_nameTextField.setWidth(100, Unit.PERCENTAGE);
    m_nameTextField.setRequired(true);
    m_nameTextField.focus();
    m_nameTextField.addValidator(new AbstractStringValidator("Name must be unique") {
        private static final long serialVersionUID = 1L;

        @Override
        protected boolean isValidValue(String value) {
            return value != null && !m_businessServiceNames.contains(value);
        }
    });
    verticalLayout.addComponent(m_nameTextField);

    /**
     * create the reduce function component
     */

    m_reduceFunctionNativeSelect = new NativeSelect("Reduce Function", ImmutableList.builder()
            .add(HighestSeverity.class).add(Threshold.class).add(HighestSeverityAbove.class).build());
    m_reduceFunctionNativeSelect.setId("reduceFunctionNativeSelect");
    m_reduceFunctionNativeSelect.setWidth(100.0f, Unit.PERCENTAGE);
    m_reduceFunctionNativeSelect.setNullSelectionAllowed(false);
    m_reduceFunctionNativeSelect.setMultiSelect(false);
    m_reduceFunctionNativeSelect.setImmediate(true);
    m_reduceFunctionNativeSelect.setNewItemsAllowed(false);

    /**
     * setting the captions for items
     */
    m_reduceFunctionNativeSelect.getItemIds().forEach(
            itemId -> m_reduceFunctionNativeSelect.setItemCaption(itemId, ((Class<?>) itemId).getSimpleName()));

    verticalLayout.addComponent(m_reduceFunctionNativeSelect);

    m_thresholdTextField = new TextField("Threshold");
    m_thresholdTextField.setId("thresholdTextField");
    m_thresholdTextField.setRequired(false);
    m_thresholdTextField.setEnabled(false);
    m_thresholdTextField.setImmediate(true);
    m_thresholdTextField.setWidth(100.0f, Unit.PERCENTAGE);
    m_thresholdTextField.setValue("0.0");
    m_thresholdTextField.addValidator(v -> {
        if (m_thresholdTextField.isEnabled()) {
            try {
                final float value = Float.parseFloat(m_thresholdTextField.getValue());
                if (0.0f >= value || value > 1.0) {
                    throw new NumberFormatException();
                }
            } catch (final NumberFormatException e) {
                throw new Validator.InvalidValueException("Threshold must be a positive number");
            }
        }
    });

    verticalLayout.addComponent(m_thresholdTextField);

    /**
     * Status selection for "Highest Severity Above"
     */
    m_thresholdStatusSelect = new NativeSelect("Threshold");
    m_thresholdStatusSelect.setId("thresholdStatusSelect");
    m_thresholdStatusSelect.setRequired(false);
    m_thresholdStatusSelect.setEnabled(false);
    m_thresholdStatusSelect.setImmediate(true);
    m_thresholdStatusSelect.setWidth(100.0f, Unit.PERCENTAGE);
    m_thresholdStatusSelect.setMultiSelect(false);
    m_thresholdStatusSelect.setNewItemsAllowed(false);
    m_thresholdStatusSelect.setNullSelectionAllowed(false);
    for (Status eachStatus : Status.values()) {
        m_thresholdStatusSelect.addItem(eachStatus);
    }
    m_thresholdStatusSelect.setValue(Status.INDETERMINATE);
    m_thresholdStatusSelect.getItemIds()
            .forEach(itemId -> m_thresholdStatusSelect.setItemCaption(itemId, ((Status) itemId).getLabel()));
    verticalLayout.addComponent(m_thresholdStatusSelect);

    m_reduceFunctionNativeSelect.addValueChangeListener(ev -> {
        boolean thresholdFunction = m_reduceFunctionNativeSelect.getValue() == Threshold.class;
        boolean highestSeverityAboveFunction = m_reduceFunctionNativeSelect
                .getValue() == HighestSeverityAbove.class;

        setVisible(m_thresholdTextField, thresholdFunction);
        setVisible(m_thresholdStatusSelect, highestSeverityAboveFunction);
    });

    if (Objects.isNull(businessService.getReduceFunction())) {
        m_reduceFunctionNativeSelect.setValue(HighestSeverity.class);
    } else {
        m_reduceFunctionNativeSelect.setValue(businessService.getReduceFunction().getClass());

        businessService.getReduceFunction().accept(new ReduceFunctionVisitor<Void>() {
            @Override
            public Void visit(HighestSeverity highestSeverity) {
                return null;
            }

            @Override
            public Void visit(HighestSeverityAbove highestSeverityAbove) {
                m_thresholdStatusSelect.setValue(highestSeverityAbove.getThreshold());
                return null;
            }

            @Override
            public Void visit(Threshold threshold) {
                m_thresholdTextField.setValue(String.valueOf(threshold.getThreshold()));
                return null;
            }
        });
    }

    /**
     * create the edges list box
     */
    m_edgesListSelect = new ListSelect("Edges");
    m_edgesListSelect.setId("edgeList");
    m_edgesListSelect.setWidth(100.0f, Unit.PERCENTAGE);
    m_edgesListSelect.setRows(10);
    m_edgesListSelect.setNullSelectionAllowed(false);
    m_edgesListSelect.setMultiSelect(false);
    refreshEdges();

    HorizontalLayout edgesListAndButtonLayout = new HorizontalLayout();

    edgesListAndButtonLayout.setWidth(100.0f, Unit.PERCENTAGE);

    VerticalLayout edgesButtonLayout = new VerticalLayout();
    edgesButtonLayout.setWidth(110.0f, Unit.PIXELS);
    edgesButtonLayout.setSpacing(true);

    Button addEdgeButton = new Button("Add Edge");
    addEdgeButton.setId("addEdgeButton");
    addEdgeButton.setWidth(110.0f, Unit.PIXELS);
    addEdgeButton.addStyleName("small");
    edgesButtonLayout.addComponent(addEdgeButton);
    addEdgeButton.addClickListener((Button.ClickListener) event -> {
        final BusinessServiceEdgeEditWindow window = new BusinessServiceEdgeEditWindow(businessService,
                businessServiceManager, null);
        window.addCloseListener(e -> refreshEdges());
        this.getUI().addWindow(window);
    });

    Button editEdgeButton = new Button("Edit Edge");
    editEdgeButton.setId("editEdgeButton");
    editEdgeButton.setEnabled(false);
    editEdgeButton.setWidth(110.0f, Unit.PIXELS);
    editEdgeButton.addStyleName("small");
    edgesButtonLayout.addComponent(editEdgeButton);
    editEdgeButton.addClickListener((Button.ClickListener) event -> {
        final BusinessServiceEdgeEditWindow window = new BusinessServiceEdgeEditWindow(businessService,
                businessServiceManager, (Edge) m_edgesListSelect.getValue());
        window.addCloseListener(e -> refreshEdges());
        this.getUI().addWindow(window);
    });

    final Button removeEdgeButton = new Button("Remove Edge");
    removeEdgeButton.setId("removeEdgeButton");
    removeEdgeButton.setEnabled(false);
    removeEdgeButton.setWidth(110.0f, Unit.PIXELS);
    removeEdgeButton.addStyleName("small");
    edgesButtonLayout.addComponent(removeEdgeButton);

    m_edgesListSelect.addValueChangeListener((Property.ValueChangeListener) event -> {
        removeEdgeButton.setEnabled(event.getProperty().getValue() != null);
        editEdgeButton.setEnabled(event.getProperty().getValue() != null);
    });

    removeEdgeButton.addClickListener((Button.ClickListener) event -> {
        if (m_edgesListSelect.getValue() != null) {
            removeEdgeButton.setEnabled(false);
            ((Edge) m_edgesListSelect.getValue()).delete();
            refreshEdges();
        }
    });

    edgesListAndButtonLayout.setSpacing(true);
    edgesListAndButtonLayout.addComponent(m_edgesListSelect);
    edgesListAndButtonLayout.setExpandRatio(m_edgesListSelect, 1.0f);

    edgesListAndButtonLayout.addComponent(edgesButtonLayout);
    edgesListAndButtonLayout.setComponentAlignment(edgesButtonLayout, Alignment.BOTTOM_CENTER);
    verticalLayout.addComponent(edgesListAndButtonLayout);

    /**
     * create the attributes list box
     */
    m_attributesListSelect = new ListSelect("Attributes");
    m_attributesListSelect.setId("attributeList");
    m_attributesListSelect.setWidth(100.0f, Unit.PERCENTAGE);
    m_attributesListSelect.setRows(10);
    m_attributesListSelect.setNullSelectionAllowed(false);
    m_attributesListSelect.setMultiSelect(false);

    refreshAttributes();

    HorizontalLayout attributesListAndButtonLayout = new HorizontalLayout();

    attributesListAndButtonLayout.setWidth(100.0f, Unit.PERCENTAGE);

    VerticalLayout attributesButtonLayout = new VerticalLayout();
    attributesButtonLayout.setWidth(110.0f, Unit.PIXELS);
    attributesButtonLayout.setSpacing(true);

    Button addAttributeButton = new Button("Add Attribute");
    addAttributeButton.setId("addAttributeButton");
    addAttributeButton.setWidth(110.0f, Unit.PIXELS);
    addAttributeButton.addStyleName("small");
    attributesButtonLayout.addComponent(addAttributeButton);
    addAttributeButton.addClickListener((Button.ClickListener) event -> {
        KeyValueInputDialogWindow keyValueInputDialogWindow = new KeyValueInputDialogWindow()
                .withKeyFieldName("Key").withValueFieldName("Value").withCaption("Attribute").withKey("")
                .withValue("").withOkAction(new KeyValueInputDialogWindow.Action() {
                    @Override
                    public void execute(KeyValueInputDialogWindow window) {
                        m_businessService.getAttributes().put(window.getKey(), window.getValue());
                        refreshAttributes();
                    }
                }).withKeyValidator(new AbstractStringValidator("Key must not be empty") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected boolean isValidValue(String value) {
                        return !Strings.isNullOrEmpty(value);
                    }
                }).withKeyValidator(new AbstractStringValidator("Key must be unique") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected boolean isValidValue(String value) {
                        return !m_businessService.getAttributes().containsKey(value);
                    }
                }).focusKey();
        this.getUI().addWindow(keyValueInputDialogWindow);
        keyValueInputDialogWindow.focus();
    });

    Button editAttributeButton = new Button("Edit Attribute");
    editAttributeButton.setId("editAttributeButton");
    editAttributeButton.setEnabled(false);
    editAttributeButton.setWidth(110.0f, Unit.PIXELS);
    editAttributeButton.addStyleName("small");
    attributesButtonLayout.addComponent(editAttributeButton);
    editAttributeButton.addClickListener((Button.ClickListener) event -> {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) m_attributesListSelect.getValue();
        KeyValueInputDialogWindow keyValueInputDialogWindow = new KeyValueInputDialogWindow()
                .withKeyFieldName("Key").withValueFieldName("Value").withCaption("Attribute")
                .withKey(entry.getKey()).disableKey().withValue(entry.getValue())
                .withOkAction(new KeyValueInputDialogWindow.Action() {
                    @Override
                    public void execute(KeyValueInputDialogWindow window) {
                        m_businessService.getAttributes().put(window.getKey(), window.getValue());
                        refreshAttributes();
                    }
                }).focusValue();
        this.getUI().addWindow(keyValueInputDialogWindow);
        keyValueInputDialogWindow.focus();
    });

    final Button removeAttributeButton = new Button("Remove Attribute");
    removeAttributeButton.setId("removeAttributeButton");
    removeAttributeButton.setEnabled(false);
    removeAttributeButton.setWidth(110.0f, Unit.PIXELS);
    removeAttributeButton.addStyleName("small");
    attributesButtonLayout.addComponent(removeAttributeButton);

    m_attributesListSelect.addValueChangeListener((Property.ValueChangeListener) event -> {
        removeAttributeButton.setEnabled(event.getProperty().getValue() != null);
        editAttributeButton.setEnabled(event.getProperty().getValue() != null);
    });

    removeAttributeButton.addClickListener((Button.ClickListener) event -> {
        if (m_attributesListSelect.getValue() != null) {
            removeAttributeButton.setEnabled(false);
            m_businessService.getAttributes()
                    .remove(((Map.Entry<String, String>) m_attributesListSelect.getValue()).getKey());
            refreshAttributes();
        }
    });

    attributesListAndButtonLayout.setSpacing(true);
    attributesListAndButtonLayout.addComponent(m_attributesListSelect);
    attributesListAndButtonLayout.setExpandRatio(m_attributesListSelect, 1.0f);

    attributesListAndButtonLayout.addComponent(attributesButtonLayout);
    attributesListAndButtonLayout.setComponentAlignment(attributesButtonLayout, Alignment.BOTTOM_CENTER);
    verticalLayout.addComponent(attributesListAndButtonLayout);

    /**
     * now add the button layout to the main layout
     */
    verticalLayout.addComponent(buttonLayout);
    verticalLayout.setExpandRatio(buttonLayout, 1.0f);

    verticalLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_RIGHT);

    /**
     * set the window's content
     */
    setContent(verticalLayout);
}

From source file:org.ripla.web.demo.config.views.LoginConfigView.java

License:Open Source License

/**
 * LoginConfigView constructor./*www.  jav  a  2 s . c om*/
 * 
 * @param inLoginConfig
 * @param inController
 *            {@link LoginConfigController}
 * @param inEnabled
 *            boolean <code>true</code> if login configuration is enabled
 */
public LoginConfigView(final boolean inLoginConfig, final LoginConfigController inController,
        final boolean inEnabled) {
    super();
    final IMessages lMessages = Activator.getMessages();
    final VerticalLayout lLayout = new VerticalLayout();
    setCompositionRoot(lLayout);
    lLayout.setStyleName("demo-view"); //$NON-NLS-1$
    lLayout.addComponent(new Label(String.format(RiplaViewHelper.TMPL_TITLE, "demo-pagetitle", //$NON-NLS-1$
            lMessages.getMessage("config.login.page.title")), ContentMode.HTML)); //$NON-NLS-1$

    lLayout.addComponent(new Label(lMessages.getMessage("view.login.remark"), ContentMode.HTML)); //$NON-NLS-1$
    if (!inEnabled) {
        lLayout.addComponent(new Label(lMessages.getMessage("view.login.disabled"), ContentMode.HTML)); //$NON-NLS-1$
    }

    final CheckBox lCheckbox = new CheckBox(lMessages.getMessage("view.login.chk.label")); //$NON-NLS-1$
    lCheckbox.setValue(inLoginConfig);
    lCheckbox.setEnabled(inEnabled);
    lCheckbox.focus();
    lLayout.addComponent(lCheckbox);

    final Button lSave = new Button(lMessages.getMessage("config.view.button.save")); //$NON-NLS-1$
    lSave.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(final ClickEvent inEvent) {
            inController.saveChange(lCheckbox.getValue());
        }
    });
    lSave.setEnabled(inEnabled);
    lSave.setClickShortcut(KeyCode.ENTER);
    lLayout.addComponent(lSave);
}

From source file:org.rubicone.poc.vpush.uil.sending.SendingUI.java

License:Apache License

private FormLayout createPushMessageSendingForm() {
    FormLayout pushMessageSendingForm = new FormLayout();

    Panel pushMessageSendingPanel = new Panel("push message sending form");
    pushMessageSendingPanel.setContent(pushMessageSendingForm);

    TextField inputField = new TextField("text to send");
    inputField.setValueChangeMode(ValueChangeMode.EAGER);
    pushMessageSendingForm.addComponent(inputField);

    Button sendButton = new Button("send", VaadinIcons.LOCATION_ARROW);
    sendButton.setDisableOnClick(true);/*from   ww w.  j  av a2s .  co m*/
    sendButton.setEnabled(false);
    sendButton.addClickListener(event -> {
        this.broadcaster.broadcast(inputField.getValue());
        this.sentMessages.addComponent(new Label(new Date() + ": " + inputField.getValue()));
        inputField.setValue("");
    });

    inputField.addValueChangeListener(event -> {
        sendButton.setEnabled(!event.getValue().isEmpty());
    });

    pushMessageSendingForm.addComponent(sendButton);

    return pushMessageSendingForm;
}