Example usage for com.vaadin.ui ComboBox ComboBox

List of usage examples for com.vaadin.ui ComboBox ComboBox

Introduction

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

Prototype

public ComboBox() 

Source Link

Document

Constructs an empty combo box without a caption.

Usage

From source file:org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorOptions.java

License:Open Source License

/**
 * Initializes the mode switcher./*  w w w  . j a va  2  s  .  c  o  m*/
 * @param current the current edit mode
 */
private void initModeSwitch(final EditMode current) {

    FormLayout modes = new FormLayout();
    modes.setHeight("100%");
    modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);

    m_modeSelect = new ComboBox();
    m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));

    // add Modes
    m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);
    m_modeSelect.setItemCaption(CmsMessageBundleEditorTypes.EditMode.DEFAULT,
            m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));
    m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);
    m_modeSelect.setItemCaption(CmsMessageBundleEditorTypes.EditMode.MASTER,
            m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));

    // set current mode as selected
    m_modeSelect.setValue(current);

    m_modeSelect.setNewItemsAllowed(false);
    m_modeSelect.setTextInputAllowed(false);
    m_modeSelect.setNullSelectionAllowed(false);

    m_modeSelect.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        public void valueChange(ValueChangeEvent event) {

            m_listener.handleModeChange((EditMode) event.getProperty().getValue());

        }
    });

    modes.addComponent(m_modeSelect);
    m_modeSwitch = modes;
}

From source file:org.opencms.ui.sitemap.CmsLocaleComparePanel.java

License:Open Source License

/**
 * Initializes the locale comparison view.<p>
 *
 * @param id the structure id of the currrent sitemap root entry
 * @param initialComparisonLocale if not null, the initially selected ccomparison locale
 *
 * @throws CmsException if something goes wrong
 *//*  ww w  . jav a  2s  .co m*/
public void initialize(CmsUUID id, Locale initialComparisonLocale) throws CmsException {

    removeAllComponents();
    CmsObject cms = A_CmsUI.getCmsObject();
    CmsResource res = cms.readResource(id);
    m_currentRoot = res;
    CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(res.getRootPath());

    Locale rootLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, res);
    m_rootLocale = rootLocale;
    Locale mainLocale = site.getMainTranslationLocale(null);
    List<Locale> secondaryLocales = site.getSecondaryTranslationLocales();

    List<Locale> possibleLocaleSelections = getMainLocaleSelectOptions(cms, res, mainLocale, secondaryLocales);
    m_rootLocaleSelector = new ComboBox();
    m_rootLocaleSelector.addStyleName("o-sitemap-localeselect");
    m_rootLocaleSelector.setNullSelectionAllowed(false);
    for (Locale selectableLocale : possibleLocaleSelections) {
        m_rootLocaleSelector.addItem(selectableLocale);
        m_rootLocaleSelector.setItemIcon(selectableLocale, FontOpenCms.SPACE);
        m_rootLocaleSelector.setItemCaption(selectableLocale,
                selectableLocale.getDisplayName(A_CmsUI.get().getLocale()));
    }
    m_rootLocaleSelector.setItemIcon(mainLocale, MAIN_LOCALE_ICON);
    m_rootLocaleSelector.setValue(m_rootLocale);
    m_rootLocaleSelector.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("synthetic-access")
        public void valueChange(ValueChangeEvent event) {

            if (!m_handlingLocaleChange) {
                m_handlingLocaleChange = true;
                try {
                    Locale newLocale = (Locale) (event.getProperty().getValue());
                    switchToLocale(newLocale);
                } catch (Exception e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    CmsErrorDialog.showErrorDialog(e);
                } finally {
                    m_handlingLocaleChange = false;
                }
            }
        }
    });

    m_comparisonLocaleSelector = new ComboBox();
    m_comparisonLocaleSelector.addStyleName("o-sitemap-localeselect");
    m_comparisonLocaleSelector.setNullSelectionAllowed(false);

    List<Locale> comparisonLocales = getComparisonLocales();
    Locale selectedComparisonLocale = null;
    for (Locale comparisonLocale : comparisonLocales) {
        m_comparisonLocaleSelector.addItem(comparisonLocale);
        m_comparisonLocaleSelector.setItemIcon(comparisonLocale, FontOpenCms.SPACE);
        m_comparisonLocaleSelector.setItemCaption(comparisonLocale,
                comparisonLocale.getDisplayName(A_CmsUI.get().getLocale()));
        if ((selectedComparisonLocale == null) && !comparisonLocale.equals(m_rootLocale)) {
            selectedComparisonLocale = comparisonLocale;
        }
        if ((initialComparisonLocale != null) && comparisonLocale.equals(initialComparisonLocale)
                && !comparisonLocale.equals(m_rootLocale)) {
            // if an initial comparison locale is given, it should have priority over the first comparison locale
            selectedComparisonLocale = comparisonLocale;
        }

    }
    m_comparisonLocale = selectedComparisonLocale;
    m_comparisonLocaleSelector.setValue(selectedComparisonLocale);
    m_comparisonLocaleSelector.setItemIcon(mainLocale, MAIN_LOCALE_ICON);

    m_comparisonLocaleSelector.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("synthetic-access")
        public void valueChange(ValueChangeEvent event) {

            if (!m_handlingLocaleChange) {
                m_handlingLocaleChange = true;
                try {
                    Locale locale = (Locale) (event.getProperty().getValue());
                    if (m_rootLocale.equals(locale)) {
                        Locale oldComparisonLocale = m_comparisonLocale;
                        if (getLocaleGroup().getResourcesByLocale().keySet().contains(oldComparisonLocale)) {
                            m_comparisonLocale = locale;
                            switchToLocale(oldComparisonLocale);
                            updateLocaleWidgets();
                        } else {
                            Notification.show(CmsVaadinUtils.getMessageText(
                                    Messages.GUI_LOCALECOMPARE_CANNOT_SWITCH_COMPARISON_LOCALE_0));
                            m_comparisonLocaleSelector.setValue(oldComparisonLocale);
                        }
                    } else {
                        m_comparisonLocale = locale;
                        updateLocaleWidgets();
                        initTree(m_currentRoot);
                    }

                } catch (Exception e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    CmsErrorDialog.showErrorDialog(e);
                } finally {
                    m_handlingLocaleChange = false;
                }
            }
        }
    });

    CssLayout localeSelectors = new CssLayout();
    localeSelectors.addStyleName(OpenCmsTheme.SITEMAP_LOCALE_BAR);

    m_rootLocaleSelector.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOCALECOMPARE_MAIN_LOCALE_0));
    m_comparisonLocaleSelector
            .setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOCALECOMPARE_COMPARISON_LOCALE_0));

    localeSelectors.setWidth("100%");
    localeSelectors.addComponent(m_rootLocaleSelector);
    localeSelectors.addComponent(m_comparisonLocaleSelector);
    // localeSelectors.setComponentAlignment(wrapper2, Alignment.MIDDLE_RIGHT);

    setSpacing(true);
    addComponent(localeSelectors);
    addComponent(m_treeContainer);
    m_treeContainer.setWidth("100%");
    initTree(res);
}

From source file:org.opencms.workplace.tools.git.ui.CmsGitToolOptionsPanel.java

License:Open Source License

/**
 * Creates a new module selector, containing only the modules for which no check box is already displayed.<p>
 *
 * @return the new module selector//from   w  ww .  j  av a2 s  .c o m
 */
private ComboBox createModuleSelector() {

    ComboBox result = new ComboBox();
    result.setPageLength(20);
    result.setWidth("350px");
    result.setFilteringMode(FilteringMode.CONTAINS);
    result.setNewItemsAllowed(false);
    result.setNullSelectionAllowed(false);
    List<String> moduleNames = Lists.newArrayList();
    for (CmsModule module : OpenCms.getModuleManager().getAllInstalledModules()) {
        String moduleName = module.getName();
        if (!m_moduleCheckboxes.containsKey(moduleName)) {
            moduleNames.add(moduleName);
        }
    }
    Collections.sort(moduleNames);
    for (String moduleName : moduleNames) {
        result.addItem(moduleName);
    }

    return result;
}

From source file:org.opennms.features.topology.plugins.ncs.ShowNCSPathOperation.java

License:Open Source License

@Override
public void execute(List<VertexRef> targets, final OperationContext operationContext) {
    //Get the current NCS criteria from here you can get the foreignIds foreignSource and deviceA and Z
    for (Criteria criterium : operationContext.getGraphContainer().getCriteria()) {
        try {//from ww w .ja  va  2  s. co  m
            NCSServiceCriteria ncsCriterium = (NCSServiceCriteria) criterium;
            if (ncsCriterium.getServiceCount() > 0) {
                m_storedCriteria = ncsCriterium;
                break;
            }
        } catch (ClassCastException e) {
        }
    }

    final VertexRef defaultVertRef = targets.get(0);
    final SelectionManager selectionManager = operationContext.getGraphContainer().getSelectionManager();
    final Collection<VertexRef> vertexRefs = getVertexRefsForNCSService(m_storedCriteria); //selectionManager.getSelectedVertexRefs();

    final UI mainWindow = operationContext.getMainWindow();

    final Window ncsPathPrompt = new Window("Show NCS Path");
    ncsPathPrompt.setModal(true);
    ncsPathPrompt.setResizable(false);
    ncsPathPrompt.setWidth("300px");
    ncsPathPrompt.setHeight("220px");

    //Items used in form field
    final PropertysetItem item = new PropertysetItem();
    item.addItemProperty("Device A", new ObjectProperty<String>("", String.class));
    item.addItemProperty("Device Z", new ObjectProperty<String>("", String.class));

    FormFieldFactory fieldFactory = new FormFieldFactory() {
        private static final long serialVersionUID = 1L;

        @Override
        public Field<?> createField(Item item, Object propertyId, Component uiContext) {
            String pid = (String) propertyId;

            ComboBox select = new ComboBox();
            for (VertexRef vertRef : vertexRefs) {
                select.addItem(vertRef.getId());
                select.setItemCaption(vertRef.getId(), vertRef.getLabel());
            }
            select.setNewItemsAllowed(false);
            select.setNullSelectionAllowed(false);
            select.setImmediate(true);
            select.setScrollToSelectedItem(true);

            if ("Device A".equals(pid)) {
                select.setCaption("Device A");
            } else {
                select.setCaption("Device Z");

            }

            return select;
        }

    };

    final Form promptForm = new Form() {

        @Override
        public void commit() {
            String deviceA = (String) getField("Device A").getValue();
            String deviceZ = (String) getField("Device Z").getValue();

            if (deviceA.equals(deviceZ)) {
                Notification.show("Device A and Device Z cannot be the same",
                        Notification.Type.WARNING_MESSAGE);
                throw new Validator.InvalidValueException("Device A and Device Z cannot be the same");
            }

            OnmsNode nodeA = m_nodeDao.get(Integer.valueOf(deviceA));
            String deviceANodeForeignId = nodeA.getForeignId();
            //Use nodeA's foreignSource, deviceZ should have the same foreignSource. It's an assumption
            // which might need to changed in the future. Didn't want to hard code it it "space" if they
            // change it in the future
            String nodeForeignSource = nodeA.getForeignSource();

            String deviceZNodeForeignId = m_nodeDao.get(Integer.valueOf(deviceZ)).getForeignId();

            NCSComponent ncsComponent = m_dao.get(m_storedCriteria.getServiceIds().get(0));
            String foreignSource = ncsComponent.getForeignSource();
            String foreignId = ncsComponent.getForeignId();
            String serviceName = ncsComponent.getName();
            try {
                NCSServicePath path = getNcsPathProvider().getPath(foreignId, foreignSource,
                        deviceANodeForeignId, deviceZNodeForeignId, nodeForeignSource, serviceName);

                if (path.getStatusCode() == 200) {
                    NCSServicePathCriteria criteria = new NCSServicePathCriteria(path.getEdges());
                    m_serviceManager.registerCriteria(criteria,
                            operationContext.getGraphContainer().getSessionId());

                    //Select only the vertices in the path
                    selectionManager.setSelectedVertexRefs(path.getVertices());
                } else {
                    LoggerFactory.getLogger(this.getClass()).warn(
                            "An error occured while retrieving the NCS Path, Juniper NetworkAppsApi send error code: "
                                    + path.getStatusCode());
                    mainWindow.showNotification("An error occurred while retrieving the NCS Path\nStatus Code: "
                            + path.getStatusCode(), Notification.TYPE_ERROR_MESSAGE);
                }

            } catch (Exception e) {

                if (e.getCause() instanceof ConnectException) {
                    LoggerFactory.getLogger(this.getClass())
                            .warn("Connection Exception Occurred while retreiving path {}", e);
                    Notification.show("Connection Refused when attempting to reach the NetworkAppsApi",
                            Notification.Type.TRAY_NOTIFICATION);
                } else if (e.getCause() instanceof HttpOperationFailedException) {
                    HttpOperationFailedException httpException = (HttpOperationFailedException) e.getCause();
                    if (httpException.getStatusCode() == 401) {
                        LoggerFactory.getLogger(this.getClass()).warn(
                                "Authentication error when connecting to NetworkAppsApi {}", httpException);
                        Notification.show(
                                "Authentication error when connecting to NetworkAppsApi, please check the username and password",
                                Notification.Type.TRAY_NOTIFICATION);
                    } else {
                        LoggerFactory.getLogger(this.getClass())
                                .warn("An error occured while retrieving the NCS Path {}", httpException);
                        Notification.show("An error occurred while retrieving the NCS Path\n"
                                + httpException.getMessage(), Notification.Type.TRAY_NOTIFICATION);
                    }
                } else if (e.getCause() instanceof Validator.InvalidValueException) {
                    Notification.show(e.getMessage(), Notification.Type.ERROR_MESSAGE);

                } else {

                    LoggerFactory.getLogger(this.getClass()).warn("Exception Occurred while retreiving path {}",
                            e);
                    Notification.show(
                            "An error occurred while calculating the path please check the karaf.log file for the exception: \n"
                                    + e.getMessage(),
                            Notification.Type.TRAY_NOTIFICATION);
                }
            }
        }

    };

    promptForm.setBuffered(true);
    promptForm.setFormFieldFactory(fieldFactory);
    promptForm.setItemDataSource(item);

    Button ok = new Button("OK");
    ok.addClickListener(new ClickListener() {

        private static final long serialVersionUID = -2742886456007926688L;

        @Override
        public void buttonClick(ClickEvent event) {
            promptForm.commit();
            mainWindow.removeWindow(ncsPathPrompt);
        }

    });
    promptForm.getFooter().addComponent(ok);

    Button cancel = new Button("Cancel");
    cancel.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -9026067481179449095L;

        @Override
        public void buttonClick(ClickEvent event) {
            mainWindow.removeWindow(ncsPathPrompt);
        }

    });
    promptForm.getFooter().addComponent(cancel);
    ncsPathPrompt.setContent(promptForm);
    mainWindow.addWindow(ncsPathPrompt);
    promptForm.getField("Device A").setValue(defaultVertRef.getId());
}

From source file:org.opennms.features.vaadin.config.DataCollectionGroupAdminPanel.java

License:Open Source License

/**
 * Instantiates a new data collection group administration panel.
 *
 * @param dataCollectionDao the OpenNMS data collection configuration DAO
 *///  w  ww.  jav  a 2s  .c  om
public DataCollectionGroupAdminPanel(final DataCollectionConfigDao dataCollectionDao) {
    setCaption("Data Collection Groups");

    final HorizontalLayout toolbar = new HorizontalLayout();
    toolbar.setMargin(true);

    final Label comboLabel = new Label("Select Data Collection Group File");
    toolbar.addComponent(comboLabel);
    toolbar.setComponentAlignment(comboLabel, Alignment.MIDDLE_LEFT);

    final File datacollectionDir = new File(ConfigFileConstants.getFilePathString(), "datacollection");
    final ComboBox dcGroupSource = new ComboBox();
    toolbar.addComponent(dcGroupSource);
    dcGroupSource.setImmediate(true);
    dcGroupSource.setNullSelectionAllowed(false);
    dcGroupSource.setContainerDataSource(new XmlFileContainer(datacollectionDir, false));
    dcGroupSource.setItemCaptionPropertyId(FilesystemContainer.PROPERTY_NAME);
    dcGroupSource.addValueChangeListener(new ComboBox.ValueChangeListener() {
        @Override
        public void valueChange(ValueChangeEvent event) {
            final File file = (File) event.getProperty().getValue();
            if (file == null)
                return;
            try {
                LOG.info("Loading data collection data from {}", file);
                DatacollectionGroup dcGroup = JaxbUtils.unmarshal(DatacollectionGroup.class, file);
                m_selectedGroup = dcGroup.getName();
                addDataCollectionGroupPanel(dataCollectionDao, file, dcGroup);
            } catch (Exception e) {
                LOG.error("an error ocurred while parsing the data collection configuration {}: {}", file,
                        e.getMessage(), e);
                Notification.show("Can't parse file " + file + " because " + e.getMessage());
            }
        }
    });

    final Button add = new Button("Add New Data Collection File");
    toolbar.addComponent(add);
    add.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            PromptWindow w = new PromptWindow("New Data Collection Group", "Group Name") {
                @Override
                public void textFieldChanged(String fieldValue) {
                    File file = new File(datacollectionDir, fieldValue.replaceAll(" ", "_") + ".xml");
                    LOG.info("Adding new data collection file {}", file);
                    DatacollectionGroup dcGroup = new DatacollectionGroup();
                    dcGroup.setName(fieldValue);
                    addDataCollectionGroupPanel(dataCollectionDao, file, dcGroup);
                }
            };
            getUI().addWindow(w);
        }
    });

    final Button remove = new Button("Remove Selected Data Collection File");
    toolbar.addComponent(remove);
    remove.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            if (dcGroupSource.getValue() == null) {
                Notification.show("Please select a data collection group configuration file.");
                return;
            }
            final File file = (File) dcGroupSource.getValue();
            ConfirmDialog.show(getUI(), "Are you sure?", "Do you really want to remove the file "
                    + file.getName()
                    + "?\nThis cannot be undone and OpenNMS won't be able to collect the metrics defined on this file.",
                    "Yes", "No", new ConfirmDialog.Listener() {
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                LOG.info("deleting file {}", file);
                                if (file.delete()) {
                                    try {
                                        // Updating datacollection-config.xml
                                        File configFile = ConfigFileConstants
                                                .getFile(ConfigFileConstants.DATA_COLLECTION_CONF_FILE_NAME);
                                        DatacollectionConfig config = JaxbUtils
                                                .unmarshal(DatacollectionConfig.class, configFile);
                                        boolean modified = false;
                                        for (SnmpCollection collection : config.getSnmpCollections()) {
                                            for (Iterator<IncludeCollection> it = collection
                                                    .getIncludeCollections().iterator(); it.hasNext();) {
                                                IncludeCollection ic = it.next();
                                                if (m_selectedGroup != null && m_selectedGroup
                                                        .equals(ic.getDataCollectionGroup())) {
                                                    it.remove();
                                                    modified = true;
                                                }
                                            }
                                        }
                                        if (modified) {
                                            LOG.info("updating data colleciton configuration on {}.",
                                                    configFile);
                                            JaxbUtils.marshal(config, new FileWriter(configFile));
                                        }
                                        // Updating UI Components
                                        dcGroupSource.select(null);
                                        removeDataCollectionGroupPanel();
                                    } catch (Exception e) {
                                        LOG.error(
                                                "an error ocurred while saving the data collection configuration: {}",
                                                e.getMessage(), e);
                                        Notification.show(
                                                "Can't save data collection configuration. " + e.getMessage(),
                                                Notification.Type.ERROR_MESSAGE);
                                    }
                                } else {
                                    Notification.show("Cannot delete file " + file,
                                            Notification.Type.WARNING_MESSAGE);
                                }
                            }
                        }
                    });
        }
    });

    addComponent(toolbar);
    addComponent(new Label(""));
    setComponentAlignment(toolbar, Alignment.MIDDLE_RIGHT);
}

From source file:org.opennms.features.vaadin.config.EventAdminApplication.java

License:Open Source License

@Override
public void init(VaadinRequest request) {
    if (eventProxy == null)
        throw new RuntimeException("eventProxy cannot be null.");
    if (eventConfDao == null)
        throw new RuntimeException("eventConfDao cannot be null.");

    final VerticalLayout layout = new VerticalLayout();

    final HorizontalLayout toolbar = new HorizontalLayout();
    toolbar.setMargin(true);//from  w w w. j  av a  2 s  .  co  m

    final Label comboLabel = new Label("Select Events Configuration File");
    toolbar.addComponent(comboLabel);
    toolbar.setComponentAlignment(comboLabel, Alignment.MIDDLE_LEFT);

    final File eventsDir = new File(ConfigFileConstants.getFilePathString(), "events");
    final XmlFileContainer container = new XmlFileContainer(eventsDir, true);
    container.addExcludeFile("default.events.xml"); // This is a protected file, should not be updated.
    final ComboBox eventSource = new ComboBox();
    toolbar.addComponent(eventSource);
    eventSource.setImmediate(true);
    eventSource.setNullSelectionAllowed(false);
    eventSource.setContainerDataSource(container);
    eventSource.setItemCaptionPropertyId(FilesystemContainer.PROPERTY_NAME);
    eventSource.addValueChangeListener(new ComboBox.ValueChangeListener() {
        @Override
        public void valueChange(ValueChangeEvent event) {
            final File file = (File) event.getProperty().getValue();
            if (file == null)
                return;
            try {
                LOG.info("Loading events from {}", file);
                final Events events = JaxbUtils.unmarshal(Events.class, file);
                addEventPanel(layout, file, events);
            } catch (Exception e) {
                LOG.error("an error ocurred while saving the event configuration {}: {}", file, e.getMessage(),
                        e);
                Notification.show("Can't parse file " + file + " because " + e.getMessage());
            }
        }
    });

    final Button add = new Button("Add New Events File");
    toolbar.addComponent(add);
    add.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            PromptWindow w = new PromptWindow("New Events Configuration", "Events File Name") {
                @Override
                public void textFieldChanged(String fieldValue) {
                    final File file = new File(eventsDir, normalizeFilename(fieldValue));
                    LOG.info("Adding new events file {}", file);
                    final Events events = new Events();
                    addEventPanel(layout, file, events);
                }
            };
            addWindow(w);
        }
    });

    final Button remove = new Button("Remove Selected Events File");
    toolbar.addComponent(remove);
    remove.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            if (eventSource.getValue() == null) {
                Notification.show("Please select an event configuration file.");
                return;
            }
            final File file = (File) eventSource.getValue();
            ConfirmDialog.show(getUI(), "Are you sure?", "Do you really want to remove the file "
                    + file.getName()
                    + "?\nThis cannot be undone and OpenNMS won't be able to handle the events configured on this file.",
                    "Yes", "No", new ConfirmDialog.Listener() {
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                LOG.info("deleting file {}", file);
                                if (file.delete()) {
                                    try {
                                        // Updating eventconf.xml
                                        boolean modified = false;
                                        File configFile = ConfigFileConstants
                                                .getFile(ConfigFileConstants.EVENT_CONF_FILE_NAME);
                                        Events config = JaxbUtils.unmarshal(Events.class, configFile);
                                        for (Iterator<String> it = config.getEventFileCollection()
                                                .iterator(); it.hasNext();) {
                                            String fileName = it.next();
                                            if (file.getAbsolutePath().contains(fileName)) {
                                                it.remove();
                                                modified = true;
                                            }
                                        }
                                        if (modified) {
                                            JaxbUtils.marshal(config, new FileWriter(configFile));
                                            EventBuilder eb = new EventBuilder(
                                                    EventConstants.EVENTSCONFIG_CHANGED_EVENT_UEI, "WebUI");
                                            eventProxy.send(eb.getEvent());
                                        }
                                        // Updating UI Components
                                        eventSource.select(null);
                                        if (layout.getComponentCount() > 1)
                                            layout.removeComponent(layout.getComponent(1));
                                    } catch (Exception e) {
                                        LOG.error("an error ocurred while saving the event configuration: {}",
                                                e.getMessage(), e);
                                        Notification.show("Can't save event configuration. " + e.getMessage(),
                                                Notification.Type.ERROR_MESSAGE);
                                    }
                                } else {
                                    Notification.show("Cannot delete file " + file,
                                            Notification.Type.WARNING_MESSAGE);
                                }
                            }
                        }
                    });
        }
    });

    layout.addComponent(toolbar);
    layout.addComponent(new Label(""));
    layout.setComponentAlignment(toolbar, Alignment.MIDDLE_RIGHT);

    setContent(layout);
}

From source file:org.opennms.features.vaadin.datacollection.MibObjFieldFactory.java

License:Open Source License

@Override
public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) {
    if (propertyId.equals("oid")) {
        final TextField field = new TextField();
        field.setSizeFull();/*from  w  w  w. j  a va  2 s  .co m*/
        field.setRequired(true);
        field.setImmediate(true);
        field.addValidator(new RegexpValidator("^\\.[.\\d]+$", "Invalid OID {0}"));
        return field;
    }
    if (propertyId.equals("instance")) {
        final ComboBox field = new ComboBox();
        field.setSizeFull();
        field.setRequired(true);
        field.setImmediate(true);
        field.setNullSelectionAllowed(false);
        field.setNewItemsAllowed(true);
        field.setNewItemHandler(new NewItemHandler() {
            @Override
            public void addNewItem(String newItemCaption) {
                if (!field.containsId(newItemCaption)) {
                    field.addItem(newItemCaption);
                    field.setValue(newItemCaption);
                }
            }
        });
        field.addItem("0");
        field.addItem("ifIndex");
        for (String rt : resourceTypes) {
            field.addItem(rt);
        }
        return field;
    }
    if (propertyId.equals("alias")) {
        final TextField field = new TextField();
        field.setSizeFull();
        field.setRequired(true);
        field.setImmediate(true);
        field.addValidator(new StringLengthValidator(
                "Invalid alias. It should not contain more than 19 characters.", 1, 19, false));
        return field;
    }
    if (propertyId.equals("type")) {
        final TextField field = new TextField();
        field.setSizeFull();
        field.setRequired(true);
        field.setImmediate(true);
        field.addValidator(new RegexpValidator(
                "^(?i)(counter|gauge|timeticks|integer|octetstring|string)?\\d*$", // Based on NumericAttributeType and StringAttributeType
                "Invalid type {0}. Valid types are: counter, gauge, timeticks, integer, octetstring, string"));
        return field;
    }
    return null;
}

From source file:org.opennms.features.vaadin.datacollection.RrdField.java

License:Open Source License

/**
 * Instantiates a new RRD field./*from   ww w. j a v a  2 s  . c o  m*/
 */
public RrdField() {
    step.setRequired(true);
    step.setImmediate(true);
    step.setValidationVisible(true);
    step.setNullSettingAllowed(false);
    step.setConverter(new StringToIntegerConverter());

    table.addStyleName("light");
    table.setVisibleColumns(new Object[] { "cf", "xff", "steps", "rows" });
    table.setColumnHeaders(new String[] { "Consolidation Function", "XFF", "Steps", "Rows" });
    table.setEditable(!isReadOnly());
    table.setSelectable(true);
    table.setImmediate(true);
    table.setHeight("125px");
    table.setWidth("100%");
    table.setTableFieldFactory(new DefaultFieldFactory() {
        @Override
        public Field<?> createField(Container container, Object itemId, Object propertyId,
                Component uiContext) {
            if (propertyId.equals("cf")) {
                final ComboBox field = new ComboBox();
                field.setImmediate(true);
                field.setRequired(true);
                field.setNullSelectionAllowed(false);
                field.addItem("AVERAGE");
                field.addItem("MIN");
                field.addItem("MAX");
                field.addItem("LAST");
                return field;
            }
            if (propertyId.equals("steps") || propertyId.equals("rows")) {
                final TextField field = new TextField();
                field.setImmediate(true);
                field.setRequired(true);
                field.setNullSettingAllowed(false);
                field.setConverter(new StringToIntegerConverter());
                return field;
            }
            if (propertyId.equals("xff")) {
                final TextField field = new TextField();
                field.setImmediate(true);
                field.setRequired(true);
                field.setNullSettingAllowed(false);
                field.setConverter(new StringToDoubleConverter());
                return field;
            }
            return null;
        }
    });

    toolbar.addComponent(add);
    toolbar.addComponent(delete);
    toolbar.setVisible(table.isEditable());
}

From source file:org.opennms.features.vaadin.events.MaskElementField.java

License:Open Source License

/**
 * Instantiates a new mask element field.
 *
 * @param caption the caption//from w  ww . ja va  2s. c o m
 */
public MaskElementField(String caption) {
    setCaption(caption);
    table.addStyleName("light");
    table.setVisibleColumns(new Object[] { "mename", "mevalueCollection" });
    table.setColumnHeader("mename", "Element Name");
    table.setColumnHeader("mevalueCollection", "Element Values");
    table.setColumnExpandRatio("mevalueCollection", 1);
    table.setEditable(!isReadOnly());
    table.setSelectable(true);
    table.setHeight("125px");
    table.setWidth("100%");
    table.setTableFieldFactory(new DefaultFieldFactory() {
        @Override
        public Field<?> createField(Container container, Object itemId, Object propertyId,
                Component uiContext) {
            if (propertyId.equals("mename")) {
                final ComboBox field = new ComboBox();
                field.setSizeFull();
                field.setRequired(true);
                field.setImmediate(true);
                field.setNullSelectionAllowed(false);
                field.setNewItemsAllowed(false);
                field.addItem(Maskelement.TAG_UEI);
                field.addItem(Maskelement.TAG_SOURCE);
                field.addItem(Maskelement.TAG_NODEID);
                field.addItem(Maskelement.TAG_HOST);
                field.addItem(Maskelement.TAG_INTERFACE);
                field.addItem(Maskelement.TAG_SNMPHOST);
                field.addItem(Maskelement.TAG_SERVICE);
                field.addItem(Maskelement.TAG_SNMP_EID);
                field.addItem(Maskelement.TAG_SNMP_SPECIFIC);
                field.addItem(Maskelement.TAG_SNMP_GENERIC);
                field.addItem(Maskelement.TAG_SNMP_COMMUNITY);
                return field;
            }
            if (propertyId.equals("mevalueCollection")) {
                final TextField field = new TextField();
                field.setConverter(new CsvListConverter());
                return field;
            }
            return super.createField(container, itemId, propertyId, uiContext);
        }
    });
    toolbar.addComponent(add);
    toolbar.addComponent(delete);
    toolbar.setVisible(table.isEditable());
}

From source file:org.ow2.sirocco.cloudmanager.MyUI.java

License:Open Source License

@Override
protected void init(final VaadinRequest request) {
    this.userName = request.getUserPrincipal().getName();
    this.identityContext.setUserName(this.userName);

    this.getPage().setTitle("Sirocco Dashboard");
    final VerticalLayout layout = new VerticalLayout();
    layout.setSizeFull();/*from   w  ww.j  a v  a  2 s . c  o m*/
    this.setContent(layout);

    // Top header *********************
    HorizontalLayout header = new HorizontalLayout();
    header.setMargin(true);
    header.setWidth("100%");
    header.setHeight("70px");
    header.setStyleName("topHeader");

    // logo
    Image image = new Image(null, new ThemeResource("img/sirocco_small_logo.png"));
    header.addComponent(image);

    // spacer
    Label spacer = new Label();
    spacer.setWidth("100%");
    header.addComponent(spacer);
    header.setExpandRatio(spacer, 1.0f);

    HorizontalLayout rightButtons = new HorizontalLayout();
    rightButtons.setStyleName("topHeader");
    rightButtons.setSpacing(true);

    this.userName = request.getUserPrincipal().getName();
    User user = null;
    try {
        user = this.userManager.getUserByUsername(this.userName);
    } catch (CloudProviderException e) {
        e.printStackTrace();
    }

    Label label = new Label("Tenant:");
    label.setStyleName("topHeaderLabel");
    rightButtons.addComponent(label);
    final ComboBox tenantSelect = new ComboBox();
    tenantSelect.setTextInputAllowed(false);
    tenantSelect.setNullSelectionAllowed(false);
    for (Tenant tenant : user.getTenants()) {
        tenantSelect.addItem(tenant.getName());
    }
    tenantSelect.setValue(user.getTenants().iterator().next().getName());
    tenantSelect.addValueChangeListener(new Property.ValueChangeListener() {

        @Override
        public void valueChange(final ValueChangeEvent event) {
            Notification.show("Switching to tenant " + tenantSelect.getValue());

        }
    });
    tenantSelect.setImmediate(true);
    rightButtons.addComponent(tenantSelect);

    this.tenantId = user.getTenants().iterator().next().getUuid();
    this.identityContext.setTenantId(this.tenantId);

    // logged user name

    label = new Label("Logged in as: " + this.userName);
    label.setStyleName("topHeaderLabel");
    rightButtons.addComponent(label);

    // sign out button
    Button button = new Button("Sign Out");
    // button.setStyleName(BaseTheme.BUTTON_LINK);
    button.addClickListener(new Button.ClickListener() {
        public void buttonClick(final ClickEvent event) {
            MyUI.this.logout();
        }
    });
    rightButtons.addComponent(button);

    header.addComponent(rightButtons);
    layout.addComponent(header);

    // Split view
    HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
    splitPanel.setSizeFull();
    splitPanel.setFirstComponent(this.createLeftMenu());

    this.inventoryContainer = new VerticalLayout();
    this.inventoryContainer.setSizeFull();

    this.inventoryContainer.addComponent(this.machineView);

    splitPanel.setSecondComponent(this.inventoryContainer);
    splitPanel.setSplitPosition(15);

    layout.addComponent(splitPanel);
    layout.setExpandRatio(splitPanel, 1.0f);

    this.listenToNotifications();

}