Example usage for com.vaadin.ui Window setWidth

List of usage examples for com.vaadin.ui Window setWidth

Introduction

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

Prototype

@Override
    public void setWidth(String width) 

Source Link

Usage

From source file:org.geant.sat.ui.EntityListViewer.java

License:BSD License

/**
 * Add entity click handler - creates a sub window for user to enter the
 * data./*from   w w  w .jav  a2s .  co m*/
 * 
 * @param event
 *            button click event.
 */
private void addEntity(ClickEvent event) {

    // We create a simple window for user to enter entity information
    // no declarative design used, we form it locally
    Window subWindowNewEntity = new Window(getString("lang.window.newentity.title"));
    subWindowNewEntity.setModal(true);
    subWindowNewEntity.setWidth("50%");
    VerticalLayout subContent = new VerticalLayout();
    TextField field = new TextField(getString("lang.window.newentity.textFieldName"));
    field.setWidth("80%");
    subContent.addComponent(field, 0);
    field = new TextField(getString("lang.window.newentity.textFieldDescription"));
    field.setWidth("80%");
    subContent.addComponent(field, 1);
    Button okButton = new Button(getString("lang.window.newentity.buttonCreate"));
    subContent.addComponent(okButton, 2);
    okButton.addClickListener(this::addedEntity);
    Button cancelButton = new Button(getString("lang.window.newentity.buttonCancel"));
    subContent.addComponent(cancelButton, 3);
    cancelButton.addClickListener(this::canceledEntityAdd);
    subWindowNewEntity.setContent(subContent);
    subWindowNewEntity.center();
    getMainUI().addWindow(subWindowNewEntity);

}

From source file:org.geant.sat.ui.ScheduleSurveyViewer.java

License:BSD License

/**
 * Creates a subwindow for editing assessor details of entity.
 * /*from  w  ww .j  ava  2s  . com*/
 * @param details
 *            entity
 */
private void editAssessors(EntityDetails details) {
    Window subWindowNewEntity = new Window(getString("lang.window.surveyschedule.editassessors.title"));
    subWindowNewEntity.setWidth("80%");
    subWindowNewEntity.setModal(true);
    VerticalLayout subContent = new VerticalLayout();
    subContent.setWidth("100%");
    TwinColSelect<AssessorDetails> selectAssessors = new TwinColSelect<>(
            getString("lang.window.newentity.editassessors.assessors"));
    selectAssessors.setItemCaptionGenerator(new AssessorDetailsHelper());
    selectAssessors.setWidth("100%");
    selectAssessors.setData(details);
    ListAssessorsResponse resp = getMainUI().getSatApiClient().getAssessors();
    if (!verifySuccess(resp)) {
        return;
    }
    List<AssessorDetails> assessorDetails = resp.getAssessors();
    selectAssessors.setItems(assessorDetails);
    selectAssessors.updateSelection(
            AssessorDetailsHelper.selectionToSet(assessorDetails, details.getAssessors()),
            new HashSet<AssessorDetails>());
    subContent.addComponent(selectAssessors, 0);
    Button editButton = new Button(getString("lang.window.newentity.buttonModify"));
    subContent.addComponent(editButton, 1);
    editButton.addClickListener(this::editedAssessors);
    Button cancelButton = new Button(getString("lang.window.newentity.buttonCancel"));
    subContent.addComponent(cancelButton, 2);
    cancelButton.addClickListener(this::canceledEditAssessors);
    subWindowNewEntity.setContent(subContent);
    getMainUI().addWindow(subWindowNewEntity);
}

From source file:org.ikasan.dashboard.ui.administration.panel.UserDirectoriesPanel.java

License:BSD License

protected void init() {
    Label userDirectories = new Label("User Directories");
    userDirectories.setStyleName(ValoTheme.LABEL_HUGE);

    Label parapraphOne = new Label();
    parapraphOne.setCaptionAsHtml(true);
    parapraphOne.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " The table below shows the user directories currently configured for Ikasan.");
    parapraphOne.addStyleName(ValoTheme.LABEL_TINY);
    parapraphOne.addStyleName(ValoTheme.LABEL_LIGHT);

    Label parapraphTwo = new Label();
    parapraphTwo.setCaptionAsHtml(true);
    parapraphTwo.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " The order of the directory is the order in which it will be searched for users and groups."
            + " It is recommended that each user exists in a single directory.");
    parapraphTwo.addStyleName(ValoTheme.LABEL_TINY);
    parapraphTwo.addStyleName(ValoTheme.LABEL_LIGHT);

    this.mainLayout.setWidth("100%");
    this.mainLayout.setSpacing(true);

    this.mainLayout.addComponent(userDirectories);
    this.mainLayout.addComponent(parapraphOne);
    this.mainLayout.addComponent(parapraphTwo);

    Button newDirectoryButton = new Button("Add Directory");
    newDirectoryButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            final UserDirectoryManagementPanel authMethodPanel = new UserDirectoryManagementPanel(
                    new AuthenticationMethod(), securityService, authenticationProviderFactory, ldapService);

            Window window = new Window("Configure User Directory");
            window.setModal(true);/*w w w  .j a  v a  2s  . c  o m*/
            window.setHeight("90%");
            window.setWidth("90%");

            window.setContent(authMethodPanel);

            UI.getCurrent().addWindow(window);

            window.addCloseListener(new Window.CloseListener() {
                @Override
                public void windowClose(Window.CloseEvent e) {
                    populateAll();
                }
            });
        }
    });

    this.mainLayout.addComponent(newDirectoryButton);

    this.setWidth("100%");
    this.setHeight("100%");

    this.directoryTable = new Table();
    this.directoryTable.setWidth("100%");
    this.directoryTable.setHeight("600px");
    this.directoryTable.setCellStyleGenerator(new IkasanCellStyleGenerator());
    this.directoryTable.addContainerProperty("Directory Name", String.class, null);
    this.directoryTable.addContainerProperty("Type", String.class, null);
    this.directoryTable.addContainerProperty("Order", Layout.class, null);
    this.directoryTable.addContainerProperty("Operations", Layout.class, null);

    this.directoryTable.setColumnExpandRatio("Directory Name", 25);
    this.directoryTable.setColumnExpandRatio("Type", 25);

    this.directoryTable.setColumnAlignment("Order", Align.CENTER);
    this.directoryTable.setColumnExpandRatio("Order", 10);
    this.directoryTable.setColumnAlignment("Operations", Align.CENTER);
    this.directoryTable.setColumnWidth("Operations", 300);

    this.mainLayout.addComponent(this.directoryTable);

    this.mainLayout.setMargin(true);

    Panel wrapperPanel = new Panel();
    wrapperPanel.addStyleName(ValoTheme.PANEL_BORDERLESS);
    wrapperPanel.setSizeFull();
    wrapperPanel.setContent(this.mainLayout);

    HorizontalLayout wrapperLayout = new HorizontalLayout();
    wrapperLayout.setSizeFull();
    wrapperLayout.setMargin(true);
    wrapperLayout.addComponent(wrapperPanel);

    this.setContent(wrapperLayout);
}

From source file:org.ikasan.dashboard.ui.administration.panel.UserDirectoriesPanel.java

License:BSD License

protected void populateDirectoryTable(final AuthenticationMethod authenticationMethod) {
    Button test = new Button("Test");
    test.setStyleName(BaseTheme.BUTTON_LINK);
    test.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                authenticationProviderFactory.testAuthenticationConnection(authenticationMethod);
            } catch (RuntimeException e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);//from w ww .jav  a  2  s. c  o m

                Notification.show("Error occurred while testing connection!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Error occurred while testing connection!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            }

            Notification.show("Connection Successful!");
        }
    });

    final Button enableDisableButton = new Button();

    if (authenticationMethod.isEnabled()) {
        enableDisableButton.setCaption("Disable");
    } else {
        enableDisableButton.setCaption("Enable");
    }
    enableDisableButton.setStyleName(BaseTheme.BUTTON_LINK);
    enableDisableButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                if (authenticationMethod.isEnabled()) {
                    authenticationMethod.setEnabled(false);
                } else {
                    authenticationMethod.setEnabled(true);
                }

                securityService.saveOrUpdateAuthenticationMethod(authenticationMethod);

                populateAll();
            } catch (RuntimeException e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Error trying to enable/disable the authentication method!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            }

            if (authenticationMethod.isEnabled()) {
                enableDisableButton.setCaption("Disable");
                Notification.show("Enabled!");
            } else {
                enableDisableButton.setCaption("Enable");
                Notification.show("Disabled!");
            }
        }
    });

    Button delete = new Button("Delete");
    delete.setStyleName(BaseTheme.BUTTON_LINK);
    delete.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                securityService.deleteAuthenticationMethod(authenticationMethod);

                List<AuthenticationMethod> authenticationMethods = securityService.getAuthenticationMethods();

                directoryTable.removeAllItems();

                long order = 1;

                for (final AuthenticationMethod authenticationMethod : authenticationMethods) {
                    authenticationMethod.setOrder(order++);
                    securityService.saveOrUpdateAuthenticationMethod(authenticationMethod);
                }

                populateAll();
            } catch (RuntimeException e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Error trying to delete the authentication method!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            }

            Notification.show("Deleted!");
        }
    });

    Button edit = new Button("Edit");
    edit.setStyleName(BaseTheme.BUTTON_LINK);
    edit.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            UserDirectoryManagementPanel authMethodPanel = new UserDirectoryManagementPanel(
                    authenticationMethod, securityService, authenticationProviderFactory, ldapService);

            Window window = new Window("Configure User Directory");
            window.setModal(true);
            window.setHeight("90%");
            window.setWidth("90%");

            window.setContent(authMethodPanel);

            UI.getCurrent().addWindow(window);
        }
    });

    Button synchronise = new Button("Synchronise");
    synchronise.setStyleName(BaseTheme.BUTTON_LINK);

    synchronise.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                ldapService.synchronize(authenticationMethod);

                authenticationMethod.setLastSynchronised(new Date());
                securityService.saveOrUpdateAuthenticationMethod(authenticationMethod);

                populateAll();
            } catch (UnexpectedRollbackException e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                logger.error("Most specific cause: " + e.getMostSpecificCause());
                e.getMostSpecificCause().printStackTrace();
                logger.error("Most specific cause: " + e.getRootCause());
                e.getRootCause().printStackTrace();

                Notification.show("Error occurred while synchronizing!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            } catch (RuntimeException e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Error occurred while synchronizing!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Error occurred while synchronizing!", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);

                return;
            }

            Notification.show("Synchronized!");
        }
    });

    GridLayout operationsLayout = new GridLayout(9, 2);
    operationsLayout.setWidth("250px");
    operationsLayout.addComponent(enableDisableButton, 0, 0);
    operationsLayout.addComponent(new Label(" "), 1, 0);
    operationsLayout.addComponent(edit, 2, 0);
    operationsLayout.addComponent(new Label(" "), 3, 0);
    operationsLayout.addComponent(delete, 4, 0);
    operationsLayout.addComponent(new Label(" "), 5, 0);
    operationsLayout.addComponent(test, 6, 0);
    operationsLayout.addComponent(new Label(" "), 7, 0);
    operationsLayout.addComponent(synchronise, 8, 0);

    TextArea synchronisedTextArea = new TextArea();
    synchronisedTextArea.setRows(3);
    synchronisedTextArea.setWordwrap(true);

    if (authenticationMethod.getLastSynchronised() != null) {
        synchronisedTextArea.setValue(
                "This directory was last synchronised at " + authenticationMethod.getLastSynchronised());
    } else {
        synchronisedTextArea.setValue("This directory has not been synchronised");
    }

    synchronisedTextArea.setSizeFull();
    synchronisedTextArea.setReadOnly(true);

    operationsLayout.addComponent(synchronisedTextArea, 0, 1, 8, 1);

    HorizontalLayout orderLayout = new HorizontalLayout();
    orderLayout.setWidth("50%");

    if (authenticationMethod.getOrder() != 1) {
        Button upArrow = new Button(VaadinIcons.ARROW_UP);
        upArrow.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
        upArrow.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        upArrow.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                if (authenticationMethod.getOrder() != 1) {
                    AuthenticationMethod upAuthMethod = securityService
                            .getAuthenticationMethodByOrder(authenticationMethod.getOrder() - 1);

                    upAuthMethod.setOrder(authenticationMethod.getOrder());
                    authenticationMethod.setOrder(authenticationMethod.getOrder() - 1);

                    securityService.saveOrUpdateAuthenticationMethod(upAuthMethod);
                    securityService.saveOrUpdateAuthenticationMethod(authenticationMethod);

                    populateAll();
                }
            }
        });

        orderLayout.addComponent(upArrow);
    }

    long numberOfAuthMethods = securityService.getNumberOfAuthenticationMethods();

    if (authenticationMethod.getOrder() != numberOfAuthMethods) {
        Button downArrow = new Button(VaadinIcons.ARROW_DOWN);
        downArrow.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
        downArrow.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        downArrow.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                long numberOfAuthMethods = securityService.getNumberOfAuthenticationMethods();

                if (authenticationMethod.getOrder() != numberOfAuthMethods) {
                    AuthenticationMethod downAuthMethod = securityService
                            .getAuthenticationMethodByOrder(authenticationMethod.getOrder() + 1);

                    downAuthMethod.setOrder(authenticationMethod.getOrder());
                    authenticationMethod.setOrder(authenticationMethod.getOrder() + 1);

                    securityService.saveOrUpdateAuthenticationMethod(downAuthMethod);
                    securityService.saveOrUpdateAuthenticationMethod(authenticationMethod);

                    populateAll();
                }
            }
        });

        orderLayout.addComponent(downArrow);
    }

    this.directoryTable.addItem(new Object[] { authenticationMethod.getName(), "Microsoft Active Directory",
            orderLayout, operationsLayout }, authenticationMethod);
}

From source file:org.opencms.ui.components.CmsBasicDialog.java

License:Open Source License

/**
 * Initializes the dialog window.<p>
 *
 * @param width the dialog width/*from  www  .  j  av a  2s. c  om*/
 *
 * @return the window to be used by dialogs
 */
public static Window prepareWindow(DialogWidth width) {

    Window window = new Window();
    window.setModal(true);
    window.setClosable(true);
    int pageWidth = Page.getCurrent().getBrowserWindowWidth();
    if (((width == DialogWidth.wide) && (pageWidth < 810))
            || ((width == DialogWidth.narrow) && (pageWidth < 610))) {
        // in case the available page width does not allow the desired width, use max
        width = DialogWidth.max;
    }
    if (width == DialogWidth.max) {
        // in case max width would result in a width very close to wide or narrow, use their static width instead of relative width
        if ((pageWidth >= 610) && (pageWidth < 670)) {
            width = DialogWidth.narrow;
        } else if ((pageWidth >= 810) && (pageWidth < 890)) {
            width = DialogWidth.wide;
        }
    }
    switch (width) {
    case content:
        // do nothing
        break;
    case wide:
        window.setWidth("800px");
        break;
    case max:
        window.setWidth("90%");
        break;
    case narrow:
    default:
        window.setWidth("600px");
        break;
    }
    window.center();
    return window;
}

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

License:Open Source License

/**
 * Opens a modal window with the given component as content.<p>
 *
 * @param component the window content/*from www .j  a v  a2 s  .c o m*/
 *
 * @return the window which is opened
 */
public Window addAsWindow(Component component) {

    // Have to use an array because Vaadin declarative tries to bind the field otherwise
    if (m_currentWindow[0] != null) {
        m_currentWindow[0].close();
        m_currentWindow[0] = null;
    }

    Window window = new Window();
    window.setContent(component);
    window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_GIT_SCRIPT_RESULTS_0));
    window.setWidth("1000px");
    window.setModal(true);
    window.setResizable(false);
    A_CmsUI.get().addWindow(window);

    m_currentWindow[0] = window;
    return window;
}

From source file:org.opennms.features.topology.app.internal.operations.RemoveVertexFromGroupOperation.java

License:Open Source License

@Override
public void execute(final List<VertexRef> targets, final OperationContext operationContext) {
    if (targets == null || targets.isEmpty() || targets.size() != 1) {
        return;/*from www.  j a  v a 2s.c  o  m*/
    }

    final Logger log = LoggerFactory.getLogger(this.getClass());

    final GraphContainer graphContainer = operationContext.getGraphContainer();

    final VertexRef currentGroup = targets.get(0);
    final Collection<? extends Vertex> children = graphContainer.getBaseTopology().getChildren(currentGroup);
    for (Vertex child : children) {
        log.debug("Child ID: {}", child.getId());
    }

    final UI window = operationContext.getMainWindow();

    final Window groupNamePrompt = new Window("Remove item from this Group");
    groupNamePrompt.setModal(true);
    groupNamePrompt.setResizable(false);
    groupNamePrompt.setHeight("180px");
    groupNamePrompt.setWidth("300px");

    // Define the fields for the form
    final PropertysetItem item = new PropertysetItem();
    item.addItemProperty("Item", new ObjectProperty<String>(null, String.class));

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

        @Override
        public Field<?> createField(Item item, Object propertyId, Component uiContext) {
            // Identify the fields by their Property ID.
            String pid = (String) propertyId;
            if ("Item".equals(pid)) {
                ComboBox select = new ComboBox("Item");
                for (Vertex child : children) {
                    log.debug("Adding child: {}, {}", child.getId(), child.getLabel());
                    select.addItem(child.getId());
                    select.setItemCaption(child.getId(), child.getLabel());
                }
                select.setNewItemsAllowed(false);
                select.setNullSelectionAllowed(false);
                return select;
            }

            return null; // Invalid field (property) name.
        }
    };

    // TODO Add validator for name value

    final Form promptForm = new Form() {

        private static final long serialVersionUID = 2067414790743946906L;

        @Override
        public void commit() {
            super.commit();

            String childId = (String) getField("Item").getValue();
            log.debug("Field value: {}", childId);

            LoggerFactory.getLogger(this.getClass()).debug("Removing item from group: {}", childId);

            Vertex grandParent = graphContainer.getBaseTopology().getParent(currentGroup);

            GraphProvider topologyProvider = graphContainer.getBaseTopology();

            // Relink the child to the grandparent group (or null if it is null)
            topologyProvider.setParent(graphContainer.getBaseTopology()
                    .getVertex(graphContainer.getBaseTopology().getVertexNamespace(), childId), grandParent);

            // Save the topology
            topologyProvider.save();

            graphContainer.redoLayout();
        }
    };
    // Buffer changes to the datasource
    promptForm.setBuffered(true);
    // You must set the FormFieldFactory before you set the data source
    promptForm.setFormFieldFactory(fieldFactory);
    promptForm.setItemDataSource(item);

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

        private static final long serialVersionUID = 7388841001913090428L;

        @Override
        public void buttonClick(ClickEvent event) {
            promptForm.commit();
            // Close the prompt window
            window.removeWindow(groupNamePrompt);
        }
    });
    promptForm.getFooter().addComponent(ok);

    Button cancel = new Button("Cancel");
    cancel.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 8780989646038333243L;

        @Override
        public void buttonClick(ClickEvent event) {
            // Close the prompt window
            window.removeWindow(groupNamePrompt);
        }
    });
    promptForm.getFooter().addComponent(cancel);

    groupNamePrompt.setContent(promptForm);

    window.addWindow(groupNamePrompt);
}

From source file:org.opennms.features.topology.app.internal.operations.RenameGroupOperation.java

License:Open Source License

@Override
public void execute(final List<VertexRef> targets, final OperationContext operationContext) {
    if (targets == null || targets.isEmpty() || targets.size() != 1) {
        return;/* ww w . j  av  a 2 s  . c  o  m*/
    }

    final GraphContainer graphContainer = operationContext.getGraphContainer();

    final UI window = operationContext.getMainWindow();

    final Window groupNamePrompt = new Window("Rename Group");
    groupNamePrompt.setModal(true);
    groupNamePrompt.setResizable(false);
    groupNamePrompt.setHeight("220px");
    groupNamePrompt.setWidth("300px");

    // Define the fields for the form
    final PropertysetItem item = new PropertysetItem();
    item.addItemProperty("Group Label", new ObjectProperty<String>("", String.class));

    final Form promptForm = new Form() {

        private static final long serialVersionUID = 9202531175744361407L;

        @Override
        public void commit() {
            // Trim the form value
            Property<String> field = getField("Group Label");
            String groupLabel = field.getValue();
            if (groupLabel == null) {
                throw new InvalidValueException("Group label cannot be null.");
            }
            field.setValue(groupLabel.trim());
            super.commit();
            groupLabel = field.getValue();

            //Object parentKey = targets.get(0);
            //Object parentId = graphContainer.getVertexItemIdForVertexKey(parentKey);
            VertexRef parentId = targets.get(0);
            Vertex parentVertex = parentId == null ? null
                    : graphContainer.getBaseTopology().getVertex(parentId, graphContainer.getCriteria());
            Item parentItem = parentVertex == null ? null : parentVertex.getItem();

            if (parentItem != null) {

                Property<String> property = parentItem.getItemProperty("label");
                if (property != null && !property.isReadOnly()) {
                    property.setValue(groupLabel);

                    // Save the topology
                    graphContainer.getBaseTopology().save();

                    graphContainer.redoLayout();
                }
            }
        }
    };
    // Buffer changes to the datasource
    promptForm.setBuffered(true);
    // Bind the item to create all of the fields
    promptForm.setItemDataSource(item);
    // Add validators to the fields
    promptForm.getField("Group Label").setRequired(true);
    promptForm.getField("Group Label").setRequiredError("Group label cannot be blank.");
    promptForm.getField("Group Label").addValidator(
            new StringLengthValidator("Label must be at least one character long.", 1, -1, false));
    promptForm.getField("Group Label")
            .addValidator(new AbstractValidator<String>("A group with label \"{0}\" already exists.") {

                private static final long serialVersionUID = 79618011585921224L;

                @Override
                protected boolean isValidValue(String value) {
                    try {
                        final Collection<? extends Vertex> vertexIds = graphContainer.getBaseTopology()
                                .getVertices();
                        final Collection<String> groupLabels = new ArrayList<String>();
                        for (Vertex vertexId : vertexIds) {
                            if (vertexId.isGroup()) {
                                groupLabels.add(vertexId.getLabel());
                            }
                        }

                        for (String label : groupLabels) {
                            LoggerFactory.getLogger(this.getClass()).debug("Comparing {} to {}", value, label);
                            if (label.equals(value)) {
                                return false;
                            }
                        }
                        return true;
                    } catch (Throwable e) {
                        LoggerFactory.getLogger(this.getClass()).error(e.getMessage(), e);
                        return false;
                    }
                }

                @Override
                public Class<String> getType() {
                    return String.class;
                }
            });

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

        private static final long serialVersionUID = 7388841001913090428L;

        @Override
        public void buttonClick(ClickEvent event) {
            promptForm.commit();
            // Close the prompt window
            window.removeWindow(groupNamePrompt);
        }
    });
    promptForm.getFooter().addComponent(ok);

    Button cancel = new Button("Cancel");
    cancel.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 8780989646038333243L;

        @Override
        public void buttonClick(ClickEvent event) {
            // Close the prompt window
            window.removeWindow(groupNamePrompt);
        }
    });
    promptForm.getFooter().addComponent(cancel);

    groupNamePrompt.setContent(promptForm);

    window.addWindow(groupNamePrompt);
}

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  w  w w . j  av a 2s.  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.dashboard.config.ui.HelpClickListener.java

License:Open Source License

@Override
public void buttonClick(Button.ClickEvent clickEvent) {
    final Window window = new Window("Help");

    window.setModal(true);/*w  ww  .  ja va 2  s . com*/
    window.setClosable(false);
    window.setResizable(false);

    window.setWidth("55%");
    window.setHeight("80%");

    m_component.getUI().addWindow(window);

    window.setContent(new VerticalLayout() {
        {
            setMargin(true);
            setSpacing(true);
            setSizeFull();

            HorizontalLayout horizontalLayout = new HorizontalLayout();
            horizontalLayout.setSizeFull();
            horizontalLayout.setSpacing(true);

            Tree tree = new Tree();
            tree.setNullSelectionAllowed(false);
            tree.setMultiSelect(false);
            tree.setImmediate(true);

            tree.addItem("Overview");
            tree.setChildrenAllowed("Overview", false);

            tree.addItem("Installed Dashlets");
            tree.setChildrenAllowed("Installed Dashlets", true);

            final List<DashletFactory> factories = m_dashletSelector.getDashletFactoryList();

            for (DashletFactory dashletFactory : factories) {
                tree.addItem(dashletFactory.getName());
                tree.setParent(dashletFactory.getName(), "Installed Dashlets");
                tree.setChildrenAllowed(dashletFactory.getName(), false);
            }
            horizontalLayout.addComponent(tree);

            for (final Object id : tree.rootItemIds()) {
                tree.expandItemsRecursively(id);
            }

            final Panel panel = new Panel();
            panel.setSizeFull();

            horizontalLayout.addComponent(panel);
            horizontalLayout.setExpandRatio(panel, 1.0f);

            addComponent(horizontalLayout);
            setExpandRatio(horizontalLayout, 1.0f);

            tree.addValueChangeListener(new Property.ValueChangeListener() {
                @Override
                public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
                    String itemId = String.valueOf(valueChangeEvent.getProperty().getValue());

                    if ("Installed Dashlets".equals(itemId)) {
                        return;
                    }

                    if ("Overview".equals(itemId)) {
                        VerticalLayout verticalLayout = new VerticalLayout();
                        verticalLayout.setSpacing(true);
                        verticalLayout.setMargin(true);

                        verticalLayout.addComponent(new Label(getOverviewHelpHTML(), ContentMode.HTML));

                        panel.setContent(verticalLayout);
                    } else {
                        DashletFactory dashletFactory = m_dashletSelector.getDashletFactoryForName(itemId);

                        if (dashletFactory != null) {
                            if (dashletFactory.providesHelpComponent()) {
                                VerticalLayout verticalLayout = new VerticalLayout();
                                verticalLayout.setSpacing(true);
                                verticalLayout.setMargin(true);

                                Label helpTitle = new Label(
                                        "Help for Dashlet '" + dashletFactory.getName() + "'");
                                helpTitle.addStyleName("help-title");

                                verticalLayout.addComponent(helpTitle);
                                verticalLayout.addComponent(dashletFactory.getHelpComponent());

                                panel.setContent(verticalLayout);
                            }
                        }
                    }
                }
            });

            tree.select("Overview");

            addComponent(new HorizontalLayout() {
                {
                    setMargin(true);
                    setSpacing(true);
                    setWidth("100%");

                    Button closeButton = new Button("Close");

                    addComponent(closeButton);
                    setComponentAlignment(closeButton, Alignment.MIDDLE_RIGHT);
                    closeButton.addClickListener(new Button.ClickListener() {
                        @Override
                        public void buttonClick(Button.ClickEvent clickEvent) {
                            window.close();
                        }
                    });
                }
            });
        }
    });
}