Example usage for com.vaadin.ui Alignment TOP_RIGHT

List of usage examples for com.vaadin.ui Alignment TOP_RIGHT

Introduction

In this page you can find the example usage for com.vaadin.ui Alignment TOP_RIGHT.

Prototype

Alignment TOP_RIGHT

To view the source code for com.vaadin.ui Alignment TOP_RIGHT.

Click Source Link

Usage

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

License:Open Source License

/**
 * Constructor for creating new instances.
 *
 * @param nodeDao        the node dao instance
 * @param rrdGraphHelper the rrd graph helper instance
 * @param rrdGraphEntry  the entry to be edited
 *///from www. j a v a  2  s .co  m
public GraphSelectionWindow(final NodeDao nodeDao, final RrdGraphHelper rrdGraphHelper,
        final RrdGraphEntry rrdGraphEntry) {
    /**
     * Setting the title
     */
    super("Select RRD graph");

    /**
     * setting up the component
     */
    setModal(true);
    setClosable(false);
    setResizable(false);
    setWidth(50, Unit.PERCENTAGE);
    setHeight(70, Unit.PERCENTAGE);

    /**
     * setting up the container
     */
    final HierarchicalContainer hierarchicalContainer = new HierarchicalContainer();

    hierarchicalContainer.addContainerProperty("id", String.class, null);
    hierarchicalContainer.addContainerProperty("label", String.class, null);
    hierarchicalContainer.addContainerProperty("type", String.class, null);

    hierarchicalContainer.addContainerProperty("nodeId", String.class, null);
    hierarchicalContainer.addContainerProperty("nodeLabel", String.class, null);
    hierarchicalContainer.addContainerProperty("resourceId", String.class, null);
    hierarchicalContainer.addContainerProperty("resourceLabel", String.class, null);
    hierarchicalContainer.addContainerProperty("resourceTypeId", String.class, null);
    hierarchicalContainer.addContainerProperty("resourceTypeLabel", String.class, null);
    hierarchicalContainer.addContainerProperty("graphId", String.class, null);
    hierarchicalContainer.addContainerProperty("graphLabel", String.class, null);
    hierarchicalContainer.addContainerProperty("graphUrl", String.class, null);

    /**
     * filling the container with node data
     */
    List<OnmsNode> onmsNodeList = nodeDao.findAll();

    for (OnmsNode onmsNode : onmsNodeList) {
        Item item = hierarchicalContainer.addItem(onmsNode.getId().toString());
        item.getItemProperty("label").setValue(onmsNode.getLabel() + " (" + onmsNode.getId() + ")");
        item.getItemProperty("id").setValue(onmsNode.getId().toString());
        item.getItemProperty("type").setValue("node");
        item.getItemProperty("nodeId").setValue(onmsNode.getId().toString());
    }

    /**
     * creating a panel for the tree component
     */
    Panel panel = new Panel();

    m_tree = new Tree();
    m_tree.setCaption("Graph");
    m_tree.setSizeFull();
    m_tree.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
    m_tree.setItemCaptionPropertyId("label");
    m_tree.setContainerDataSource(hierarchicalContainer);
    m_tree.setMultiSelect(false);
    m_tree.setNewItemsAllowed(false);
    m_tree.setImmediate(true);

    /**
     * adding en expand listener for lazy loading the resourceType and resource data
     */
    m_tree.addExpandListener(new Tree.ExpandListener() {
        @Override
        public void nodeExpand(Tree.ExpandEvent expandEvent) {
            String itemToExpandId = String.valueOf(expandEvent.getItemId());

            /**
             * if the data has already been loaded, return
             */
            if (m_tree.hasChildren(itemToExpandId)) {
                return;
            }

            Item itemToExpand = m_tree.getItem(expandEvent.getItemId());
            String type = itemToExpand.getItemProperty("type").getValue().toString();

            /**
             * a node is selected
             */
            if ("node".equals(type)) {
                Map<OnmsResourceType, List<OnmsResource>> resourceTypeMap = rrdGraphHelper
                        .getResourceTypeMapForNodeId(
                                String.valueOf(itemToExpand.getItemProperty("id").getValue()));

                for (Map.Entry<OnmsResourceType, List<OnmsResource>> resourceTypeMapEntry : resourceTypeMap
                        .entrySet()) {
                    String newResourceTypeItemId = "node[" + itemToExpandId + "]."
                            + resourceTypeMapEntry.getKey().getName();

                    Item newResourceTypeItem = hierarchicalContainer.addItem(newResourceTypeItemId);

                    newResourceTypeItem.getItemProperty("label")
                            .setValue(resourceTypeMapEntry.getKey().getLabel());
                    newResourceTypeItem.getItemProperty("type").setValue("resourceType");
                    newResourceTypeItem.getItemProperty("nodeId").setValue(itemToExpandId);
                    newResourceTypeItem.getItemProperty("nodeLabel")
                            .setValue(itemToExpand.getItemProperty("label").getValue());
                    newResourceTypeItem.getItemProperty("resourceTypeId").setValue(newResourceTypeItemId);
                    newResourceTypeItem.getItemProperty("resourceTypeLabel")
                            .setValue(resourceTypeMapEntry.getKey().getLabel());

                    m_tree.setParent(newResourceTypeItemId, itemToExpandId);
                    m_tree.setChildrenAllowed(newResourceTypeItemId, true);

                    for (OnmsResource onmsResource : resourceTypeMapEntry.getValue()) {

                        String newResourceItemId = null;

                        try {
                            newResourceItemId = URLDecoder.decode(onmsResource.getId(), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        Item newResourceItem = hierarchicalContainer.addItem(newResourceItemId);

                        newResourceItem.getItemProperty("label").setValue(onmsResource.getLabel());
                        newResourceItem.getItemProperty("type").setValue("resource");
                        newResourceItem.getItemProperty("nodeId").setValue(itemToExpandId);
                        newResourceItem.getItemProperty("nodeLabel")
                                .setValue(itemToExpand.getItemProperty("label").getValue());
                        newResourceItem.getItemProperty("resourceId").setValue(newResourceItemId);
                        newResourceItem.getItemProperty("resourceLabel").setValue(onmsResource.getLabel());
                        newResourceItem.getItemProperty("resourceTypeId").setValue(newResourceTypeItemId);
                        newResourceItem.getItemProperty("resourceTypeLabel")
                                .setValue(newResourceTypeItem.getItemProperty("label").getValue());

                        m_tree.setParent(newResourceItemId, newResourceTypeItemId);
                        m_tree.setChildrenAllowed(newResourceItemId, true);
                    }
                }
            }

            /**
             * a resource is selected
             */
            if ("resource".equals(type)) {
                Map<String, String> map = rrdGraphHelper.getGraphResultsForResourceId(itemToExpandId);
                Map<String, String> titleNameMapping = rrdGraphHelper
                        .getGraphTitleNameMappingForResourceId(itemToExpandId);

                for (Map.Entry<String, String> entry : titleNameMapping.entrySet()) {
                    String newGraphItemId = itemToExpandId + "." + entry.getKey();
                    /*
                                            if (hierarchicalContainer.containsId(newGraphItemId)) {
                    continue;
                                            }
                    */
                    Item newGraphItem = hierarchicalContainer.addItem(newGraphItemId);

                    newGraphItem.getItemProperty("label").setValue(entry.getKey());
                    newGraphItem.getItemProperty("type").setValue("graph");
                    newGraphItem.getItemProperty("nodeId")
                            .setValue(String.valueOf(itemToExpand.getItemProperty("nodeId").getValue()));
                    newGraphItem.getItemProperty("nodeLabel")
                            .setValue(String.valueOf(itemToExpand.getItemProperty("nodeLabel").getValue()));
                    newGraphItem.getItemProperty("resourceId")
                            .setValue(String.valueOf(itemToExpand.getItemProperty("resourceId").getValue()));
                    newGraphItem.getItemProperty("resourceLabel")
                            .setValue(String.valueOf(itemToExpand.getItemProperty("resourceLabel").getValue()));
                    newGraphItem.getItemProperty("resourceTypeId").setValue(
                            String.valueOf(itemToExpand.getItemProperty("resourceTypeId").getValue()));
                    newGraphItem.getItemProperty("resourceTypeLabel").setValue(
                            String.valueOf(itemToExpand.getItemProperty("resourceTypeLabel").getValue()));
                    newGraphItem.getItemProperty("graphId").setValue(newGraphItemId);
                    newGraphItem.getItemProperty("graphLabel").setValue(entry.getKey());
                    newGraphItem.getItemProperty("graphUrl").setValue(map.get(entry.getValue()));

                    m_tree.setParent(newGraphItemId, itemToExpandId);
                    m_tree.setChildrenAllowed(newGraphItemId, false);
                }
            }
        }
    });

    /**
     * adding button to a horizontal layout
     */
    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setMargin(true);
    buttonLayout.setSpacing(true);
    buttonLayout.setWidth("100%");

    final Button cancel = new Button("Cancel");
    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);
    buttonLayout.setComponentAlignment(cancel, Alignment.TOP_RIGHT);

    /**
     * ...and the OK button
     */
    final Button ok = new Button("Select");

    ok.setEnabled(false);

    ok.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (m_tree.getValue() != null) {
                /**
                 * saving the data
                 */
                Item selectedItem = m_tree.getItem(m_tree.getValue());

                rrdGraphEntry.setGraphId(String.valueOf(selectedItem.getItemProperty("graphId").getValue()));
                rrdGraphEntry.setResourceTypeId(
                        String.valueOf(selectedItem.getItemProperty("resourceTypeId").getValue()));
                rrdGraphEntry
                        .setResourceId(String.valueOf(selectedItem.getItemProperty("resourceId").getValue()));
                rrdGraphEntry.setNodeId(String.valueOf(selectedItem.getItemProperty("nodeId").getValue()));

                rrdGraphEntry
                        .setGraphLabel(String.valueOf(selectedItem.getItemProperty("graphLabel").getValue()));
                rrdGraphEntry.setResourceTypeLabel(
                        String.valueOf(selectedItem.getItemProperty("resourceTypeLabel").getValue()));
                rrdGraphEntry.setResourceLabel(
                        String.valueOf(selectedItem.getItemProperty("resourceLabel").getValue()));
                rrdGraphEntry
                        .setNodeLabel(String.valueOf(selectedItem.getItemProperty("nodeLabel").getValue()));

                rrdGraphEntry.setGraphUrl(String.valueOf(selectedItem.getItemProperty("graphUrl").getValue()));

                rrdGraphEntry.update();
            }
            close();
        }
    });

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

    buttonLayout.addComponent(ok);

    /**
     * if data is available expand the required nodes
     */
    if (rrdGraphEntry.getNodeId() != null) {
        m_tree.expandItem(rrdGraphEntry.getNodeId());

        if (rrdGraphEntry.getResourceTypeId() != null) {
            m_tree.expandItem(rrdGraphEntry.getResourceTypeId());

            if (rrdGraphEntry.getResourceId() != null) {
                m_tree.expandItem(rrdGraphEntry.getResourceId());

                /**
                 * and select the specified entry
                 */
                if (rrdGraphEntry.getGraphId() != null) {
                    m_tree.select(rrdGraphEntry.getGraphId());
                }
            }
        }
    }

    /**
     * adding a value change listener that checks if leaf node is selected
     */
    m_tree.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            if (valueChangeEvent.getProperty().getValue() != null) {
                Item selectedItem = m_tree.getItem(valueChangeEvent.getProperty().getValue());
                Object object = selectedItem.getItemProperty("graphId").getValue();

                ok.setEnabled(object != null);
            }
        }
    });

    /**
     * creating the layout and setting the content
     */
    panel.setContent(m_tree);
    panel.setCaption("Graph");
    panel.setSizeFull();

    VerticalLayout verticalLayout = new VerticalLayout();
    verticalLayout.setSizeFull();
    verticalLayout.setMargin(true);
    verticalLayout.addComponent(panel);
    verticalLayout.setExpandRatio(panel, 1.0f);
    verticalLayout.addComponent(buttonLayout);

    setContent(verticalLayout);
}

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
 *//*w w  w  .  j  a  va 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 w ww  .ja va2s  . 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.dashboard.dashlets.SummaryDashlet.java

License:Open Source License

private Component getLegend(String entity) {
    HorizontalLayout horizontalLayout = new HorizontalLayout();

    horizontalLayout.setSpacing(true);//  ww  w  .j av  a2  s. c om
    horizontalLayout.addStyleName("summary");
    horizontalLayout.addStyleName("global");

    Label labelx = new Label(entity);
    labelx.addStyleName("summary-font-legend");

    Image ackdImage = new Image(null, new ThemeResource("img/acknowledged.png"));
    ackdImage.setWidth(16, Sizeable.Unit.PIXELS);

    Image unackdImage = new Image(null, new ThemeResource("img/unacknowledged.png"));
    unackdImage.setWidth(16, Sizeable.Unit.PIXELS);

    Label dummyLabel = new Label();
    dummyLabel.setWidth(32, Sizeable.Unit.PIXELS);

    horizontalLayout.addComponent(labelx);
    horizontalLayout.addComponent(ackdImage);
    horizontalLayout.addComponent(unackdImage);
    horizontalLayout.addComponent(dummyLabel);

    horizontalLayout.setComponentAlignment(ackdImage, Alignment.TOP_RIGHT);
    horizontalLayout.setComponentAlignment(unackdImage, Alignment.TOP_RIGHT);

    horizontalLayout.setExpandRatio(labelx, 4.0f);
    horizontalLayout.setExpandRatio(ackdImage, 1.0f);
    horizontalLayout.setExpandRatio(unackdImage, 1.0f);
    horizontalLayout.setExpandRatio(dummyLabel, 1.0f);

    horizontalLayout.setWidth(375, Sizeable.Unit.PIXELS);

    return horizontalLayout;
}

From source file:org.opennms.features.vaadin.mibcompiler.MibCompilerPanel.java

License:Open Source License

/**
 * Instantiates a new MIB tree panel.//from w  w  w. ja v  a 2  s . com
 *
 * @param dataCollectionDao the OpenNMS Data Collection Configuration DAO 
 * @param eventsDao the OpenNMS Events Configuration DAO
 * @param eventsProxy the OpenNMS Events Proxy
 * @param mibParser the MIB parser
 * @param logger the logger
 */
public MibCompilerPanel(final DataCollectionConfigDao dataCollectionDao, final EventConfDao eventsDao,
        final EventProxy eventsProxy, final MibParser mibParser, final Logger logger) {
    super("MIB Compiler");

    if (dataCollectionDao == null)
        throw new RuntimeException("dataCollectionDao cannot be null.");
    if (eventsProxy == null)
        throw new RuntimeException("eventProxy cannot be null.");
    if (eventsDao == null)
        throw new RuntimeException("eventsDao cannot be null.");

    this.eventsDao = eventsDao;
    this.eventsProxy = eventsProxy;
    this.dataCollectionDao = dataCollectionDao;

    logger.info("Reading MIBs from " + MIBS_ROOT_DIR);

    // Make sure MIB directories exist

    if (!MIBS_COMPILED_DIR.exists()) {
        if (!MIBS_COMPILED_DIR.mkdirs()) {
            throw new RuntimeException(
                    "Unable to create directory for compiled MIBs (" + MIBS_COMPILED_DIR + ")");
        }
    }
    if (!MIBS_PENDING_DIR.exists()) {
        if (!MIBS_PENDING_DIR.mkdirs()) {
            throw new RuntimeException(
                    "Unable to create directory for pending MIBs (" + MIBS_PENDING_DIR + ")");
        }
    }

    // Parser Configuration

    this.mibParser = mibParser;
    mibParser.setMibDirectory(MIBS_COMPILED_DIR);

    // Initialize Toolbar

    MibUploadButton upload = new MibUploadButton(MIBS_PENDING_DIR, MIBS_COMPILED_DIR, logger) {
        @Override
        public void uploadHandler(String filename) {
            addTreeItem(filename, PENDING);
        }
    };

    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(upload);

    // Initialize MIB Tree

    mibsTree = new Tree("MIB Tree");
    initMibTree(logger);
    final Label label = new Label(
            "<p>Use the right-click context menu over the MIB tree files, to display the compiler operations.</p>");
    label.setContentMode(ContentMode.HTML);

    layout.addComponent(label);
    layout.addComponent(mibsTree);

    // Panel Setup
    setSizeFull();
    addStyleName("light");
    layout.setComponentAlignment(upload, Alignment.TOP_RIGHT);
    layout.setExpandRatio(mibsTree, 1);

    setContent(layout);
}

From source file:org.opennms.features.vaadin.mibcompiler.MibConsolePanel.java

License:Open Source License

/**
 * Instantiates a new MIB Console Panel.
 *//*from ww w  . j a va 2 s.  co m*/
public MibConsolePanel() {
    super("MIB Console");
    addStyleName("light");

    Button clearButton = new Button("Clear Log");
    clearButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            logContent.removeAllComponents();
        }
    });

    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(clearButton);
    layout.setComponentAlignment(clearButton, Alignment.TOP_RIGHT);

    logContent = new VerticalLayout();
    layout.addComponent(logContent);

    setSizeFull();

    setContent(layout);
}

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

License:Open Source License

/**
 * The constructor for instantiating this component.
 *
 * @param surveillanceViewService the surveillance view service to be used.
 * @param defs                    the column/row defs
 * @param def                     the def to be edited
 * @param saveActionListener      the listener for the saving action
 *///  www.ja  va2 s .co m
public SurveillanceViewConfigurationCategoryWindow(final SurveillanceViewService surveillanceViewService,
        final Collection<?> defs, final Def def, final SaveActionListener saveActionListener) {
    /**
     * calling the super constructor
     */
    super("Window title");

    /**
     * Check whether this dialog is for a column or row and alter the window title
     */
    if (def instanceof RowDef) {
        super.setCaption("Row definition");
    } else {
        super.setCaption("Column definition");
    }

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

    /**
     * Title and refresh seconds
     */
    final TextField labelField = new TextField();
    labelField.setValue(def.getLabel());
    labelField.setImmediate(true);
    labelField.setCaption("Label");
    labelField.setDescription("Label of this category");
    labelField.setWidth(100, Unit.PERCENTAGE);

    /**
     * Creating a simple validator for the title field
     */
    labelField.addValidator(
            new AbstractStringValidator("Please use an unique name for this column/row definition") {
                @Override
                protected boolean isValidValue(String s) {
                    if ("".equals(s.trim())) {
                        return false;
                    }

                    /**
                     * check if the name clashes with other defs
                     */
                    for (Def defx : (Collection<Def>) defs) {
                        if (defx.getLabel().equals(s)) {
                            if (defx != def) {
                                return false;
                            }
                        }
                    }

                    return true;
                }
            });

    /**
     * Categories table
     */
    final Table categoriesTable = new Table();
    categoriesTable.setSizeFull();
    categoriesTable.setHeight(250.0f, Unit.PIXELS);
    categoriesTable.setCaption("Categories");
    categoriesTable.setSortEnabled(true);
    categoriesTable.addContainerProperty("name", String.class, "");
    categoriesTable.setColumnHeader("name", "Category");
    categoriesTable.setColumnExpandRatio("Category", 1.0f);
    categoriesTable.setSelectable(true);
    categoriesTable.setMultiSelect(true);

    final List<OnmsCategory> categories = surveillanceViewService.getOnmsCategories();
    final Map<Integer, OnmsCategory> categoriesMap = new HashMap<>();

    for (OnmsCategory onmsCategory : categories) {
        categoriesTable.addItem(new Object[] { onmsCategory.getName() }, onmsCategory.getId());
        categoriesMap.put(onmsCategory.getId(), onmsCategory);
        if (def.containsCategory(onmsCategory.getName())) {
            categoriesTable.select(onmsCategory.getId());
        }
    }

    /**
     * Create form layouts...
     */
    FormLayout baseFormLayout = new FormLayout();
    baseFormLayout.setSizeFull();
    baseFormLayout.setMargin(true);
    baseFormLayout.addComponent(labelField);
    baseFormLayout.addComponent(categoriesTable);

    /**
     * Creating the vertical layout...
     */
    VerticalLayout verticalLayout = new VerticalLayout();
    verticalLayout.setSizeFull();
    verticalLayout.addComponent(baseFormLayout);
    verticalLayout.setExpandRatio(baseFormLayout, 1.0f);

    /**
     * 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) {
            Def finalDef = null;

            if (def instanceof RowDef) {
                finalDef = new RowDef();
            }
            if (def instanceof ColumnDef) {
                finalDef = new ColumnDef();
            }

            Set<Object> categories = (Set<Object>) categoriesTable.getValue();

            if (!labelField.isValid()) {
                ((SurveillanceViewsConfigUI) getUI()).notifyMessage("Error",
                        "Please use an unique label for this category", Notification.Type.ERROR_MESSAGE);
                return;
            }

            if (categories.isEmpty()) {
                ((SurveillanceViewsConfigUI) getUI()).notifyMessage("Error",
                        "You must choose at least one surveillance category", Notification.Type.ERROR_MESSAGE);
                return;
            }

            for (Object object : categories) {
                Category category = new Category();
                category.setName(categoriesMap.get(object).getName());
                finalDef.getCategories().add(category);
            }

            finalDef.setLabel(labelField.getValue());
            saveActionListener.save(finalDef);

            close();
        }
    });

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

    verticalLayout.addComponent(horizontalLayout);

    setContent(verticalLayout);
}

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 va  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.BusinessServiceMainLayout.java

License:Open Source License

public BusinessServiceMainLayout(BusinessServiceManager businessServiceManager) {
    m_businessServiceManager = Objects.requireNonNull(businessServiceManager);
    m_table = new BusinessServiceTreeTable(businessServiceManager);

    setSizeFull();/*from  w  w w.  j a  v a2  s .  c  o  m*/

    // Create button
    final Button createButton = UIHelper.createButton("New Business Service", null, FontAwesome.PLUS_SQUARE,
            (Button.ClickListener) event -> {
                final BusinessService businessService = m_businessServiceManager.createBusinessService();
                final BusinessServiceEditWindow window = new BusinessServiceEditWindow(businessService,
                        m_businessServiceManager);
                window.addCloseListener(e -> m_table.refresh());
                getUI().addWindow(window);
            });
    createButton.setId("createButton");

    // Collapse all
    final Button collapseButton = UIHelper.createButton("Collapse All", null, FontAwesome.FOLDER,
            (Button.ClickListener) event -> {
                m_table.getContainerDataSource().getItemIds().forEach(id -> m_table.setCollapsed(id, true));
            });
    collapseButton.setId("collapseButton");

    // Expand all
    final Button expandButton = UIHelper.createButton("Expand All", null, FontAwesome.FOLDER_OPEN,
            (Button.ClickListener) event -> {
                m_table.getContainerDataSource().getItemIds().forEach(id -> m_table.setCollapsed(id, false));
            });
    expandButton.setId("expandButton");

    // Refresh
    final Button refreshButton = UIHelper.createButton("Refresh Table", null, FontAwesome.REFRESH,
            (Button.ClickListener) event -> {
                m_table.refresh();
            });
    refreshButton.setId("refreshButton");

    // Reload daemon
    final Button reloadButton = UIHelper.createButton("Reload Daemon",
            "Reloads the Business Service State Machine", FontAwesome.RETWEET, (Button.ClickListener) event -> {
                m_businessServiceManager.triggerDaemonReload();
            });
    reloadButton.setId("reloadButton");

    // Group the create and collapse buttons on the left
    HorizontalLayout leftButtonGroup = new HorizontalLayout();
    leftButtonGroup.setSpacing(true);
    leftButtonGroup.addComponent(createButton);
    leftButtonGroup.addComponent(collapseButton);
    leftButtonGroup.addComponent(expandButton);
    leftButtonGroup.setDefaultComponentAlignment(Alignment.TOP_LEFT);

    // Group the refresh and reload buttons to the right
    HorizontalLayout rightButtonGroup = new HorizontalLayout();
    rightButtonGroup.setSpacing(true);
    rightButtonGroup.addComponent(refreshButton);
    rightButtonGroup.addComponent(reloadButton);
    rightButtonGroup.setDefaultComponentAlignment(Alignment.TOP_RIGHT);

    // Build the upper layout
    HorizontalLayout upperLayout = new HorizontalLayout();
    upperLayout.setSpacing(true);
    upperLayout.addComponent(leftButtonGroup);
    upperLayout.addComponent(rightButtonGroup);
    upperLayout.setComponentAlignment(leftButtonGroup, Alignment.TOP_LEFT);
    upperLayout.setComponentAlignment(rightButtonGroup, Alignment.TOP_RIGHT);
    upperLayout.setWidth(100, Unit.PERCENTAGE);
    addComponent(upperLayout);

    // Add some space between the upper layout and the table
    Label sz = new Label("");
    sz.setWidth(null);
    sz.setHeight(5, Unit.PIXELS);
    addComponent(sz);

    /**
     * add the table to the layout
     */
    addComponent(m_table);
    setExpandRatio(m_table, 1.0f);

    /**
     * initial refresh of table
     */
    m_table.refresh();
}

From source file:org.opennms.netmgt.vaadin.core.KeyValueInputDialogWindow.java

License:Open Source License

/**
 * Constructor responsible for creating new instances of this class
 *
 * @param caption   the window's title/*from  w  w  w.  j  a va  2  s .  c o m*/
 * @param keyName   the title of the key input field
 * @param valueName the title of the value input field
 */
public KeyValueInputDialogWindow(String caption, String keyName, String valueName) {
    super(caption);

    /**
     * set window properties
     */
    setModal(true);
    setClosable(false);
    setResizable(false);

    /**
     * create the main layout
     */
    VerticalLayout verticalLayout = new VerticalLayout();

    /**
     * add the key input field
     */
    m_keyInputField = new TextField(keyName);

    m_keyInputField.setValue("");
    m_keyInputField.setId("keyField");
    m_keyInputField.selectAll();
    m_keyInputField.setImmediate(true);
    m_keyInputField.focus();

    /**
     * add the value input field
     */
    m_valueInputField = new TextField(valueName);

    m_valueInputField.setValue("");
    m_valueInputField.setId("valueField");
    m_valueInputField.selectAll();
    m_valueInputField.setImmediate(true);

    /**
     * create nested FormLayout instance
     */
    FormLayout formLayout = new FormLayout();
    formLayout.setSizeUndefined();
    formLayout.setMargin(true);
    formLayout.addComponent(m_keyInputField);
    formLayout.addComponent(m_valueInputField);

    /**
     * add the buttons in a horizontal layout
     */
    HorizontalLayout horizontalLayout = new HorizontalLayout();

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

    /**
     * create cancel button
     */
    m_cancelButton = new Button("Cancel");
    m_cancelButton.setId("cancelBtn");
    m_cancelButton.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    m_cancelButton.addClickListener(this);

    horizontalLayout.addComponent(m_cancelButton);
    horizontalLayout.setExpandRatio(m_cancelButton, 1);
    horizontalLayout.setComponentAlignment(m_cancelButton, Alignment.TOP_RIGHT);

    /**
     * create ok button
     */
    m_okButton = new Button("OK");
    m_okButton.setId("okBtn");
    m_okButton.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
    m_okButton.addClickListener(this);

    horizontalLayout.addComponent(m_okButton);
    formLayout.addComponent(horizontalLayout);
    verticalLayout.addComponent(formLayout);

    addFocusListener(new FieldEvents.FocusListener() {
        @Override
        public void focus(FieldEvents.FocusEvent event) {
            if (m_focusKey) {
                m_keyInputField.focus();
            } else {
                m_valueInputField.focus();
            }
        }
    });

    /**
     * the close listener
     */
    addCloseListener(this);

    /**
     * set the content
     */
    setContent(verticalLayout);
}