Example usage for com.vaadin.ui TextArea getValue

List of usage examples for com.vaadin.ui TextArea getValue

Introduction

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

Prototype

@Override
    public String getValue() 

Source Link

Usage

From source file:org.escidoc.browser.ui.listeners.OnContextAdminDescriptor.java

License:Open Source License

/**
 * Editing since it has a parameter// ww  w.jav a2s .  c o m
 * 
 * @param adminDescriptor
 */
public void adminDescriptorForm(AdminDescriptor adminDescriptor) {

    // Editing
    final Window subwindow = new Window("A modal subwindow");
    subwindow.setModal(true);
    subwindow.setWidth("650px");

    VerticalLayout layout = (VerticalLayout) subwindow.getContent();
    layout.setMargin(true);
    layout.setSpacing(true);

    final TextField txtName = new TextField("Name");
    txtName.setValue(adminDescriptor.getName());
    txtName.setImmediate(true);
    txtName.setValidationVisible(true);
    final TextArea txtContent = new TextArea("Content");
    txtContent.setColumns(30);
    txtContent.setRows(40);
    try {
        txtContent.setValue(adminDescriptor.getContentAsString());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    txtContent.setColumns(30);

    Button addAdmDescButton = new Button("Add Description");
    addAdmDescButton.addListener(new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {

            if (txtName.getValue().toString() == null) {
                router.getMainWindow().showNotification(ViewConstants.PLEASE_ENTER_A_NAME,
                        Notification.TYPE_ERROR_MESSAGE);

            } else if (!XmlUtil.isWellFormed(txtContent.getValue().toString())) {
                router.getMainWindow().showNotification(ViewConstants.XML_IS_NOT_WELL_FORMED,
                        Notification.TYPE_ERROR_MESSAGE);
            } else {
                controller.addAdminDescriptor(txtName.getValue().toString(), txtContent.getValue().toString());
                (subwindow.getParent()).removeWindow(subwindow);
                router.getMainWindow().showNotification("Addedd Successfully",
                        Notification.TYPE_HUMANIZED_MESSAGE);
            }
        }
    });

    subwindow.addComponent(txtName);
    subwindow.addComponent(txtContent);
    subwindow.addComponent(addAdmDescButton);

    Button close = new Button(ViewConstants.CLOSE, new Button.ClickListener() {
        @Override
        public void buttonClick(@SuppressWarnings("unused") ClickEvent event) {
            (subwindow.getParent()).removeWindow(subwindow);
        }
    });
    layout.addComponent(close);
    layout.setComponentAlignment(close, Alignment.TOP_RIGHT);

    router.getMainWindow().addWindow(subwindow);

}

From source file:org.escidoc.browser.ui.maincontent.ContainerView.java

License:Open Source License

private void handleLayoutListeners() {
    if (hasAccess()) {

        vlPropertiesLeft.addListener(new LayoutClickListener() {
            private static final long serialVersionUID = 1L;

            @Override/*from w  w w.  j a v  a2  s  .  c  o  m*/
            public void layoutClick(final LayoutClickEvent event) {
                // Get the child component which was clicked

                if (event.getChildComponent() != null) {
                    // Is Label?
                    if (event.getChildComponent().getClass().getCanonicalName() == "com.vaadin.ui.Label") {
                        final Label child = (Label) event.getChildComponent();
                        if ((child.getDescription() == ViewConstants.DESC_STATUS)
                                && (!lblStatus.getValue().equals(status + "withdrawn"))) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editStatus(child.getValue().toString().replace(status, ""));
                            vlPropertiesLeft.replaceComponent(oldComponent, swapComponent);
                        } else if (child.getDescription() == ViewConstants.DESC_LOCKSTATUS) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editLockStatus(child.getValue().toString().replace(status, ""));
                            vlPropertiesLeft.replaceComponent(oldComponent, swapComponent);
                        }
                    }
                    // else {
                    // // getWindow().showNotification(
                    // // "The click was over a " +
                    // event.getChildComponent().getClass().getCanonicalName()
                    // // + event.getChildComponent().getStyleName());
                    // }
                } else {
                    reSwapComponents();
                }
            }

            /**
             * Switch the component back to the original component (Label) after inline editing
             */
            private void reSwapComponents() {

                if (swapComponent != null) {
                    if (swapComponent instanceof Label) {
                        ((Label) oldComponent).setValue(((TextArea) swapComponent).getValue());
                    } else if ((swapComponent instanceof ComboBox)
                            && ((ComboBox) swapComponent).getValue() != null) {
                        ((Label) oldComponent).setValue(status + ((ComboBox) swapComponent).getValue());
                        // Because there should be no comment-window on
                        // Delete Operation
                        if (!(((ComboBox) swapComponent).getValue().equals("delete"))) {
                            addCommentWindow();
                        } else {
                            updateContainer("");
                        }
                    }
                    vlPropertiesLeft.replaceComponent(swapComponent, oldComponent);
                    swapComponent = null;
                }
            }

            private Component editLockStatus(final String lockStatus) {
                final ComboBox cmbLockStatus = new ComboBox();
                cmbLockStatus.setNullSelectionAllowed(false);
                if (lockStatus.contains("unlocked")) {
                    cmbLockStatus.addItem(LockStatus.LOCKED.toString().toLowerCase());
                } else {
                    cmbLockStatus.addItem(LockStatus.UNLOCKED.toString().toLowerCase());
                }
                cmbLockStatus.select(1);
                return cmbLockStatus;

            }

            private Component editStatus(final String publicStatus) {
                final ComboBox cmbStatus = new ComboBox();
                cmbStatus.setInvalidAllowed(false);
                cmbStatus.setNullSelectionAllowed(false);
                final String pubStatus = publicStatus.toUpperCase();
                if (publicStatus.equals("pending")) {
                    cmbStatus.addItem(PublicStatus.PENDING.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.setNullSelectionItemId(PublicStatus.PENDING.toString().toLowerCase());
                    if (hasAccessDelResource()) {
                        cmbStatus.addItem("delete");
                    }

                } else if (publicStatus.equals("submitted")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                } else if (publicStatus.equals("in_revision")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                } else if (publicStatus.equals("released")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.WITHDRAWN.toString().toLowerCase());
                } else if (publicStatus.equals("withdrawn")) {
                    // do nothing
                } else {
                    cmbStatus.addItem(PublicStatus.valueOf(pubStatus));
                }
                cmbStatus.select(1);

                return cmbStatus;
            }

            private boolean hasAccessDelResource() {
                try {
                    return repositories.pdp().forCurrentUser().isAction(ActionIdConstants.DELETE_CONTAINER)
                            .forResource(resourceProxy.getId()).permitted();
                } catch (UnsupportedOperationException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (EscidocClientException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (URISyntaxException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                }
            }

            public void addCommentWindow() {
                subwindow = new Window(ViewConstants.SUBWINDOW_EDIT);
                subwindow.setModal(true);
                // Configure the windws layout; by default a VerticalLayout
                VerticalLayout layout = (VerticalLayout) subwindow.getContent();
                layout.setMargin(true);
                layout.setSpacing(true);
                layout.setSizeUndefined();

                final TextArea editor = new TextArea("Your Comment");
                editor.setRequired(true);
                editor.setRequiredError("The Field may not be empty.");

                HorizontalLayout hl = new HorizontalLayout();

                Button close = new Button("Update", new Button.ClickListener() {
                    // inline click-listener
                    @Override
                    public void buttonClick(ClickEvent event) {
                        // close the window by removing it from the
                        // parent window
                        updateContainer(editor.getValue().toString());
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });
                Button cancel = new Button("Cancel", new Button.ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });

                hl.addComponent(close);
                hl.addComponent(cancel);

                subwindow.addComponent(editor);
                subwindow.addComponent(hl);
                mainWindow.addWindow(subwindow);
            }

            private void updatePublicStatus(Container container, String comment) {
                // Update PublicStatus if there is a change
                if (!resourceProxy.getVersionStatus()
                        .equals(lblCurrentVersionStatus.getValue().toString().replace(status, ""))) {

                    String publicStatusTxt = lblCurrentVersionStatus.getValue().toString().replace(status, "")
                            .toUpperCase();
                    if (publicStatusTxt.equals("DELETE")) {
                        new ResourceDeleteConfirmation(container, repositories.container(), mainWindow);

                    }
                    try {
                        repositories.container().changePublicStatus(container,
                                lblCurrentVersionStatus.getValue().toString().replace(status, "").toUpperCase(),
                                comment);
                        if (publicStatusTxt.equals("SUBMITTED")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.SUBMITTED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("IN_REVISION")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.IN_REVISION,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("RELEASED")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.RELEASED,
                                    Notification.TYPE_TRAY_NOTIFICATION));

                        } else if (publicStatusTxt.equals("WITHDRAWN")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.WITHDRAWN,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        }
                    } catch (EscidocClientException e) {
                        mainWindow.showNotification(new Window.Notification(ViewConstants.ERROR, e.getMessage(),
                                Notification.TYPE_ERROR_MESSAGE));
                    }
                }
            }

            private void updateLockStatus(Container container, String comment) {
                // Update LockStatus if there is a change
                if (!resourceProxy.getLockStatus()
                        .equals(lblLockstatus.getValue().toString().replace(lockStatus, ""))) {
                    String lockStatusTxt = lblLockstatus.getValue().toString().replace(lockStatus, "")
                            .toUpperCase();
                    try {
                        if (lockStatusTxt.contains("LOCKED")) {
                            repositories.container().unlockResource(container, comment);
                            mainWindow.showNotification(new Window.Notification(ViewConstants.LOCKED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else {
                            repositories.container().lockResource(container, comment);
                            mainWindow.showNotification(new Window.Notification(ViewConstants.UNLOCKED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        }

                    } catch (EscidocClientException e) {
                        mainWindow.showNotification(new Window.Notification(ViewConstants.ERROR, e.getMessage(),
                                Notification.TYPE_ERROR_MESSAGE));
                    }
                }
            }

            private void updateContainer(String comment) {
                LOG.debug("Called the updateContainer");
                Container container;
                try {
                    container = repositories.container().findContainerById(resourceProxy.getId());
                    if (resourceProxy.getLockStatus().contains("unlocked")) {
                        updatePublicStatus(container, comment);
                        // retrive the container to get the last
                        // modifiaction date.
                        container = repositories.container().findContainerById(resourceProxy.getId());
                        updateLockStatus(container, comment);
                    } else {
                        updateLockStatus(container, comment);
                        updatePublicStatus(container, comment);
                    }
                } catch (final EscidocClientException e) {
                    LOG.debug("Infrastructure Exception " + e.getLocalizedMessage());
                }
            }

        });
    }

}

From source file:org.escidoc.browser.ui.maincontent.ContextView.java

License:Open Source License

/**
 * Called in the reSwapComponents()/*from  w w  w  .  j a va2s .  c o m*/
 * 
 * @return String
 */
public void addCommentWindow(final String status) {
    final Window subwindow = new Window(ViewConstants.SUBWINDOW_EDIT);
    subwindow.setModal(true);
    // Configure the windws layout; by default a VerticalLayout
    VerticalLayout layout = (VerticalLayout) subwindow.getContent();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.setSizeUndefined();

    final TextArea editor = new TextArea("Your Comment");
    editor.setRequired(true);
    editor.setRequiredError("The Field may not be empty.");

    HorizontalLayout hl = new HorizontalLayout();

    Button close = new Button("Update", new Button.ClickListener() {

        @Override
        public void buttonClick(@SuppressWarnings("unused") com.vaadin.ui.Button.ClickEvent event) {
            // close the window by removing it from the parent window
            String comment = editor.getValue().toString();
            try {
                contextController.updatePublicStatus(status, resourceProxy.getId(), comment);
                mainWindow.showNotification("Context Status updated successfully",
                        Notification.TYPE_TRAY_NOTIFICATION);
            } catch (EscidocClientException e) {
                mainWindow.showNotification(
                        "Could not update Context Type, an error occurred" + e.getLocalizedMessage(),
                        Notification.TYPE_ERROR_MESSAGE);
            }
            (subwindow.getParent()).removeWindow(subwindow);

        }
    });
    Button cancel = new Button("Cancel", new Button.ClickListener() {
        @Override
        public void buttonClick(@SuppressWarnings("unused") com.vaadin.ui.Button.ClickEvent event) {
            (subwindow.getParent()).removeWindow(subwindow);

        }
    });

    hl.addComponent(close);
    hl.addComponent(cancel);

    subwindow.addComponent(editor);
    subwindow.addComponent(hl);
    mainWindow.addWindow(subwindow);
}

From source file:org.escidoc.browser.ui.maincontent.FolderView.java

License:Open Source License

private void handleLayoutListeners() {
    if (folderController.hasAccess()) {
        vlLeft.addListener(new LayoutClickListener() {
            private static final long serialVersionUID = 1L;

            private Window subwindow;

            @Override/* w ww .  j  a va 2 s.  c  o  m*/
            public void layoutClick(final LayoutClickEvent event) {
                // Get the child component which was clicked

                if (event.getChildComponent() != null) {
                    // Is Label?
                    if (event.getChildComponent().getClass().getCanonicalName() == "com.vaadin.ui.Label") {
                        final Label child = (Label) event.getChildComponent();
                        if ((child.getDescription() == ViewConstants.DESC_STATUS)
                                && (!lblStatus.getValue().equals(status + "withdrawn"))) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editStatus(child.getValue().toString().replace(status, ""));
                            vlLeft.replaceComponent(oldComponent, swapComponent);
                        } else if (child.getDescription() == ViewConstants.DESC_LOCKSTATUS) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editLockStatus(child.getValue().toString().replace(status, ""));
                            vlLeft.replaceComponent(oldComponent, swapComponent);
                        }
                    }
                    // else {
                    // // getWindow().showNotification(
                    // // "The click was over a " +
                    // event.getChildComponent().getClass().getCanonicalName()
                    // // + event.getChildComponent().getStyleName());
                    // }
                } else {
                    reSwapComponents();
                }
            }

            /**
             * Switch the component back to the original component (Label) after inline editing
             */
            private void reSwapComponents() {

                if (swapComponent != null) {
                    if (swapComponent instanceof Label) {
                        ((Label) oldComponent).setValue(((TextArea) swapComponent).getValue());
                    } else if ((swapComponent instanceof ComboBox)
                            && ((ComboBox) swapComponent).getValue() != null) {
                        ((Label) oldComponent).setValue(status + ((ComboBox) swapComponent).getValue());
                        // Because there should be no comment-window on
                        // Delete Operation
                        if (!(((ComboBox) swapComponent).getValue().equals("delete"))) {
                            addCommentWindow();
                        } else {
                            updateContainer("");
                        }
                    }
                    vlLeft.replaceComponent(swapComponent, oldComponent);
                    swapComponent = null;
                }
            }

            private Component editLockStatus(final String lockStatus) {
                final ComboBox cmbLockStatus = new ComboBox();
                cmbLockStatus.setNullSelectionAllowed(false);
                if (lockStatus.contains("unlocked")) {
                    cmbLockStatus.addItem(LockStatus.LOCKED.toString().toLowerCase());
                } else {
                    cmbLockStatus.addItem(LockStatus.UNLOCKED.toString().toLowerCase());
                }
                cmbLockStatus.select(1);
                return cmbLockStatus;

            }

            private Component editStatus(final String publicStatus) {
                final ComboBox cmbStatus = new ComboBox();
                cmbStatus.setInvalidAllowed(false);
                cmbStatus.setNullSelectionAllowed(false);
                final String pubStatus = publicStatus.toUpperCase();
                if (publicStatus.equals("pending")) {
                    cmbStatus.addItem(PublicStatus.PENDING.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.setNullSelectionItemId(PublicStatus.PENDING.toString().toLowerCase());
                    if (hasAccessDelResource()) {
                        cmbStatus.addItem("delete");
                    }

                } else if (publicStatus.equals("submitted")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                } else if (publicStatus.equals("in_revision")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                } else if (publicStatus.equals("released")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.WITHDRAWN.toString().toLowerCase());
                } else if (publicStatus.equals("withdrawn")) {
                    // do nothing
                } else {
                    cmbStatus.addItem(PublicStatus.valueOf(pubStatus));
                }
                cmbStatus.select(1);

                return cmbStatus;
            }

            private boolean hasAccessDelResource() {
                try {
                    return repositories.pdp().forCurrentUser().isAction(ActionIdConstants.DELETE_CONTAINER)
                            .forResource(resourceProxy.getId()).permitted();
                } catch (UnsupportedOperationException e) {
                    router.getMainWindow().showNotification(e.getMessage(),
                            Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (EscidocClientException e) {
                    router.getMainWindow().showNotification(e.getMessage(),
                            Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (URISyntaxException e) {
                    router.getMainWindow().showNotification(e.getMessage(),
                            Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                }
            }

            public void addCommentWindow() {
                subwindow = new Window(ViewConstants.SUBWINDOW_EDIT);
                subwindow.setModal(true);
                // Configure the windws layout; by default a VerticalLayout
                VerticalLayout layout = (VerticalLayout) subwindow.getContent();
                layout.setMargin(true);
                layout.setSpacing(true);
                layout.setSizeUndefined();

                final TextArea editor = new TextArea("Your Comment");
                editor.setRequired(true);
                editor.setRequiredError("The Field may not be empty.");

                HorizontalLayout hl = new HorizontalLayout();

                Button close = new Button("Update", new Button.ClickListener() {
                    // inline click-listener
                    @Override
                    public void buttonClick(ClickEvent event) {
                        // close the window by removing it from the
                        // parent window
                        updateContainer(editor.getValue().toString());
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });
                Button cancel = new Button("Cancel", new Button.ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });

                hl.addComponent(close);
                hl.addComponent(cancel);

                subwindow.addComponent(editor);
                subwindow.addComponent(hl);
                router.getMainWindow().addWindow(subwindow);
            }

            private void updatePublicStatus(Container container, String comment) {
                // Update PublicStatus if there is a change
                if (!resourceProxy.getVersionStatus()
                        .equals(lblCurrentVersionStatus.getValue().toString().replace(status, ""))) {

                    String publicStatusTxt = lblCurrentVersionStatus.getValue().toString().replace(status, "")
                            .toUpperCase();
                    if (publicStatusTxt.equals("DELETE")) {
                        new ResourceDeleteConfirmation(container, repositories.container(),
                                router.getMainWindow());

                    }
                    try {
                        repositories.container().changePublicStatus(container,
                                lblCurrentVersionStatus.getValue().toString().replace(status, "").toUpperCase(),
                                comment);
                        if (publicStatusTxt.equals("SUBMITTED")) {
                            router.getMainWindow().showNotification(new Window.Notification(
                                    ViewConstants.SUBMITTED, Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("IN_REVISION")) {
                            router.getMainWindow().showNotification(new Window.Notification(
                                    ViewConstants.IN_REVISION, Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("RELEASED")) {
                            router.getMainWindow().showNotification(new Window.Notification(
                                    ViewConstants.RELEASED, Notification.TYPE_TRAY_NOTIFICATION));

                        } else if (publicStatusTxt.equals("WITHDRAWN")) {
                            router.getMainWindow().showNotification(new Window.Notification(
                                    ViewConstants.WITHDRAWN, Notification.TYPE_TRAY_NOTIFICATION));
                        }
                    } catch (EscidocClientException e) {
                        router.getMainWindow().showNotification(new Window.Notification(ViewConstants.ERROR,
                                e.getMessage(), Notification.TYPE_ERROR_MESSAGE));
                    }
                }
            }

            private void updateContainer(String comment) {
                LOG.debug("Called the updateContainer");
                Container container;
                try {
                    container = repositories.container().findContainerById(resourceProxy.getId());
                    if (resourceProxy.getLockStatus().contains("unlocked")) {
                        container = repositories.container().findContainerById(resourceProxy.getId());
                        updatePublicStatus(container, comment);
                    } else {
                        updatePublicStatus(container, comment);
                    }
                } catch (final EscidocClientException e) {
                    LOG.debug("Infrastructure Exception " + e.getLocalizedMessage());
                }
            }

        });
    }

}

From source file:org.escidoc.browser.ui.view.helpers.ItemPropertiesVH.java

License:Open Source License

private void handleLayoutListeners() {
    if (controller.canUpdateItem()) {
        vlPropertiesLeft.addListener(new LayoutClickListener() {

            @Override//from   ww w . j  a  v  a  2 s  . c  o  m
            public void layoutClick(final LayoutClickEvent event) {
                // Get the child component which was clicked

                if (event.getChildComponent() != null) {

                    // Is Label?
                    if (event.getChildComponent().getClass().getCanonicalName().equals("com.vaadin.ui.Label")) {
                        final Label child = (Label) event.getChildComponent();
                        if ((child.getDescription() == ViewConstants.DESC_STATUS2)
                                && (!lblStatus.getValue().equals(status + "withdrawn"))) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editStatus(child.getValue().toString().replace(status, ""));
                            vlPropertiesLeft.replaceComponent(oldComponent, swapComponent);
                        } else if (child.getDescription() == ViewConstants.DESC_LOCKSTATUS) {
                            reSwapComponents();
                            oldComponent = event.getClickedComponent();
                            swapComponent = editLockStatus(child.getValue().toString().replace(status, ""));
                            vlPropertiesLeft.replaceComponent(oldComponent, swapComponent);
                        }
                    }
                } else {
                    reSwapComponents();
                }
            }

            /**
             * Switch the component back to the original component (Label) after inline editing
             */
            private void reSwapComponents() {

                if (swapComponent != null) {
                    if (swapComponent instanceof Label) {
                        ((Label) oldComponent).setValue(((TextArea) swapComponent).getValue());
                    } else if ((swapComponent instanceof ComboBox)
                            && ((ComboBox) swapComponent).getValue() != null) {
                        ((Label) oldComponent).setValue(status + ((ComboBox) swapComponent).getValue());
                        // Because there should be no comment-window on
                        // Delete Operation
                        if (!(((ComboBox) swapComponent).getValue().equals("delete"))) {
                            addCommentWindow();
                        } else {
                            updateItem("");
                        }
                    }
                    vlPropertiesLeft.replaceComponent(swapComponent, oldComponent);
                    swapComponent = null;
                }
            }

            private Component editLockStatus(final String lockStatus) {
                final ComboBox cmbLockStatus = new ComboBox();
                cmbLockStatus.setNullSelectionAllowed(false);
                if (lockStatus.contains("unlocked")) {
                    cmbLockStatus.addItem(LockStatus.LOCKED.toString().toLowerCase());
                } else {
                    cmbLockStatus.addItem(LockStatus.UNLOCKED.toString().toLowerCase());
                }
                cmbLockStatus.select(Integer.valueOf(1));
                return cmbLockStatus;

            }

            private Component editStatus(final String publicStatus) {
                final ComboBox cmbStatus = new ComboBox();
                cmbStatus.setInvalidAllowed(false);
                cmbStatus.setNullSelectionAllowed(false);
                final String pubStatus = publicStatus.toUpperCase();
                if (publicStatus.equals("pending")) {
                    cmbStatus.addItem(PublicStatus.PENDING.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.setNullSelectionItemId(PublicStatus.PENDING.toString().toLowerCase());

                    if (hasAccessDelResource()) {
                        cmbStatus.addItem("delete");
                    }
                } else if (publicStatus.equals("submitted")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                } else if (publicStatus.equals("in_revision")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.IN_REVISION.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.SUBMITTED.toString().toLowerCase());
                } else if (publicStatus.equals("released")) {
                    cmbStatus.setNullSelectionItemId(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.RELEASED.toString().toLowerCase());
                    cmbStatus.addItem(PublicStatus.WITHDRAWN.toString().toLowerCase());
                } else if (publicStatus.equals("withdrawn")) {
                    lblStatus.setValue("withdrawn");
                } else {
                    cmbStatus.addItem(PublicStatus.valueOf(pubStatus));
                }
                cmbStatus.select(Integer.valueOf(1));

                return cmbStatus;
            }

            private boolean hasAccessDelResource() {
                try {
                    return repositories.pdp().forCurrentUser().isAction(ActionIdConstants.DELETE_CONTAINER)
                            .forResource(resourceProxy.getId()).permitted();
                } catch (final UnsupportedOperationException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (final EscidocClientException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                } catch (final URISyntaxException e) {
                    mainWindow.showNotification(e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                }
            }

            public void addCommentWindow() {
                subwindow = new Window(ViewConstants.SUBWINDOW_EDIT);
                subwindow.setModal(true);
                // Configure the windws layout; by default a VerticalLayout
                final VerticalLayout layout = (VerticalLayout) subwindow.getContent();
                layout.setMargin(true);
                layout.setSpacing(true);
                layout.setSizeUndefined();

                final TextArea editor = new TextArea("Your Comment");
                editor.setRequired(true);
                editor.setRequiredError("The Field may not be empty.");

                final HorizontalLayout hl = new HorizontalLayout();

                final Button close = new Button("Update", new Button.ClickListener() {

                    private static final long serialVersionUID = 1424933077274899865L;

                    // inline click-listener
                    @Override
                    public void buttonClick(final ClickEvent event) {
                        // close the window by removing it from the
                        // parent window
                        updateItem(editor.getValue().toString());
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });
                final Button cancel = new Button("Cancel", new Button.ClickListener() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public void buttonClick(final ClickEvent event) {
                        (subwindow.getParent()).removeWindow(subwindow);
                    }
                });

                hl.addComponent(close);
                hl.addComponent(cancel);

                subwindow.addComponent(editor);
                subwindow.addComponent(hl);
                mainWindow.addWindow(subwindow);
            }

            private void updatePublicStatus(final Item item, final String comment) {
                Preconditions.checkNotNull(item, "Item is null");
                Preconditions.checkNotNull(comment, "Comment is null");
                // Update PublicStatus if there is a change
                if (!resourceProxy.getVersionStatus()
                        .equals(lblCurrentVersionStatus.getValue().toString().replace(status, ""))) {
                    String publicStatusTxt = lblCurrentVersionStatus.getValue().toString().replace(status, "")
                            .toUpperCase();
                    if (publicStatusTxt.equals("DELETE")) {
                        new ResourceDeleteConfirmation(item, repositories.item(), mainWindow);
                    }
                    try {
                        repositories.item().changePublicStatus(item,
                                lblCurrentVersionStatus.getValue().toString().replace(status, "").toUpperCase(),
                                comment);
                        if (publicStatusTxt.equals("SUBMITTED")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.SUBMITTED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("IN_REVISION")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.IN_REVISION,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("RELEASED")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.RELEASED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else if (publicStatusTxt.equals("WITHDRAWN")) {
                            mainWindow.showNotification(new Window.Notification(ViewConstants.WITHDRAWN,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        }
                    } catch (EscidocClientException e) {
                        mainWindow.showNotification(new Window.Notification(ViewConstants.ERROR, e.getMessage(),
                                Notification.TYPE_ERROR_MESSAGE));
                    }
                }
            }

            private void updateLockStatus(final Item item, final String comment) {
                if (!resourceProxy.getLockStatus()
                        .equals(lblLockstatus.getValue().toString().replace(lockStatus, ""))) {
                    String lockStatusTxt = lblLockstatus.getValue().toString().replace(lockStatus, "")
                            .toUpperCase();
                    try {
                        if (lockStatusTxt.contains("LOCKED")) {
                            repositories.item().lockResource(item, comment);
                            mainWindow.showNotification(new Window.Notification(ViewConstants.LOCKED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        } else {
                            repositories.item().unlockResource(item, comment);
                            mainWindow.showNotification(new Window.Notification(ViewConstants.UNLOCKED,
                                    Notification.TYPE_TRAY_NOTIFICATION));
                        }

                    } catch (EscidocClientException e) {
                        mainWindow.showNotification(new Window.Notification(ViewConstants.ERROR, e.getMessage(),
                                Notification.TYPE_ERROR_MESSAGE));
                    }
                }
            }

            private void updateItem(final String comment) {
                Item item;
                try {
                    item = repositories.item().findItemById(resourceProxy.getId());
                    if (resourceProxy.getLockStatus().equals("unlocked")) {
                        updatePublicStatus(item, comment);
                        // retrive the container to get the last
                        // modifiaction date.
                        item = repositories.item().findItemById(resourceProxy.getId());
                        updateLockStatus(item, comment);
                    } else {
                        updateLockStatus(item, comment);
                        updatePublicStatus(item, comment);
                    }
                } catch (final EscidocClientException e) {
                    LOG.debug("Infrastructure Exception " + e.getLocalizedMessage());
                }
            }

        });
    }

}

From source file:org.ikasan.dashboard.ui.topology.window.ComponentConfigurationWindow.java

License:BSD License

@SuppressWarnings("unchecked")
public void populate(Component component) {
    configuration = this.configurationManagement.getConfiguration(component.getConfigurationId());

    if (configuration == null) {
        Server server = component.getFlow().getModule().getServer();

        String url = "http://" + server.getUrl() + ":" + server.getPort()
                + component.getFlow().getModule().getContextRoot() + "/rest/configuration/createConfiguration/"
                + component.getFlow().getModule().getName() + "/" + component.getFlow().getName() + "/"
                + component.getName();/*w  w w . j a va2 s .  co m*/

        logger.info("Configuration Url: " + url);

        IkasanAuthentication authentication = (IkasanAuthentication) VaadinService.getCurrentRequest()
                .getWrappedSession().getAttribute(DashboardSessionValueConstants.USER);

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(authentication.getName(),
                (String) authentication.getCredentials());

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(feature);

        Client client = ClientBuilder.newClient(clientConfig);

        ObjectMapper mapper = new ObjectMapper();

        WebTarget webTarget = client.target(url);

        Response response = webTarget.request().get();

        if (response.getStatus() != 200) {
            response.bufferEntity();

            String responseMessage = response.readEntity(String.class);
            Notification.show("An error was received trying to create configured resource '"
                    + component.getConfigurationId() + "': " + responseMessage, Type.ERROR_MESSAGE);
        }

        configuration = this.configurationManagement.getConfiguration(component.getConfigurationId());
    }

    final List<ConfigurationParameter> parameters = (List<ConfigurationParameter>) configuration
            .getParameters();

    this.layout = new GridLayout(2, parameters.size() + 6);
    this.layout.setSpacing(true);
    this.layout.setColumnExpandRatio(0, .25f);
    this.layout.setColumnExpandRatio(1, .75f);

    this.layout.setWidth("95%");
    this.layout.setMargin(true);

    Label configurationParametersLabel = new Label("Configuration Parameters");
    configurationParametersLabel.setStyleName(ValoTheme.LABEL_HUGE);
    this.layout.addComponent(configurationParametersLabel, 0, 0);

    GridLayout paramLayout = new GridLayout(2, 2);
    paramLayout.setSpacing(true);
    paramLayout.setSizeFull();
    paramLayout.setMargin(true);
    paramLayout.setColumnExpandRatio(0, .25f);
    paramLayout.setColumnExpandRatio(1, .75f);

    Label configuredResourceIdLabel = new Label("Configured Resource Id");
    configuredResourceIdLabel.addStyleName(ValoTheme.LABEL_LARGE);
    configuredResourceIdLabel.addStyleName(ValoTheme.LABEL_BOLD);
    Label configuredResourceIdValueLabel = new Label(configuration.getConfigurationId());
    configuredResourceIdValueLabel.addStyleName(ValoTheme.LABEL_LARGE);
    configuredResourceIdValueLabel.addStyleName(ValoTheme.LABEL_BOLD);

    paramLayout.addComponent(configuredResourceIdLabel, 0, 0);
    paramLayout.setComponentAlignment(configuredResourceIdLabel, Alignment.TOP_RIGHT);
    paramLayout.addComponent(configuredResourceIdValueLabel, 1, 0);

    Label configurationDescriptionLabel = new Label("Description:");
    configurationDescriptionLabel.setSizeUndefined();
    paramLayout.addComponent(configurationDescriptionLabel, 0, 1);
    paramLayout.setComponentAlignment(configurationDescriptionLabel, Alignment.TOP_RIGHT);

    TextArea conmfigurationDescriptionTextField = new TextArea();
    conmfigurationDescriptionTextField.setRows(4);
    conmfigurationDescriptionTextField.setWidth("80%");
    paramLayout.addComponent(conmfigurationDescriptionTextField, 1, 1);

    this.layout.addComponent(paramLayout, 0, 1, 1, 1);

    int i = 2;

    for (ConfigurationParameter parameter : parameters) {
        if (parameter instanceof ConfigurationParameterIntegerImpl) {
            this.layout.addComponent(
                    this.createTextAreaPanel(parameter, new IntegerValidator("Must be a valid number")), 0, i,
                    1, i);
        } else if (parameter instanceof ConfigurationParameterStringImpl) {
            this.layout.addComponent(this.createTextAreaPanel(parameter, new StringValidator()), 0, i, 1, i);
        } else if (parameter instanceof ConfigurationParameterBooleanImpl) {
            this.layout.addComponent(this.createTextAreaPanel(parameter, new BooleanValidator()), 0, i, 1, i);
        } else if (parameter instanceof ConfigurationParameterLongImpl) {
            this.layout.addComponent(this.createTextAreaPanel(parameter, new LongValidator()), 0, i, 1, i);
        } else if (parameter instanceof ConfigurationParameterMapImpl) {
            this.layout.addComponent(this.createMapPanel((ConfigurationParameterMapImpl) parameter), 0, i, 1,
                    i);
        } else if (parameter instanceof ConfigurationParameterListImpl) {
            this.layout.addComponent(this.createListPanel((ConfigurationParameterListImpl) parameter), 0, i, 1,
                    i);
        }

        i++;
    }

    Button saveButton = new Button("Save");
    saveButton.addStyleName(ValoTheme.BUTTON_SMALL);
    saveButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                for (TextArea textField : textFields.values()) {
                    textField.validate();
                }
            } catch (InvalidValueException e) {
                e.printStackTrace();
                for (TextArea textField : textFields.values()) {
                    textField.setValidationVisible(true);
                }

                Notification.show("There are errors on the form above", Type.ERROR_MESSAGE);

                return;
            }

            for (ConfigurationParameter parameter : parameters) {
                TextArea textField = ComponentConfigurationWindow.this.textFields.get(parameter.getName());
                TextArea descriptionTextField = ComponentConfigurationWindow.this.descriptionTextFields
                        .get(parameter.getName());

                if (parameter != null && descriptionTextField != null) {
                    parameter.setDescription(descriptionTextField.getValue());
                }

                if (parameter instanceof ConfigurationParameterIntegerImpl) {
                    logger.info("Setting Integer value: " + textField.getValue());

                    if (textField.getValue() != null && textField.getValue().length() > 0)
                        parameter.setValue(new Integer(textField.getValue()));
                } else if (parameter instanceof ConfigurationParameterStringImpl) {
                    logger.info("Setting String value: " + textField.getValue());
                    if (textField.getValue() != null && textField.getValue().length() > 0)
                        parameter.setValue(textField.getValue());
                } else if (parameter instanceof ConfigurationParameterBooleanImpl) {
                    logger.info("Setting Boolean value: " + textField.getValue());
                    if (textField.getValue() != null && textField.getValue().length() > 0)
                        parameter.setValue(new Boolean(textField.getValue()));
                } else if (parameter instanceof ConfigurationParameterLongImpl) {
                    logger.info("Setting Boolean value: " + textField.getValue());
                    if (textField.getValue() != null && textField.getValue().length() > 0)
                        parameter.setValue(new Long(textField.getValue()));
                } else if (parameter instanceof ConfigurationParameterMapImpl) {
                    ConfigurationParameterMapImpl mapParameter = (ConfigurationParameterMapImpl) parameter;

                    HashMap<String, String> map = new HashMap<String, String>();

                    logger.info("Saving map: " + mapTextFields.size());

                    for (String key : mapTextFields.keySet()) {
                        if (key.startsWith(parameter.getName())) {
                            TextFieldKeyValuePair pair = mapTextFields.get(key);

                            logger.info("Saving for key: " + key);

                            if (pair.key.getValue() != "") {
                                map.put(pair.key.getValue(), pair.value.getValue());
                            }
                        }
                    }

                    parameter.setValue(map);
                } else if (parameter instanceof ConfigurationParameterListImpl) {
                    ConfigurationParameterListImpl mapParameter = (ConfigurationParameterListImpl) parameter;

                    ArrayList<String> map = new ArrayList<String>();

                    for (String key : valueTextFields.keySet()) {
                        if (key.startsWith(parameter.getName())) {
                            map.add(valueTextFields.get(key).getValue());
                        }
                    }

                    parameter.setValue(map);
                }

            }

            ComponentConfigurationWindow.this.configurationManagement.saveConfiguration(configuration);

            Notification notification = new Notification("Saved",
                    "The configuration has been saved successfully!", Type.HUMANIZED_MESSAGE);
            notification.setStyleName(ValoTheme.NOTIFICATION_CLOSABLE);
            notification.show(Page.getCurrent());
        }
    });

    Button deleteButton = new Button("Delete");
    deleteButton.addStyleName(ValoTheme.BUTTON_SMALL);
    deleteButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            DeleteConfigurationAction action = new DeleteConfigurationAction(configuration,
                    configurationManagement, ComponentConfigurationWindow.this);

            IkasanMessageDialog dialog = new IkasanMessageDialog("Delete configuration",
                    "Are you sure you would like to delete this configuration?", action);

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

    GridLayout buttonLayout = new GridLayout(2, 1);
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(saveButton, 0, 0);
    buttonLayout.addComponent(deleteButton, 1, 0);

    this.layout.addComponent(buttonLayout, 0, i, 1, i);
    this.layout.setComponentAlignment(buttonLayout, Alignment.MIDDLE_CENTER);

    Panel configurationPanel = new Panel();
    configurationPanel.setContent(this.layout);

    this.setContent(configurationPanel);
}

From source file:org.opennms.features.topology.netutils.internal.ping.PingWindow.java

License:Open Source License

/**
 * Creates the PingWindow to make ping requests.
 *
 * @param locations All available locations to ping from. Must not be null.
 * @param defaultLocation The location to pre-select from the locations. Ensure <code>defaultLocation</code> is also available in the <code>locations</code> list.
 * @param ipAddresses All available ipAddresses. Must not be null or empty.
 * @param defaultIp The default ip to pre-select from the ip addresses. Ensure <code>defaultIp</code> is also available in the <code>ipAddresses</code> list.
 * @param pingClient The LocationAwarePingClient to ping. Must not be null.
 *///  ww w  .j av a 2s  . c  o  m
public PingWindow(LocationAwarePingClient pingClient, List<String> locations, List<InetAddress> ipAddresses,
        String defaultLocation, InetAddress defaultIp, String caption) {
    Objects.requireNonNull(pingClient);
    Objects.requireNonNull(ipAddresses);
    Objects.requireNonNull(defaultIp);
    Objects.requireNonNull(locations);
    Objects.requireNonNull(defaultLocation);
    Objects.requireNonNull(caption);

    // Remember initial poll interval, as we poll as soon as we start pinging
    final int initialPollInterval = UI.getCurrent().getPollInterval();

    // Ping Form
    pingForm = new PingForm(locations, defaultLocation, ipAddresses, defaultIp);

    // Result
    final TextArea resultArea = new TextArea();
    resultArea.setRows(15);
    resultArea.setSizeFull();

    // Progress Indicator
    progressIndicator = new ProgressBar();
    progressIndicator.setIndeterminate(true);

    // Buttons
    cancelButton = new Button("Cancel");
    cancelButton.addClickListener((event) -> {
        cancel(pingFuture);
        resultArea.setValue(resultArea.getValue() + "\n" + "Ping cancelled by user");
        getUI().setPollInterval(initialPollInterval);
        setRunning(false);
    });
    pingButton = new Button("Ping");
    pingButton.addClickListener((event) -> {
        try {
            final PingRequest pingRequest = pingForm.getPingRequest();

            resultArea.setValue(""); // Clear
            setRunning(true);
            getUI().setPollInterval(POLL_INTERVAL);

            pingFuture = pingClient.ping(pingRequest.getInetAddress()).withRetries(pingRequest.getRetries())
                    .withPacketSize(pingRequest.getPacketSize())
                    .withTimeout(pingRequest.getTimeout(), TimeUnit.MILLISECONDS)
                    .withLocation(pingRequest.getLocation())
                    .withNumberOfRequests(pingRequest.getNumberRequests())
                    .withProgressCallback((newSequence, summary) -> {
                        getUI().accessSynchronously(() -> {
                            if (pingFuture != null && !pingFuture.isCancelled()) {
                                setRunning(!summary.isComplete());
                                resultArea.setValue(PingStringUtils.renderAll(summary));
                                if (summary.isComplete()) {
                                    getUI().setPollInterval(initialPollInterval);
                                }
                            }
                        });
                    }).execute();
        } catch (FieldGroup.CommitException e) {
            Notification.show("Validation errors",
                    "Please correct them. Make sure all required fields are set.",
                    Notification.Type.ERROR_MESSAGE);
        }
    });

    // Button Layout
    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(pingButton);
    buttonLayout.addComponent(cancelButton);
    buttonLayout.addComponent(progressIndicator);

    // Root Layout
    final VerticalLayout rootLayout = new VerticalLayout();
    rootLayout.setSpacing(true);
    rootLayout.setMargin(true);
    rootLayout.addComponent(pingForm);
    rootLayout.addComponent(buttonLayout);
    rootLayout.addComponent(new Label("<b>Results</b>", ContentMode.HTML));
    rootLayout.addComponent(resultArea);
    rootLayout.setExpandRatio(resultArea, 1.0f);

    // Window Config
    setCaption(caption);
    setResizable(false);
    setModal(true);
    setWidth(800, Unit.PIXELS);
    setHeight(600, Unit.PIXELS);
    setContent(rootLayout);
    center();
    setRunning(false);

    // Set back to default, when closing
    addCloseListener((CloseListener) e -> {
        cancel(pingFuture);
        getUI().setPollInterval(initialPollInterval);
    });
}

From source file:org.opennms.features.topology.netutils.internal.PingWindow.java

License:Open Source License

/**
 * Creates the PingWindow to make ping requests.
 *
 * @param vertex The vertex which IP Address is pinged.
 *               It is expected that the IP Address os not null and parseable.
 * @param pingService The {@link PingService} to actually make the ping request.
 *///from   w w  w.j a  v a2  s.c om
public PingWindow(Vertex vertex, PingService pingService) {
    Objects.requireNonNull(vertex);
    Objects.requireNonNull(pingService);

    // Remember initial poll interval, as we poll as soon as we start pinging
    final int initialPollInterval = UI.getCurrent().getPollInterval();

    // Ping Form
    pingForm = new PingForm(InetAddressUtils.getInetAddress(vertex.getIpAddress()));

    // Result
    final TextArea resultArea = new TextArea();
    resultArea.setRows(15);
    resultArea.setSizeFull();

    // Progress Indicator
    progressIndicator = new ProgressBar();
    progressIndicator.setIndeterminate(true);

    // Buttons
    cancelButton = new Button("Cancel");
    cancelButton.addClickListener((event) -> {
        pingService.cancel();
        resultArea.setValue(resultArea.getValue() + "\n" + "Ping cancelled by user");
        getUI().setPollInterval(initialPollInterval);
        setRunning(false);
    });
    pingButton = new Button("Ping");
    pingButton.addClickListener((event) -> {
        try {
            final PingRequest pingRequest = pingForm.getPingRequest();
            setRunning(true);
            getUI().setPollInterval(POLL_INTERVAL);
            resultArea.setValue(""); // Clear
            pingService.ping(pingRequest, (result) -> {
                setRunning(!result.isComplete());
                resultArea.setValue(result.toDetailString());
                if (result.isComplete()) {
                    getUI().setPollInterval(initialPollInterval);
                }
            });
        } catch (FieldGroup.CommitException e) {
            Notification.show("Validation errors",
                    "Please correct them. Make sure all required fields are set.",
                    Notification.Type.ERROR_MESSAGE);
        }
    });
    // Button Layout
    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(pingButton);
    buttonLayout.addComponent(cancelButton);
    buttonLayout.addComponent(progressIndicator);

    // Root Layout
    final VerticalLayout rootLayout = new VerticalLayout();
    rootLayout.setSpacing(true);
    rootLayout.setMargin(true);
    rootLayout.addComponent(pingForm);
    rootLayout.addComponent(buttonLayout);
    rootLayout.addComponent(new Label("<b>Results</b>", ContentMode.HTML));
    rootLayout.addComponent(resultArea);
    rootLayout.setExpandRatio(resultArea, 1.0f);

    // Window Config
    setCaption(String.format("Ping - %s (%s)", vertex.getLabel(), vertex.getIpAddress()));
    setResizable(false);
    setModal(true);
    setWidth(800, Unit.PIXELS);
    setHeight(550, Unit.PIXELS);
    setContent(rootLayout);
    center();
    setRunning(false);

    // Set back to default, when closing
    addCloseListener((CloseListener) e -> {
        pingService.cancel();
        getUI().setPollInterval(initialPollInterval);
    });
}

From source file:org.vaadin.addons.serverpush.samples.chat.ChatLayout.java

License:Apache License

public ChatLayout(final User user, final User from) {
    setSizeFull();//from  ww w  .  j  a v a 2  s .  c o m
    Table table = new Table();
    table.setSizeFull();
    table.setContainerDataSource(new MessageContainer(user, from));
    table.addListener(new Container.ItemSetChangeListener() {
        public void containerItemSetChange(Container.ItemSetChangeEvent event) {
            ((Pushable) getApplication()).push();
        }
    });
    table.setVisibleColumns(new String[] { "from", "to", "received", "message" });

    addComponent(table);

    HorizontalLayout hl = new HorizontalLayout();
    hl.setWidth("100%");
    final TextArea textArea = new TextArea();
    textArea.setRows(5);
    textArea.setSizeFull();
    textArea.setWordwrap(true);
    textArea.setValue("");
    hl.addComponent(textArea);

    Button sendButton = new Button("Send");
    sendButton.setWidth("120px");
    sendButton.setImmediate(true);
    sendButton.addListener(new Button.ClickListener() {
        public void buttonClick(Button.ClickEvent event) {
            Message msg = new Message();
            msg.setFrom(from);
            msg.setTo(user);
            msg.setMessage(textArea.getValue().toString());
            MessageManager.getInstance().addMessage(msg);
            textArea.setValue("");
        }
    });
    hl.addComponent(sendButton);
    hl.setComponentAlignment(sendButton, Alignment.BOTTOM_RIGHT);
    hl.setExpandRatio(textArea, 1);
    addComponent(hl);

    setExpandRatio(table, 1);
}

From source file:org.vaadin.tori.view.thread.ReportComponent.java

License:Apache License

private Component newReportLayout() {
    final VerticalLayout layout = new VerticalLayout();
    layout.setWidth("260px");
    layout.setSpacing(true);/*from   ww w .j  a  va 2s . c  o m*/
    layout.setMargin(true);

    layout.addComponent(new Label("What's wrong with this post?"));

    final OptionGroup reason = new OptionGroup();
    reason.addItem(Reason.SPAM);
    reason.setItemCaption(Reason.SPAM, "Spam");
    reason.addItem(Reason.OFFENSIVE);
    reason.setItemCaption(Reason.OFFENSIVE, "Offensive, abusive or hateful.");
    reason.addItem(Reason.WRONG_CATEGORY);
    reason.setItemCaption(Reason.WRONG_CATEGORY, "Doesn't belong in the category.");
    reason.addItem(Reason.MODERATOR_ALERT);
    reason.setItemCaption(Reason.MODERATOR_ALERT, "A moderator should take a look at it.");

    reason.setImmediate(true);
    reason.addValueChangeListener(new OptionGroup.ValueChangeListener() {
        @Override
        public void valueChange(final ValueChangeEvent event) {
            explanationLayout.setVisible(reason.getValue() == Reason.MODERATOR_ALERT);
            reportButton.setEnabled(reason.getValue() != null);
        }
    });

    layout.addComponent(reason);

    explanationLayout = new CssLayout();
    explanationLayout.setStyleName("explanationlayout");
    explanationLayout.addComponent(new Label("Here's why:"));
    final TextArea reasonText = createReasonTextArea();
    explanationLayout.addComponent(reasonText);
    explanationLayout.setVisible(false);
    explanationLayout.setWidth("100%");
    layout.addComponent(explanationLayout);

    final HorizontalLayout footer = new HorizontalLayout();
    footer.setSpacing(true);
    layout.addComponent(footer);
    layout.setComponentAlignment(footer, Alignment.BOTTOM_RIGHT);

    reportButton = new Button("Report Post");
    reportButton.addClickListener(new NativeButton.ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            final URI l = Page.getCurrent().getLocation();
            final String link = l.getScheme() + "://" + l.getAuthority() + l.getPath() + postPermalink;
            presenter.handlePostReport(post, (Reason) reason.getValue(), reasonText.getValue(), link);
            reportPopup.setPopupVisible(false);
        }
    });
    reportButton.setEnabled(false);
    footer.addComponent(reportButton);

    final Button cancel = ComponentUtil.getSecondaryButton("Cancel", new Button.ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            reportPopup.setPopupVisible(false);
        }
    });
    footer.addComponent(cancel);

    return layout;
}