Example usage for com.vaadin.ui DragAndDropWrapper setDragStartMode

List of usage examples for com.vaadin.ui DragAndDropWrapper setDragStartMode

Introduction

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

Prototype

public void setDragStartMode(DragStartMode dragStartMode) 

Source Link

Usage

From source file:com.hybridbpm.ui.component.bpm.designer.ProcessEditor.java

License:Apache License

private void prepareModeler() {

    processModelLayout.setProcessEditor(this);
    final DragAndDropWrapper pane = new DragAndDropWrapper(processModelLayout);
    pane.setDragStartMode(DragAndDropWrapper.DragStartMode.NONE);
    pane.setDropHandler(processModelLayout.dropHandler);
    processModelLayout.setProcessModel(processModel);
    processModelLayout.initUI();//from  ww w  . j  ava  2  s  .  com

    cssLayout.addComponent(pane);
    cssLayout.addStyleName("process-editor");
    cssLayout.setSizeFull();

    editorBackground.setSizeFull();
    editorBackground.setMargin(false);
    editorBackground.setSpacing(false);
    editorBackground.addComponent(cssLayout);

    mainPanel.setContent(editorBackground);
}

From source file:com.jorambarrez.PropertyPanel.java

License:Apache License

protected void initTrashIcon() {
    Embedded trashIcon = new Embedded(null, Images.MODELER_TRASH);
    trashIcon.setWidth(63, UNITS_PIXELS);
    trashIcon.setHeight(61, UNITS_PIXELS);
    trashIcon.setType(Embedded.TYPE_IMAGE);

    VerticalLayout trashLayout = new VerticalLayout();
    trashLayout.setWidth(120, UNITS_PIXELS);
    trashLayout.setHeight(120, UNITS_PIXELS);
    trashLayout.addComponent(trashIcon);
    trashLayout.setComponentAlignment(trashIcon, Alignment.MIDDLE_CENTER);

    DragAndDropWrapper dragAndDropWrapper = new DragAndDropWrapper(trashLayout);
    dragAndDropWrapper.setDragStartMode(DragStartMode.NONE);
    dragAndDropWrapper.setSizeUndefined();
    addComponent(dragAndDropWrapper);/*from   w  ww. java 2 s. co m*/
    setComponentAlignment(dragAndDropWrapper, Alignment.BOTTOM_CENTER);

    dragAndDropWrapper.setDropHandler(new DropHandler() {
        private static final long serialVersionUID = 1L;

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }

        public void drop(DragAndDropEvent event) {
            WrapperTransferable wrapperTransferable = (WrapperTransferable) event.getTransferable();
            Node srcNode = (Node) wrapperTransferable.getSourceComponent();

            // TODO: use eventrouter!
            ModelerApp.get().getFlowEditor().removeNode(srcNode);
        }
    });
}

From source file:com.mcparland.john.ComponentCollection.java

License:Apache License

/**
 * Create some tabs for each size//from w ww . j  av a2  s .c  o  m
 * 
 * @param sizes
 *            the sizes
 */
private void createTabs() {
    for (String size : sizes) {
        final Layout layout = createLayout();
        layout.setCaption("Icons size " + size + " x " + size);
        addComponent(layout);

        for (String icon : icons) {
            final Image image = createImage(size, icon);
            DragAndDropWrapper imageWrap = new DragAndDropWrapper(image);
            imageWrap.setDragStartMode(DragStartMode.COMPONENT);
            imageWrap.setSizeUndefined();
            layout.addComponent(imageWrap);
        }
    }
}

From source file:com.mcparland.john.DragAndDropPanel.java

License:Apache License

/**
 * Create a drag-and-droppable button./* w w w.jav  a  2 s  .c o m*/
 * 
 * @param name
 *            the name of the button.
 * @return a drag-and-droppable button.
 */
public Component createButton(String name) {
    Button button = new Button(name);
    DragAndDropWrapper buttonWrap = new DragAndDropWrapper(button);
    buttonWrap.setDragStartMode(DragStartMode.COMPONENT);
    buttonWrap.setSizeUndefined();
    return buttonWrap;
}

From source file:com.peergreen.example.webconsole.extensions.ConfirmDialogExtension.java

License:Open Source License

private DragAndDropWrapper getDraggableComponent(Component component) {
    DragAndDropWrapper dragAndDropWrapper = new DragAndDropWrapper(component);
    dragAndDropWrapper.setDragStartMode(DragAndDropWrapper.DragStartMode.COMPONENT);
    return dragAndDropWrapper;
}

From source file:org.apache.ace.webui.vaadin.VaadinClient.java

License:Apache License

private void initGrid() {
    User user = (User) getUser();/*from   w  w  w.  jav a2 s.  c om*/
    Authorization auth = m_userAdmin.getAuthorization(user);
    int count = 0;
    for (String role : new String[] { "viewArtifact", "viewFeature", "viewDistribution", "viewTarget" }) {
        if (auth.hasRole(role)) {
            count++;
        }
    }

    final GenericUploadHandler uploadHandler = new GenericUploadHandler(m_sessionDir) {
        @Override
        public void updateProgress(long readBytes, long contentLength) {
            Float percentage = new Float(readBytes / (float) contentLength);
            m_progress.setValue(percentage);
        }

        @Override
        protected void artifactsUploaded(List<UploadHandle> uploadedArtifacts) {
            StringBuilder failedMsg = new StringBuilder();
            StringBuilder successMsg = new StringBuilder();
            Set<String> selection = new HashSet<>();

            for (UploadHandle handle : uploadedArtifacts) {
                if (!handle.isSuccessful()) {
                    // Upload failed, so let's report this one...
                    appendFailure(failedMsg, handle);

                    m_log.log(LogService.LOG_ERROR, "Upload of " + handle.getFile() + " failed.",
                            handle.getFailureReason());
                } else {
                    try {
                        // Upload was successful, try to upload it to our OBR...
                        ArtifactObject artifact = uploadToOBR(handle);
                        if (artifact != null) {
                            selection.add(artifact.getDefinition());

                            appendSuccess(successMsg, handle);
                        }
                    } catch (ArtifactAlreadyExistsException exception) {
                        appendFailureExists(failedMsg, handle);

                        m_log.log(LogService.LOG_WARNING,
                                "Upload of " + handle.getFilename() + " failed, as it already exists!");
                    } catch (Exception exception) {
                        appendFailure(failedMsg, handle, exception);

                        m_log.log(LogService.LOG_ERROR, "Upload of " + handle.getFilename() + " failed.",
                                exception);
                    }
                }

                // We're done with this (temporary) file, so we can remove it...
                handle.cleanup();
            }

            m_artifactsPanel.setValue(selection);

            // Notify the user what the overall status was...
            Notification notification = createNotification(failedMsg, successMsg);
            getMainWindow().showNotification(notification);

            m_progress.setStyleName("invisible");
            m_statusLine.setStatus(notification.getCaption() + "...");
        }

        @Override
        protected void uploadStarted(UploadHandle upload) {
            m_progress.setStyleName("visible");
            m_progress.setValue(new Float(0.0f));

            m_statusLine.setStatus("Upload of '%s' started...", upload.getFilename());
        }

        private void appendFailure(StringBuilder sb, UploadHandle handle) {
            appendFailure(sb, handle, handle.getFailureReason());
        }

        private void appendFailure(StringBuilder sb, UploadHandle handle, Exception cause) {
            sb.append("<li>'").append(handle.getFile().getName()).append("': failed");
            if (cause != null) {
                sb.append(", possible reason:<br/>").append(cause.getMessage());
            }
            sb.append("</li>");
        }

        private void appendFailureExists(StringBuilder sb, UploadHandle handle) {
            sb.append("<li>'").append(handle.getFile().getName())
                    .append("': already exists in repository</li>");
        }

        private void appendSuccess(StringBuilder sb, UploadHandle handle) {
            sb.append("<li>'").append(handle.getFile().getName()).append("': added to repository</li>");
        }

        private Notification createNotification(StringBuilder failedMsg, StringBuilder successMsg) {
            String caption = "Upload completed";
            int delay = 500; // msec.
            StringBuilder notification = new StringBuilder();
            if (failedMsg.length() > 0) {
                caption = "Upload completed with failures";
                delay = -1;
                notification.append("<ul>").append(failedMsg).append("</ul>");
            }
            if (successMsg.length() > 0) {
                notification.append("<ul>").append(successMsg).append("</ul>");
            }
            if (delay < 0) {
                notification.append("<p>(click to dismiss this notification).</p>");
            }

            Notification summary = new Notification(caption, notification.toString(),
                    Notification.TYPE_TRAY_NOTIFICATION);
            summary.setDelayMsec(delay);
            return summary;
        }

        private ArtifactObject uploadToOBR(UploadHandle handle) throws IOException {
            return UploadHelper.importRemoteBundle(m_artifactRepository, handle.getFile());
        }
    };

    m_grid = new GridLayout(count, 4);
    m_grid.setSpacing(true);
    m_grid.setSizeFull();

    m_mainToolbar = createToolbar();
    m_grid.addComponent(m_mainToolbar, 0, 0, count - 1, 0);

    m_artifactsPanel = createArtifactsPanel();
    m_artifactToolbar = createArtifactToolbar();

    final DragAndDropWrapper artifactsPanelWrapper = new DragAndDropWrapper(m_artifactsPanel);
    artifactsPanelWrapper.setDragStartMode(DragStartMode.HTML5);
    artifactsPanelWrapper.setDropHandler(new ArtifactDropHandler(uploadHandler));
    artifactsPanelWrapper.setCaption(m_artifactsPanel.getCaption());
    artifactsPanelWrapper.setSizeFull();

    count = 0;
    if (auth.hasRole("viewArtifact")) {
        m_grid.addComponent(artifactsPanelWrapper, count, 2);
        m_grid.addComponent(m_artifactToolbar, count, 1);
        count++;
    }

    m_featuresPanel = createFeaturesPanel();
    m_featureToolbar = createFeatureToolbar();

    if (auth.hasRole("viewFeature")) {
        m_grid.addComponent(m_featuresPanel, count, 2);
        m_grid.addComponent(m_featureToolbar, count, 1);
        count++;
    }

    m_distributionsPanel = createDistributionsPanel();
    m_distributionToolbar = createDistributionToolbar();

    if (auth.hasRole("viewDistribution")) {
        m_grid.addComponent(m_distributionsPanel, count, 2);
        m_grid.addComponent(m_distributionToolbar, count, 1);
        count++;
    }

    m_targetsPanel = createTargetsPanel();
    m_targetToolbar = createTargetToolbar();

    if (auth.hasRole("viewTarget")) {
        m_grid.addComponent(m_targetsPanel, count, 2);
        m_grid.addComponent(m_targetToolbar, count, 1);
    }

    m_statusLine = new StatusLine();

    m_grid.addComponent(m_statusLine, 0, 3, 2, 3);

    m_progress = new ProgressIndicator(0f);
    m_progress.setStyleName("invisible");
    m_progress.setIndeterminate(false);
    m_progress.setPollingInterval(1000);

    m_grid.addComponent(m_progress, 3, 3);

    m_grid.setRowExpandRatio(2, 1.0f);

    m_grid.setColumnExpandRatio(0, 0.31f);
    m_grid.setColumnExpandRatio(1, 0.23f);
    m_grid.setColumnExpandRatio(2, 0.23f);
    m_grid.setColumnExpandRatio(3, 0.23f);

    // Wire up all panels so they have the correct associations...
    m_artifactsPanel.setAssociatedTables(null, m_featuresPanel);
    m_featuresPanel.setAssociatedTables(m_artifactsPanel, m_distributionsPanel);
    m_distributionsPanel.setAssociatedTables(m_featuresPanel, m_targetsPanel);
    m_targetsPanel.setAssociatedTables(m_distributionsPanel, null);

    addListener(m_statusLine, StatefulTargetObject.TOPIC_ALL,
            RepositoryObject.PUBLIC_TOPIC_ROOT.concat(RepositoryObject.TOPIC_ALL_SUFFIX));
    addListener(m_mainToolbar, StatefulTargetObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_artifactsPanel, ArtifactObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_featuresPanel, FeatureObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_distributionsPanel, DistributionObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_targetsPanel, StatefulTargetObject.TOPIC_ALL, TargetObject.TOPIC_ALL,
            RepositoryAdmin.TOPIC_STATUSCHANGED, RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);

    m_mainWindow.addComponent(m_grid);
    // Ensure the focus is properly defined (for the shortcut keys to work)...
    m_mainWindow.focus();
}

From source file:org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons.java

License:Open Source License

private DragAndDropWrapper createDragAndDropWrapper(final Button tagButton, final String name, final Long id) {
    final DragAndDropWrapper bsmBtnWrapper = new DragAndDropWrapper(tagButton);
    bsmBtnWrapper.addStyleName(ValoTheme.DRAG_AND_DROP_WRAPPER_NO_VERTICAL_DRAG_HINTS);
    bsmBtnWrapper.addStyleName(ValoTheme.DRAG_AND_DROP_WRAPPER_NO_HORIZONTAL_DRAG_HINTS);
    bsmBtnWrapper.addStyleName(SPUIStyleDefinitions.FILTER_BUTTON_WRAPPER);
    if (getButtonWrapperData() != null) {
        if (id == null) {
            bsmBtnWrapper.setData(getButtonWrapperData());
        } else {/*from w  w w  . j a  v a2s. c  om*/
            bsmBtnWrapper.setData(getButtonWrapperData().concat("" + id));
        }
    }
    bsmBtnWrapper.setId(getButttonWrapperIdPrefix().concat(name));
    bsmBtnWrapper.setDragStartMode(DragStartMode.WRAPPER);
    bsmBtnWrapper.setDropHandler(getFilterButtonDropHandler());
    return bsmBtnWrapper;
}

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

License:BSD License

/**
 * Helper method to initialise behaviour of the policy name field.
 * /* w  ww  . j  a va  2s  .c  o  m*/
 * @return
 */
protected DragAndDropWrapper initPolicyNameField() {
    // The policy field name is an autocomplete field.
    this.policyNameField = new AutocompleteField<Policy>();
    this.policyNameField.setWidth("70%");

    // We also want it to be drag and drop friendly.
    final DragAndDropWrapper policyNameFieldWrap = new DragAndDropWrapper(policyNameField);
    policyNameFieldWrap.setDragStartMode(DragStartMode.COMPONENT);

    // In order to have the auto complete work we must add a query listener.
    // The query listener gets activated when a user begins to type into 
    // the field and hits the database looking for suggestions.
    policyNameField.setQueryListener(new AutocompleteQueryListener<Policy>() {
        @Override
        public void handleUserQuery(AutocompleteField<Policy> field, String query) {
            // Iterate over the returned results and add them as suggestions
            for (Policy policy : securityService.getPolicyByNameLike(query)) {
                field.addSuggestion(policy, policy.getName());
            }
        }
    });

    // Once a suggestion is selected the listener below gets fired and we populate
    // associated fields as required.
    policyNameField.setSuggestionPickedListener(new AutocompleteSuggestionPickedListener<Policy>() {
        @Override
        public void onSuggestionPicked(final Policy pickedPolicy) {
            PolicyManagementPanel.this.policy = pickedPolicy;

            // Populate all the policy related fields.
            PolicyManagementPanel.this.policyItem = new BeanItem<Policy>(PolicyManagementPanel.this.policy);
            PolicyManagementPanel.this.policyNameField
                    .setPropertyDataSource(policyItem.getItemProperty("name"));
            PolicyManagementPanel.this.descriptionField
                    .setPropertyDataSource(policyItem.getItemProperty("description"));

            if (PolicyManagementPanel.this.policy.getPolicyLink() != null) {
                PolicyManagementPanel.this.linkedEntity.setVisible(true);
                PolicyManagementPanel.this.linkType.setVisible(true);
                PolicyManagementPanel.this.linkTypeLabel.setVisible(true);
                PolicyManagementPanel.this.linkedEntityLabel.setVisible(true);
                PolicyManagementPanel.this.linkType.setValue(
                        PolicyManagementPanel.this.policy.getPolicyLink().getPolicyLinkType().getName());
                PolicyManagementPanel.this.linkedEntity
                        .setValue(PolicyManagementPanel.this.policy.getPolicyLink().getName());
            } else {
                PolicyManagementPanel.this.linkType.setValue(null);
                PolicyManagementPanel.this.linkedEntity.setValue(new String());

                PolicyManagementPanel.this.linkedEntity.setVisible(false);
                PolicyManagementPanel.this.linkedEntityLabel.setVisible(false);
                PolicyManagementPanel.this.linkType.setVisible(false);
                PolicyManagementPanel.this.linkTypeLabel.setVisible(false);
            }

            roleTable.removeAllItems();

            // Add all the associated roles to the role table.
            for (final Role role : policy.getRoles()) {
                Button deleteButton = new Button();
                deleteButton.setIcon(VaadinIcons.TRASH);
                deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);
                deleteButton.setDescription("Remove Policy from this Role");

                // Add the delete functionality to each role that is added
                deleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        // Update the roles associated with policy
                        // and update in the DB.
                        policy.getRoles().remove(role);
                        PolicyManagementPanel.this.savePolicy(policy);

                        // Once we are happy that the DB call was fine
                        // update the UI components to reflect the change.
                        roleTable.removeItem(role);
                        policyDropTable.removeItem(policy.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), deleteButton }, role);
            }

            PolicyManagementPanel.this.cancelButton.setVisible(false);
            PolicyManagementPanel.this.newButton.setVisible(true);
            PolicyManagementPanel.this.deleteButton.setVisible(true);
        }
    });

    return policyNameFieldWrap;
}

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

License:BSD License

@SuppressWarnings("deprecation")
protected void init() {
    this.setWidth("100%");
    this.setHeight("100%");

    VerticalLayout layout = new VerticalLayout();
    layout.setSpacing(true);//from   www.j a  va  2s  .  c om
    layout.setSizeFull();

    Panel securityAdministrationPanel = new Panel();
    securityAdministrationPanel.addStyleName(ValoTheme.PANEL_BORDERLESS);
    securityAdministrationPanel.setHeight("100%");
    securityAdministrationPanel.setWidth("100%");

    GridLayout gridLayout = new GridLayout(2, 5);
    gridLayout.setWidth("100%");
    gridLayout.setHeight("100%");
    gridLayout.setMargin(true);
    gridLayout.setSizeFull();

    Label groupManagementLabel = new Label("Group Management");
    groupManagementLabel.setStyleName(ValoTheme.LABEL_HUGE);
    gridLayout.addComponent(groupManagementLabel, 0, 0, 1, 0);

    Label groupSearchHintLabel = new Label();
    groupSearchHintLabel.setCaptionAsHtml(true);
    groupSearchHintLabel.setCaption(
            VaadinIcons.QUESTION_CIRCLE_O.getHtml() + " Type into the Group Name field to find a group.");
    groupSearchHintLabel.addStyleName(ValoTheme.LABEL_TINY);
    groupSearchHintLabel.addStyleName(ValoTheme.LABEL_LIGHT);
    gridLayout.addComponent(groupSearchHintLabel, 0, 1, 1, 1);

    Label principalNameLabel = new Label("Group Name:");
    principalNameLabel.setSizeUndefined();

    principalNameField = new AutocompleteField<IkasanPrincipal>();
    principalNameField.setWidth("70%");

    final DragAndDropWrapper principalNameFieldWrap = new DragAndDropWrapper(principalNameField);
    principalNameFieldWrap.setDragStartMode(DragStartMode.COMPONENT);

    principalTypeField.setWidth("70%");
    descriptionField.setWidth("70%");
    descriptionField.setHeight("60px");

    roleTable.addContainerProperty("Role", String.class, null);
    roleTable.addContainerProperty("", Button.class, null);
    roleTable.setHeight("610px");
    roleTable.setWidth("300px");

    userTable.addContainerProperty("Associated Users", String.class, null);
    userTable.setHeight("610px");
    userTable.setWidth("300px");

    principalDropTable.addContainerProperty("Members", String.class, null);
    principalDropTable.addContainerProperty("", Button.class, null);
    principalDropTable.setHeight("700px");
    principalDropTable.setWidth("300px");

    principalNameField.setQueryListener(new AutocompleteQueryListener<IkasanPrincipal>() {
        @Override
        public void handleUserQuery(AutocompleteField<IkasanPrincipal> field, String query) {
            for (IkasanPrincipal principal : securityService.getPrincipalByNameLike(query)) {
                field.addSuggestion(principal, principal.getName());
            }
        }
    });

    principalNameField.setSuggestionPickedListener(new AutocompleteSuggestionPickedListener<IkasanPrincipal>() {
        @Override
        public void onSuggestionPicked(final IkasanPrincipal principal) {
            PrincipalManagementPanel.this.principal = principal;
            PrincipalManagementPanel.this.setValues();
        }
    });

    GridLayout formLayout = new GridLayout(2, 3);
    formLayout.setWidth("100%");
    formLayout.setHeight("135px");
    formLayout.setSpacing(true);

    formLayout.setColumnExpandRatio(0, .1f);
    formLayout.setColumnExpandRatio(1, .8f);

    formLayout.addComponent(principalNameLabel, 0, 0);
    formLayout.setComponentAlignment(principalNameLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(principalNameFieldWrap, 1, 0);

    Label principalTypeLabel = new Label("Group Type:");
    principalTypeLabel.setSizeUndefined();
    formLayout.addComponent(principalTypeLabel, 0, 1);
    formLayout.setComponentAlignment(principalTypeLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(principalTypeField, 1, 1);

    Label descriptionLabel = new Label("Description:");
    descriptionLabel.setSizeUndefined();
    formLayout.addComponent(descriptionLabel, 0, 2);
    formLayout.setComponentAlignment(descriptionLabel, Alignment.TOP_RIGHT);
    formLayout.addComponent(descriptionField, 1, 2);

    gridLayout.addComponent(formLayout, 0, 2, 1, 2);

    principalDropTable.setDragMode(TableDragMode.ROW);
    principalDropTable.setDropHandler(new DropHandler() {
        @Override
        public void drop(final DragAndDropEvent dropEvent) {
            // criteria verify that this is safe
            logger.info("Trying to drop: " + dropEvent);

            if (rolesCombo.getValue() == null) {
                // Do nothing if there is no role selected
                logger.info("Ignoring drop: " + dropEvent);
                return;
            }

            final WrapperTransferable t = (WrapperTransferable) dropEvent.getTransferable();

            final AutocompleteField sourceContainer = (AutocompleteField) t.getDraggedComponent();
            logger.info("sourceContainer.getText(): " + sourceContainer.getText());

            Button deleteButton = new Button();

            deleteButton.setIcon(VaadinIcons.TRASH);
            deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
            deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

            final IkasanPrincipal principal = securityService.findPrincipalByName(sourceContainer.getText());
            final Role roleToRemove = (Role) rolesCombo.getValue();

            deleteButton.addClickListener(new Button.ClickListener() {
                public void buttonClick(ClickEvent event) {
                    principalDropTable.removeItem(principal.getName());

                    principal.getRoles().remove(roleToRemove);

                    securityService.savePrincipal(principal);

                    if (principalNameField.getText().equals(principal.getName())) {
                        roleTable.removeItem(roleToRemove);
                    }
                }
            });

            principalDropTable.addItem(new Object[] { sourceContainer.getText(), deleteButton },
                    sourceContainer.getText());

            principal.getRoles().add((Role) rolesCombo.getValue());

            securityService.savePrincipal(principal);

            roleTable.removeAllItems();

            for (final Role role : principal.getRoles()) {
                Button roleDeleteButton = new Button();
                roleDeleteButton.setIcon(VaadinIcons.TRASH);
                roleDeleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                roleDeleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                roleDeleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        roleTable.removeItem(role);

                        principal.getRoles().remove(role);

                        securityService.savePrincipal(principal);

                        principalDropTable.removeItem(principal.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), roleDeleteButton }, role);
            }
        }

        @Override
        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    });

    Label roleTableHintLabel = new Label();
    roleTableHintLabel.setCaptionAsHtml(true);
    roleTableHintLabel.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " The Roles table below displays the roles that are assigned to the group. Roles can be deleted from this table.");
    roleTableHintLabel.addStyleName(ValoTheme.LABEL_TINY);
    roleTableHintLabel.addStyleName(ValoTheme.LABEL_LIGHT);
    gridLayout.addComponent(roleTableHintLabel, 0, 3, 1, 3);

    gridLayout.addComponent(roleTable, 0, 4);
    gridLayout.addComponent(userTable, 1, 4);

    this.rolesCombo = new ComboBox("Roles");
    this.rolesCombo.setWidth("90%");
    this.rolesCombo.addListener(new Property.ValueChangeListener() {
        public void valueChange(ValueChangeEvent event) {
            final Role role = (Role) event.getProperty().getValue();

            if (role != null) {
                logger.info("Value changed got Role: " + role);

                List<IkasanPrincipal> principals = securityService.getAllPrincipalsWithRole(role.getName());

                principalDropTable.removeAllItems();

                for (final IkasanPrincipal principal : principals) {
                    Button deleteButton = new Button();

                    deleteButton.setIcon(VaadinIcons.TRASH);
                    deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                    deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                    deleteButton.addClickListener(new Button.ClickListener() {
                        public void buttonClick(ClickEvent event) {
                            principalDropTable.removeItem(principal.getName());

                            principal.getRoles().remove(role);

                            securityService.savePrincipal(principal);

                            if (principalNameField.getText().equals(principal.getName())) {
                                roleTable.removeItem(role);
                            }
                        }
                    });

                    principalDropTable.addItem(new Object[] { principal.getName(), deleteButton },
                            principal.getName());
                }
            }
        }
    });

    Panel roleMemberPanel = new Panel();

    roleMemberPanel.addStyleName(ValoTheme.PANEL_BORDERLESS);
    roleMemberPanel.setHeight("100%");
    roleMemberPanel.setWidth("100%");

    GridLayout roleMemberLayout = new GridLayout();
    roleMemberLayout.setSpacing(true);
    roleMemberLayout.setWidth("100%");
    roleMemberLayout.setHeight("100%");

    Label roleGroupLabels = new Label("Role/Group Associations");
    roleGroupLabels.setStyleName(ValoTheme.LABEL_HUGE);
    gridLayout.addComponent(roleGroupLabels);

    Label groupDragHintLabel = new Label();
    groupDragHintLabel.setCaptionAsHtml(true);
    groupDragHintLabel.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " Drop groups into the table below to assign them the role.");

    roleMemberLayout.addComponent(roleGroupLabels);
    roleMemberLayout.addComponent(groupDragHintLabel);
    roleMemberLayout.addComponent(this.rolesCombo);
    roleMemberLayout.addComponent(this.principalDropTable);

    roleMemberPanel.setContent(roleMemberLayout);

    securityAdministrationPanel.setContent(gridLayout);
    layout.addComponent(securityAdministrationPanel);

    VerticalLayout roleMemberPanelLayout = new VerticalLayout();
    roleMemberPanelLayout.setWidth("100%");
    roleMemberPanelLayout.setHeight("100%");
    roleMemberPanelLayout.setMargin(true);
    roleMemberPanelLayout.addComponent(roleMemberPanel);
    roleMemberPanelLayout.setSizeFull();

    HorizontalSplitPanel hsplit = new HorizontalSplitPanel();
    hsplit.setFirstComponent(layout);
    hsplit.setSecondComponent(roleMemberPanelLayout);

    // Set the position of the splitter as percentage
    hsplit.setSplitPosition(65, Unit.PERCENTAGE);
    hsplit.setLocked(true);

    this.setContent(hsplit);
}

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

License:BSD License

@SuppressWarnings("deprecation")
protected void init() {
    this.setWidth("100%");
    this.setHeight("100%");

    VerticalLayout layout = new VerticalLayout();
    layout.setSizeFull();//ww  w.j  a  v  a  2s  .c om

    Panel securityAdministrationPanel = new Panel();
    securityAdministrationPanel.addStyleName(ValoTheme.PANEL_BORDERLESS);
    securityAdministrationPanel.setHeight("100%");
    securityAdministrationPanel.setWidth("100%");

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

    Label mappingConfigurationLabel = new Label("User Management");
    mappingConfigurationLabel.setStyleName(ValoTheme.LABEL_HUGE);
    gridLayout.addComponent(mappingConfigurationLabel, 0, 0, 1, 0);

    Label userSearchHintLabel = new Label();
    userSearchHintLabel.setCaptionAsHtml(true);
    userSearchHintLabel.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " Type into the Username, Firstname or Surname fields to find a user.");
    userSearchHintLabel.addStyleName(ValoTheme.LABEL_TINY);
    userSearchHintLabel.addStyleName(ValoTheme.LABEL_LIGHT);
    gridLayout.addComponent(userSearchHintLabel, 0, 1, 1, 1);

    Label usernameLabel = new Label("Username:");

    usernameField.setWidth("40%");

    final DragAndDropWrapper usernameFieldWrap = new DragAndDropWrapper(usernameField);
    usernameFieldWrap.setDragStartMode(DragStartMode.COMPONENT);

    firstName = new AutocompleteField<User>();
    firstName.setWidth("40%");
    surname = new AutocompleteField<User>();
    surname.setWidth("40%");
    final TextField department = new TextField();
    department.setWidth("40%");
    final TextField email = new TextField();
    email.setWidth("40%");

    final Table roleTable = new Table();
    roleTable.addContainerProperty("Role", String.class, null);
    roleTable.addContainerProperty("", Button.class, null);
    roleTable.setHeight("520px");
    roleTable.setWidth("250px");

    usernameField.setQueryListener(new AutocompleteQueryListener<User>() {
        @Override
        public void handleUserQuery(AutocompleteField<User> field, String query) {
            for (User user : userService.getUserByUsernameLike(query)) {
                field.addSuggestion(user, user.getUsername());
            }
        }
    });

    usernameField.setSuggestionPickedListener(new AutocompleteSuggestionPickedListener<User>() {
        @Override
        public void onSuggestionPicked(User user) {
            UserManagementPanel.this.user = user;
            firstName.setText(user.getFirstName());
            surname.setText(user.getSurname());
            department.setValue(user.getDepartment());
            email.setValue(user.getEmail());

            final IkasanPrincipal principal = securityService.findPrincipalByName(user.getUsername());

            roleTable.removeAllItems();

            for (final Role role : principal.getRoles()) {
                Button deleteButton = new Button();
                deleteButton.setIcon(VaadinIcons.TRASH);
                deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                deleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        roleTable.removeItem(role);

                        principal.getRoles().remove(role);

                        securityService.savePrincipal(principal);

                        userDropTable.removeItem(principal.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), deleteButton }, role);
            }

            associatedPrincipalsTable.removeAllItems();

            for (IkasanPrincipal ikasanPrincipal : user.getPrincipals()) {
                if (!ikasanPrincipal.getType().equals("user")) {
                    associatedPrincipalsTable.addItem(new Object[] { ikasanPrincipal.getName() },
                            ikasanPrincipal);
                }
            }
        }
    });

    firstName.setQueryListener(new AutocompleteQueryListener<User>() {
        @Override
        public void handleUserQuery(AutocompleteField<User> field, String query) {
            for (User user : userService.getUserByFirstnameLike(query)) {
                field.addSuggestion(user, user.getFirstName() + " " + user.getSurname());
            }
        }
    });

    firstName.setSuggestionPickedListener(new AutocompleteSuggestionPickedListener<User>() {
        @Override
        public void onSuggestionPicked(User user) {
            UserManagementPanel.this.user = user;
            usernameField.setText(user.getUsername());
            firstName.setText(user.getFirstName());
            surname.setText(user.getSurname());
            department.setValue(user.getDepartment());
            email.setValue(user.getEmail());

            final IkasanPrincipal principal = securityService.findPrincipalByName(user.getUsername());

            roleTable.removeAllItems();

            for (final Role role : principal.getRoles()) {
                Button deleteButton = new Button();
                deleteButton.setIcon(VaadinIcons.TRASH);
                deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                deleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        roleTable.removeItem(role);

                        principal.getRoles().remove(role);

                        securityService.savePrincipal(principal);

                        userDropTable.removeItem(principal.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), deleteButton }, role);
            }

            associatedPrincipalsTable.removeAllItems();

            for (IkasanPrincipal ikasanPrincipal : user.getPrincipals()) {
                if (!ikasanPrincipal.getType().equals("user")) {
                    associatedPrincipalsTable.addItem(new Object[] { ikasanPrincipal.getName() },
                            ikasanPrincipal);
                }
            }
        }
    });

    surname.setQueryListener(new AutocompleteQueryListener<User>() {
        @Override
        public void handleUserQuery(AutocompleteField<User> field, String query) {
            for (User user : userService.getUserBySurnameLike(query)) {
                field.addSuggestion(user, user.getFirstName() + " " + user.getSurname());
            }
        }
    });

    surname.setSuggestionPickedListener(new AutocompleteSuggestionPickedListener<User>() {
        @Override
        public void onSuggestionPicked(User user) {
            UserManagementPanel.this.user = user;
            usernameField.setText(user.getUsername());
            firstName.setText(user.getFirstName());
            surname.setText(user.getSurname());
            department.setValue(user.getDepartment());
            email.setValue(user.getEmail());

            final IkasanPrincipal principal = securityService.findPrincipalByName(user.getUsername());

            roleTable.removeAllItems();

            for (final Role role : principal.getRoles()) {
                Button deleteButton = new Button();
                deleteButton.setIcon(VaadinIcons.TRASH);
                deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                deleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        roleTable.removeItem(role);

                        principal.getRoles().remove(role);

                        securityService.savePrincipal(principal);

                        userDropTable.removeItem(principal.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), deleteButton }, role);

                associatedPrincipalsTable.removeAllItems();

                for (IkasanPrincipal ikasanPrincipal : user.getPrincipals()) {
                    if (!ikasanPrincipal.getType().equals("user")) {
                        associatedPrincipalsTable.addItem(new Object[] { ikasanPrincipal.getName() },
                                ikasanPrincipal);
                    }
                }
            }
        }
    });

    GridLayout formLayout = new GridLayout(2, 5);
    formLayout.setSpacing(true);
    formLayout.setWidth("100%");

    formLayout.setColumnExpandRatio(0, .1f);
    formLayout.setColumnExpandRatio(1, .8f);

    usernameLabel.setSizeUndefined();
    formLayout.addComponent(usernameLabel, 0, 0);
    formLayout.setComponentAlignment(usernameLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(usernameFieldWrap, 1, 0);

    Label firstNameLabel = new Label("First name:");
    firstNameLabel.setSizeUndefined();
    formLayout.addComponent(firstNameLabel, 0, 1);
    formLayout.setComponentAlignment(firstNameLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(firstName, 1, 1);

    Label surnameLabel = new Label("Surname:");
    surnameLabel.setSizeUndefined();
    formLayout.addComponent(surnameLabel, 0, 2);
    formLayout.setComponentAlignment(surnameLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(surname, 1, 2);

    Label departmentLabel = new Label("Department:");
    departmentLabel.setSizeUndefined();
    formLayout.addComponent(departmentLabel, 0, 3);
    formLayout.setComponentAlignment(departmentLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(department, 1, 3);

    Label emailLabel = new Label("Email address:");
    emailLabel.setSizeUndefined();
    formLayout.addComponent(emailLabel, 0, 4);
    formLayout.setComponentAlignment(emailLabel, Alignment.MIDDLE_RIGHT);
    formLayout.addComponent(email, 1, 4);

    gridLayout.addComponent(formLayout, 0, 2, 1, 2);

    Label rolesAndGroupsHintLabel1 = new Label();
    rolesAndGroupsHintLabel1.setCaptionAsHtml(true);
    rolesAndGroupsHintLabel1.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " The Roles table below displays the roles that the user has. Roles can be deleted from this table.");
    rolesAndGroupsHintLabel1.addStyleName(ValoTheme.LABEL_TINY);
    rolesAndGroupsHintLabel1.addStyleName(ValoTheme.LABEL_LIGHT);
    rolesAndGroupsHintLabel1.setWidth(300, Unit.PIXELS);
    gridLayout.addComponent(rolesAndGroupsHintLabel1, 0, 3, 1, 3);

    Label rolesAndGroupsHintLabel2 = new Label();
    rolesAndGroupsHintLabel2.setCaptionAsHtml(true);
    rolesAndGroupsHintLabel2.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " The Groups table below displays all the LDAP groups that the user is a member of. You cannot manage these "
            + "from this application.");
    rolesAndGroupsHintLabel2.addStyleName(ValoTheme.LABEL_TINY);
    rolesAndGroupsHintLabel2.addStyleName(ValoTheme.LABEL_LIGHT);
    rolesAndGroupsHintLabel2.setWidth(300, Unit.PIXELS);
    gridLayout.addComponent(rolesAndGroupsHintLabel2, 0, 4, 1, 4);

    final ClientSideCriterion acceptCriterion = new SourceIs(usernameField);

    userDropTable.addContainerProperty("Members", String.class, null);
    userDropTable.addContainerProperty("", Button.class, null);
    userDropTable.setHeight("715px");
    userDropTable.setWidth("300px");

    userDropTable.setDragMode(TableDragMode.ROW);
    userDropTable.setDropHandler(new DropHandler() {
        @Override
        public void drop(final DragAndDropEvent dropEvent) {
            if (rolesCombo.getValue() == null) {
                // Do nothing if there is no role selected
                logger.info("Ignoring drop: " + dropEvent);
                return;
            }

            // criteria verify that this is safe
            logger.info("Trying to drop: " + dropEvent);

            final WrapperTransferable t = (WrapperTransferable) dropEvent.getTransferable();

            final AutocompleteField sourceContainer = (AutocompleteField) t.getDraggedComponent();
            logger.info("sourceContainer.getText(): " + sourceContainer.getText());

            Button deleteButton = new Button();

            deleteButton.setIcon(VaadinIcons.TRASH);
            deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
            deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

            final IkasanPrincipal principal = securityService.findPrincipalByName(sourceContainer.getText());
            final Role roleToRemove = (Role) rolesCombo.getValue();

            deleteButton.addClickListener(new Button.ClickListener() {
                public void buttonClick(ClickEvent event) {
                    userDropTable.removeItem(principal.getName());

                    principal.getRoles().remove(roleToRemove);

                    securityService.savePrincipal(principal);

                    if (UserManagementPanel.this.usernameField.getText().equals(principal.getName())) {
                        roleTable.removeItem(roleToRemove);
                    }
                }
            });

            userDropTable.addItem(new Object[] { sourceContainer.getText(), deleteButton },
                    sourceContainer.getText());

            principal.getRoles().add((Role) rolesCombo.getValue());

            securityService.savePrincipal(principal);

            roleTable.removeAllItems();

            for (final Role role : principal.getRoles()) {
                Button roleDeleteButton = new Button();
                roleDeleteButton.setIcon(VaadinIcons.TRASH);
                roleDeleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                roleDeleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                roleDeleteButton.addClickListener(new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        roleTable.removeItem(role);

                        principal.getRoles().remove(role);

                        securityService.savePrincipal(principal);

                        userDropTable.removeItem(principal.getName());
                    }
                });

                roleTable.addItem(new Object[] { role.getName(), roleDeleteButton }, role);
            }
        }

        @Override
        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    });

    gridLayout.addComponent(roleTable, 0, 5);

    this.associatedPrincipalsTable.addContainerProperty("Groups", String.class, null);
    this.associatedPrincipalsTable.addItemClickListener(this.associatedPrincipalItemClickListener);
    associatedPrincipalsTable.setHeight("520px");
    associatedPrincipalsTable.setWidth("400px");

    gridLayout.addComponent(this.associatedPrincipalsTable, 1, 5);

    this.rolesCombo = new ComboBox("Roles");
    this.rolesCombo.setWidth("90%");
    this.rolesCombo.addValueChangeListener(new Property.ValueChangeListener() {
        public void valueChange(ValueChangeEvent event) {
            final Role role = (Role) event.getProperty().getValue();

            if (role != null) {
                logger.info("Value changed got Role: " + role);

                List<IkasanPrincipal> principals = securityService.getAllPrincipalsWithRole(role.getName());

                userDropTable.removeAllItems();

                for (final IkasanPrincipal principal : principals) {
                    Button deleteButton = new Button();
                    deleteButton.setIcon(VaadinIcons.TRASH);
                    deleteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
                    deleteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);

                    deleteButton.addClickListener(new Button.ClickListener() {
                        public void buttonClick(ClickEvent event) {
                            userDropTable.removeItem(principal.getName());

                            principal.getRoles().remove(role);

                            securityService.savePrincipal(principal);

                            if (UserManagementPanel.this.usernameField.getText().equals(principal.getName())) {
                                roleTable.removeItem(role);
                            }
                        }
                    });

                    userDropTable.addItem(new Object[] { principal.getName(), deleteButton },
                            principal.getName());
                }
            }
        }
    });

    Panel roleMemberPanel = new Panel();

    roleMemberPanel.addStyleName(ValoTheme.PANEL_BORDERLESS);
    roleMemberPanel.setHeight("100%");
    roleMemberPanel.setWidth("100%");

    GridLayout roleMemberLayout = new GridLayout();
    roleMemberLayout.setSpacing(true);
    roleMemberLayout.setWidth("100%");

    Label roleMemberAssociationsLabel = new Label("Role/Member Associations");
    roleMemberAssociationsLabel.setStyleName(ValoTheme.LABEL_HUGE);

    Label userDragHintLabel = new Label();
    userDragHintLabel.setCaptionAsHtml(true);
    userDragHintLabel.setCaption(VaadinIcons.QUESTION_CIRCLE_O.getHtml()
            + " Drop users into the table below to assign them the role.");

    roleMemberLayout.addComponent(roleMemberAssociationsLabel);
    roleMemberLayout.addComponent(userDragHintLabel);
    roleMemberLayout.addComponent(this.rolesCombo);
    roleMemberLayout.addComponent(this.userDropTable);

    roleMemberPanel.setContent(roleMemberLayout);

    securityAdministrationPanel.setContent(gridLayout);
    layout.addComponent(securityAdministrationPanel);

    VerticalLayout roleMemberPanelLayout = new VerticalLayout();
    roleMemberPanelLayout.setWidth("100%");
    roleMemberPanelLayout.setHeight("100%");
    roleMemberPanelLayout.setMargin(true);
    roleMemberPanelLayout.addComponent(roleMemberPanel);
    roleMemberPanelLayout.setSizeFull();

    HorizontalSplitPanel hsplit = new HorizontalSplitPanel();
    hsplit.setFirstComponent(layout);
    hsplit.setSecondComponent(roleMemberPanelLayout);

    // Set the position of the splitter as percentage
    hsplit.setSplitPosition(65, Unit.PERCENTAGE);
    hsplit.setLocked(true);

    this.setContent(hsplit);
}