Example usage for com.vaadin.ui HorizontalLayout setComponentAlignment

List of usage examples for com.vaadin.ui HorizontalLayout setComponentAlignment

Introduction

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

Prototype

@Override
    public void setComponentAlignment(Component childComponent, Alignment alignment) 

Source Link

Usage

From source file:edu.kit.dama.ui.admin.administration.usergroup.UserGroupAdministrationTab.java

License:Apache License

private VerticalLayout getMainLayout() {
    if (mainLayout == null) {
        String id = "mainLayout";
        LOGGER.debug("Building " + DEBUG_ID_PREFIX + id + " ...");

        mainLayout = new VerticalLayout();
        mainLayout.setId(DEBUG_ID_PREFIX + id);
        mainLayout.setSizeFull();/* ww  w.  ja  v a2 s.  c om*/
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);

        HorizontalLayout filterButtons = new HorizontalLayout(getRemoveAllFiltersButton(),
                getAddFilterButton());

        filterButtons.setComponentAlignment(getRemoveAllFiltersButton(), Alignment.BOTTOM_RIGHT);
        filterButtons.setComponentAlignment(getAddFilterButton(), Alignment.BOTTOM_RIGHT);

        // Add components to mainLayout
        mainLayout.addComponent(getUserGroupForm());
        mainLayout.addComponent(filterButtons);
        mainLayout.addComponent(getUserGroupTablePanel());

        mainLayout.setComponentAlignment(filterButtons, Alignment.BOTTOM_RIGHT);
    }
    return mainLayout;
}

From source file:edu.kit.dama.ui.admin.LandingPageComponent.java

License:Apache License

public final void update(DigitalObject object, boolean privileged) {
    if (object == null) {
        UIUtils7.GridLayoutBuilder builder = new UIUtils7.GridLayoutBuilder(1, 1);
        builder.fill(new Label("Access to digital object not permitted."), 0, 0);
        mainLayout = builder.getLayout();
        mainLayout.setMargin(true);//from w w w . ja  v  a 2s .  c  o m
        mainLayout.setSpacing(true);
        mainLayout.setStyleName("landing");
        HorizontalLayout hLayout = new HorizontalLayout(mainLayout);
        hLayout.setSizeFull();
        hLayout.setComponentAlignment(mainLayout, Alignment.MIDDLE_CENTER);
        setCompositionRoot(hLayout);
    } else {
        final TextField oidField = new TextField();
        Button searchButton = new Button("Search");
        Button metsButton = new Button("METS");
        final Button dcButton = new Button("DublinCore");
        Button dataButton = new Button("Download");
        VerticalLayout metadataDownloadButtons = new VerticalLayout(dcButton, metsButton);
        UIUtils7.GridLayoutBuilder builder = new UIUtils7.GridLayoutBuilder(3, 6);

        StreamResource metsResource = new StreamResource(() -> {
            try {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                MetsBuilder.init(object).createMinimalMetsDocument(UserData.WORLD_USER).write(bout);
                return new ByteArrayInputStream(bout.toByteArray());
            } catch (Exception ex) {
                LOGGER.error("Failed to provide METS document.", ex);
                UIComponentTools.showError(
                        "Failed to initialize METS document for download. Cause: " + ex.getMessage());
                return null;
            }
        }, object.getDigitalObjectIdentifier() + ".mets.xml");

        StreamResource dcResource = new StreamResource(() -> {
            try {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                DublinCoreHelper.writeDublinCoreDocument(object, UserData.WORLD_USER, bout);
                return new ByteArrayInputStream(bout.toByteArray());
            } catch (ParserConfigurationException ex) {
                LOGGER.error("Failed to provide DC document.", ex);
                UIComponentTools
                        .showError("Failed to initialize DC document for download. Cause: " + ex.getMessage());
                return null;
            }
        }, object.getDigitalObjectIdentifier() + ".dc.xml");

        StreamResource dataResource = new StreamResource(() -> {
            IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
            mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
            try {
                IAuthorizationContext ctx = new AuthorizationContext(new UserId(Constants.WORLD_USER_ID),
                        new GroupId(Constants.WORLD_USER_ID), Role.GUEST);
                if (accessGranted(object, ctx) || accessGranted(object, UIHelper.getSessionContext())) {
                    Response response = new PublicDownloadHandler().prepareStream(object);
                    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
                        return (InputStream) response.getEntity();
                    } else {
                        LOGGER.error("Preparation of the public download for object "
                                + object.getDigitalObjectIdentifier() + " returned status "
                                + response.getStatus() + ". Aborting.");
                    }
                }
                throw new IOException("Public access not available.");
            } catch (IOException ex) {
                LOGGER.error(
                        "Failed to provide data stream for object " + object.getDigitalObjectIdentifier() + ".",
                        ex);
                UIComponentTools.showError(
                        "Failed to initialize data stream for public download. Probably, the digital object is not publicly available.");
                return null;
            }
        }, object.getDigitalObjectIdentifier() + ".zip");

        Map<String, String> dcElementMap = new HashMap<>();
        try {
            dcElementMap = DublinCoreHelper.createDublinCoreElementMap(object, UserData.WORLD_USER);
        } catch (ParserConfigurationException ex) {
            LOGGER.error(
                    "Failed to create DC metadata for object with id " + object.getDigitalObjectIdentifier(),
                    ex);
        }
        oidField.setValue(object.getDigitalObjectIdentifier());

        FileDownloader metsDownloader = new FileDownloader(metsResource);
        metsDownloader.extend(metsButton);

        FileDownloader dcDownloader = new FileDownloader(dcResource);
        dcDownloader.extend(dcButton);

        FileDownloader dataDownloader = new FileDownloader(dataResource);
        dataDownloader.extend(dataButton);

        oidField.setSizeFull();
        searchButton.setWidth("128px");

        searchButton.addClickListener((Button.ClickEvent event) -> {
            String oid = oidField.getValue();
            Page.getCurrent().setLocation(
                    URI.create(UIHelper.getWebAppUrl().toString() + "?landing&oid=" + oid).toString());
        });

        dcButton.setWidth("128px");
        metsButton.setWidth("128px");
        dataButton.setWidth("128px");

        metadataDownloadButtons.setComponentAlignment(dcButton, Alignment.TOP_LEFT);
        metadataDownloadButtons.setComponentAlignment(metsButton, Alignment.TOP_LEFT);

        //build layout
        Label oidLabel = new Label("<u>Object Id</u>", ContentMode.HTML);
        builder.fillRow(oidLabel, 0, 0, 1);
        oidLabel.addStyleName("myboldcaption");
        builder.addComponent(oidField, 0, 1, 2, 1).addComponent(searchButton, 2, 1);
        Label dcMetadataLabel = new Label("<u>DC Metadata</u>", ContentMode.HTML);
        builder.fillRow(dcMetadataLabel, 0, 2, 1);
        dcMetadataLabel.addStyleName("myboldcaption");

        Set<Map.Entry<String, String>> entries = dcElementMap.entrySet();

        Table dcTable = new Table();
        dcTable.setPageLength(entries.size() + 1);
        dcTable.addContainerProperty("dc:key", String.class, "-");
        dcTable.addContainerProperty("dc:value", String.class, "-");
        entries.forEach((entry) -> {
            Object newItemId = dcTable.addItem();
            Item row1 = dcTable.getItem(newItemId);
            row1.getItemProperty("dc:key").setValue(entry.getKey());
            row1.getItemProperty("dc:value").setValue(entry.getValue());
        });

        dcTable.setWidth("640px");
        dcTable.addStyleName("myboldcaption");
        builder.addComponent(dcTable, 0, 3, 2, 1);
        builder.addComponent(metadataDownloadButtons, 2, 3, 1, 1);

        builder.fillRow(new Label("<u>Data Access</u>", ContentMode.HTML), 0, 4, 1);
        long bytes = DataOrganizationUtils.getAssociatedDataSize(object.getDigitalObjectId());
        String formatted = AbstractFile.formatSize(bytes);
        Label oidDownloadLabel = new Label(
                object.getDigitalObjectIdentifier() + ".zip (approx. " + formatted + ")");
        oidDownloadLabel.addStyleName("myboldcaption");
        builder.addComponent(oidDownloadLabel, 0, 5, 2, 1);
        builder.addComponent(dataButton, 2, 5, 1, 1);

        mainLayout = builder.getLayout();
        mainLayout.setRowExpandRatio(0, .1f);
        mainLayout.setRowExpandRatio(1, .1f);
        mainLayout.setRowExpandRatio(2, .6f);
        mainLayout.setRowExpandRatio(3, .1f);
        mainLayout.setRowExpandRatio(4, .1f);

        mainLayout.setColumnExpandRatio(0, .1f);
        mainLayout.setColumnExpandRatio(1, .8f);
        mainLayout.setColumnExpandRatio(2, .1f);
    }
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);
    mainLayout.setStyleName("landing");
    HorizontalLayout hLayout = new HorizontalLayout(mainLayout);
    hLayout.setSizeFull();
    hLayout.setComponentAlignment(mainLayout, Alignment.MIDDLE_CENTER);
    setCompositionRoot(hLayout);
}

From source file:edu.kit.dama.ui.admin.wizard.FirstStartWizard.java

License:Apache License

private void buildMainLayout() {
    stepLayout = new VerticalLayout();

    back.setEnabled(false);//  w  ww  .j  ava 2  s .  c  o  m
    stepLayout.addComponent(stepList[currentStep]);
    stepLayout.setComponentAlignment(stepList[currentStep], Alignment.TOP_RIGHT);
    stepLayout.setSpacing(false);
    stepLayout.setMargin(false);
    stepLayout.setWidth("100%");
    stepLayout.setHeight("500px");

    final VerticalLayout stepLabels = new VerticalLayout();
    for (WizardStep step : stepList) {
        Label stepLabel = new Label(step.getStepName());
        stepLabel.setWidth("250px");
        stepLabels.addComponent(stepLabel);
        stepLabels.setComponentAlignment(stepLabel, Alignment.TOP_LEFT);
    }

    //make introduction label bold
    stepLabels.getComponent(0).addStyleName("myboldcaption");

    Label spacer = new Label();
    stepLabels.addComponent(spacer);
    stepLabels.setExpandRatio(spacer, 1.0f);
    stepLabels.setWidth("275px");
    stepLabels.setHeight("550px");
    stepLabels.setSpacing(true);

    UIUtils7.GridLayoutBuilder builder = new UIUtils7.GridLayoutBuilder(2, 2);

    HorizontalLayout buttonLayout = new HorizontalLayout(back, next);
    buttonLayout.setSizeFull();
    buttonLayout.setComponentAlignment(back, Alignment.BOTTOM_RIGHT);
    buttonLayout.setComponentAlignment(next, Alignment.BOTTOM_RIGHT);
    buttonLayout.setExpandRatio(back, 1.0f);

    next.addClickListener((event) -> {
        if ("Go To Login".equals(next.getCaption())) {
            Page.getCurrent().reload();
        } else if ("Finish".equals(next.getCaption())) {
            //do finish
            WizardPersistHelper helper = new WizardPersistHelper();
            if (helper.persist(properties)) {
                UIUtils7.showInformation("Success",
                        "All information have been successfully stored into the database. For details, please refer to the log output above.\n"
                                + "You may now dismiss this message and click 'Go To Login' in order to access the login page.\n"
                                + "From there you can to login using your administrator account or create a personalized user account.",
                        3000);
                back.setVisible(false);
                next.setCaption("Go To Login");
            } else {
                UIUtils7.showError("Failed to store collected information in database.\n"
                        + "Please refer to the log output above.");
            }
            ((WizardSummary) stepList[currentStep]).setSummary(helper.getMessages());
        } else {
            if (currentStep + 1 <= stepList.length - 1) {
                if (stepList[currentStep].validate()) {
                    stepList[currentStep].collectProperties(properties);
                    currentStep++;
                    stepLayout.replaceComponent(stepList[currentStep - 1], stepList[currentStep]);
                    Label currentLabel = (Label) stepLabels.getComponent(currentStep);
                    Label prevLabel = (Label) stepLabels.getComponent(currentStep - 1);
                    currentLabel.addStyleName("myboldcaption");
                    prevLabel.removeStyleName("myboldcaption");

                    if (stepList[currentStep] instanceof WizardSummary) {
                        StringBuilder summary = new StringBuilder();
                        for (WizardStep step : stepList) {
                            summary.append(step.getSummary()).append("\n");
                        }
                        ((WizardSummary) stepList[currentStep]).setSummary(summary.toString());
                    }
                }
            }

            if (currentStep == stepList.length - 1) {
                //finish
                next.setCaption("Finish");
            } else {
                next.setCaption("Next");
            }

            back.setEnabled(true);
        }
    });

    back.addClickListener((event) -> {
        if (currentStep - 1 >= 0) {
            stepList[currentStep].collectProperties(properties);
            currentStep--;
            stepLayout.replaceComponent(stepList[currentStep + 1], stepList[currentStep]);
            Label currentLabel = (Label) stepLabels.getComponent(currentStep);
            Label prevLabel = (Label) stepLabels.getComponent(currentStep + 1);
            currentLabel.addStyleName("myboldcaption");
            prevLabel.removeStyleName("myboldcaption");
        }
        next.setEnabled(true);
        back.setEnabled(currentStep > 0);
        next.setCaption("Next");
    });

    builder.addComponent(stepLabels, Alignment.TOP_LEFT, 0, 0, 1, 2);
    builder.addComponent(stepLayout, Alignment.TOP_LEFT, 1, 0, 1, 1);
    builder.addComponent(buttonLayout, Alignment.BOTTOM_LEFT, 1, 1, 1, 1);

    mainLayout = builder.getLayout();
    mainLayout.setMargin(true);
    mainLayout.setSizeFull();

    // mainLayout.setColumnExpandRatio(0, .3f);
    mainLayout.setColumnExpandRatio(1, 1f);
    mainLayout.setRowExpandRatio(0, .95f);
    mainLayout.setRowExpandRatio(1, .05f);
}

From source file:edu.kit.dama.ui.admin.workflow.DataWorkflowBasePropertiesLayout.java

License:Apache License

public DataWorkflowBasePropertiesLayout() {
    LOGGER.debug("Building " + DEBUG_ID_PREFIX + " ...");

    setId(DEBUG_ID_PREFIX.substring(0, DEBUG_ID_PREFIX.length() - 1));
    setSizeFull();//from  ww  w.  j av  a 2  s  . com
    setMargin(true);
    setSpacing(true);
    setCaption("TASK CONFIGURATION");

    setColumns(4);
    setRows(6);
    //first row
    addComponent(getNameField(), 0, 0);
    addComponent(getVersionField(), 1, 0);
    addComponent(getContactBox(), 2, 0);
    addComponent(getGroupBox(), 3, 0);
    //second row
    addComponent(getApplicationPackageUrlField(), 0, 1, 1, 1);
    addComponent(getApplicationArgumentsField(), 2, 1);
    //addComponent(getCheckBoxesLayout(), 3, 1, 3, 2);
    //add placeholder only
    addComponent(new VerticalLayout(), 3, 1, 3, 2);
    Label l = new Label("* Changing fields with a red border will update the version of the associated task.");
    l.addStyleName("red-text");
    addComponent(l, 0, 2, 2, 2);
    l.setHeight("12px");
    setComponentAlignment(l, Alignment.TOP_CENTER);

    //
    addComponent(getKeywordsField(), 0, 3, 2, 3);
    //
    addComponent(getDescriptionArea(), 0, 4, 2, 5);

    Button addPropertyButton = new Button();
    addPropertyButton.setIcon(new ThemeResource(IconContainer.ADD));
    addPropertyButton.addClickListener((Button.ClickEvent event) -> {
        addPropertyComponent.reset();
        addPropertyComponent.showWindow();
    });

    HorizontalLayout layout = new HorizontalLayout(getEnvironmentPropertiesSelect(), addPropertyButton);
    layout.setComponentAlignment(getEnvironmentPropertiesSelect(), Alignment.TOP_LEFT);
    layout.setComponentAlignment(addPropertyButton, Alignment.BOTTOM_RIGHT);
    layout.setSizeFull();
    layout.setExpandRatio(getEnvironmentPropertiesSelect(), .95f);
    layout.setExpandRatio(addPropertyButton, .05f);
    addComponent(layout, 3, 3, 3, 5);

    //add popup to layout
    addPropertyComponent = new AddEnvironmentPropertyComponent(this);

    //set dummy row height to 0
    setColumnExpandRatio(0, 0.2f);
    setColumnExpandRatio(1, 0.15f);
    setColumnExpandRatio(2, 0.2f);
    setColumnExpandRatio(3, 0.25f);
    setRowExpandRatio(5, 1f);

}

From source file:edu.kit.dama.ui.admin.workflow.ExecutionEnvironmentBasePropertiesLayout.java

License:Apache License

/**
 * Default constructor.//from   www.  j  a v  a2s. com
 */
public ExecutionEnvironmentBasePropertiesLayout() {
    super();

    LOGGER.debug("Building " + DEBUG_ID_PREFIX + " ...");

    setId(DEBUG_ID_PREFIX.substring(0, DEBUG_ID_PREFIX.length() - 1));
    setSizeFull();
    setMargin(true);
    setSpacing(true);

    setColumns(4);
    setRows(6);

    addComponent(getNameField(), 0, 0, 2, 0);
    addComponent(getGroupBox(), 3, 0);
    //
    addComponent(getAccessPointBox(), 0, 1, 2, 1);
    addComponent(getCheckBoxesLayout(), 3, 1);
    //

    addComponent(getAccessPointBasePathField(), 0, 2, 2, 2);
    addComponent(getPathSelectorButton(), 3, 2);
    //
    addComponent(getMaxTasksField(), 0, 3, 2, 3);
    //
    addComponent(getDescriptionArea(), 0, 4, 2, 5);

    //add property selection
    Button addPropertyButton = new Button();
    addPropertyButton.setIcon(new ThemeResource(IconContainer.ADD));
    addPropertyButton.addClickListener(new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            addPropertyComponent.reset();
            addPropertyComponent.showWindow();
        }
    });

    HorizontalLayout layout = new HorizontalLayout(getEnvironmentPropertiesSelect(), addPropertyButton);
    layout.setComponentAlignment(getEnvironmentPropertiesSelect(), Alignment.TOP_LEFT);
    layout.setComponentAlignment(addPropertyButton, Alignment.BOTTOM_RIGHT);
    layout.setSizeFull();
    layout.setExpandRatio(getEnvironmentPropertiesSelect(), .95f);
    layout.setExpandRatio(addPropertyButton, .05f);
    addComponent(layout, 3, 4, 3, 5);

    //add popup to layout
    addPropertyComponent = new AddEnvironmentPropertyComponent(this);

    setComponentAlignment(getPathSelectorButton(), Alignment.BOTTOM_LEFT);
    setColumnExpandRatio(0, 0.2f);
    setColumnExpandRatio(1, 0.2f);
    setColumnExpandRatio(2, 0.2f);
    setColumnExpandRatio(3, 0.2f);
    setRowExpandRatio(5, 1f);
}

From source file:edu.kit.dama.ui.commons.util.PaginationLayout.java

License:Apache License

/**
 * Update the layout. This method is either called internally when scrolling
 * or/*from ww w.ja va  2 s  .  co m*/
 */
public final void update() {
    //remove all components (old result page and navigation)
    removeAllComponents();

    //add current results
    renderPage();

    //build pagination
    int pages = overallEntries / entriesPerPage;
    if (overallEntries % entriesPerPage > 0) {
        pages++;
    }

    final int overallPages = pages;
    HorizontalLayout navigation = new HorizontalLayout();
    //add "JumpToFirstPage" button
    final NativeButton first = new NativeButton();
    first.setIcon(firstIcon);
    if (firstIcon == null) {
        first.setCaption("<<");
    }
    first.setDescription("First Page");
    first.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            currentPage = 0;
            update();
        }
    });
    //add "PreviousPage" button
    final NativeButton prev = new NativeButton();
    prev.setIcon(prevIcon);
    if (prevIcon == null) {
        prev.setCaption("<");
    }
    prev.setDescription("Previous Page");
    prev.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (currentPage > 0) {
                currentPage--;
                update();
            }
        }
    });
    //add "NextPage" button
    final NativeButton next = new NativeButton();
    next.setIcon(nextIcon);
    if (nextIcon == null) {
        next.setCaption(">");
    }
    next.setDescription("Next Page");
    next.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (currentPage + 1 < overallPages) {
                currentPage++;
                update();
            }
        }
    });
    //add "JumpToLastPage" button
    final NativeButton last = new NativeButton();
    last.setIcon(endIcon);
    if (endIcon == null) {
        next.setCaption(">>");
    }
    last.setDescription("Last Page");
    last.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            currentPage = overallPages - 1;
            update();
        }
    });

    //enable/disable buttons depending on the current page
    if (overallPages == 0) {
        first.setEnabled(false);
        prev.setEnabled(false);
        next.setEnabled(false);
        last.setEnabled(false);
    } else {
        first.setEnabled(!(currentPage == 0) || !(overallPages < 2));
        prev.setEnabled(!(currentPage == 0) || !(overallPages < 2));
        next.setEnabled(!(currentPage == overallPages - 1) || !(overallPages < 2));
        last.setEnabled(!(currentPage == overallPages - 1) || !(overallPages < 2));
    }

    //at first, put the page size selection box into the navigation
    final ComboBox entriesPerPageBox = new ComboBox();
    entriesPerPageBox.setItemCaptionPropertyId("name");
    entriesPerPageBox.addContainerProperty("name", String.class, null);
    entriesPerPageBox.addItem(5);
    entriesPerPageBox.getContainerProperty(5, "name").setValue("5 Entries / Page");
    entriesPerPageBox.addItem(10);
    entriesPerPageBox.getContainerProperty(10, "name").setValue("10 Entries / Page");
    entriesPerPageBox.addItem(15);
    entriesPerPageBox.getContainerProperty(15, "name").setValue("15 Entries / Page");
    entriesPerPageBox.addItem(20);
    entriesPerPageBox.getContainerProperty(20, "name").setValue("20 Entries / Page");

    entriesPerPageBox.setValue(entriesPerPage);
    entriesPerPageBox.setNullSelectionAllowed(false);
    entriesPerPageBox.setImmediate(true);

    entriesPerPageBox.addListener(new Property.ValueChangeListener() {
        public void valueChange(ValueChangeEvent event) {
            entriesPerPage = (Integer) entriesPerPageBox.getValue();
            update();
        }
    });

    navigation.addComponent(entriesPerPageBox);

    //filler labels are added to the beginning and to the end to keep the navigation in the middle
    Label leftFiller = new Label();
    leftFiller.setWidth("25px");
    navigation.addComponent(leftFiller);
    navigation.addComponent(first);
    navigation.addComponent(prev);

    //Show max. 10 pages at once for performance and layout reasons.
    //If there are more than 10 pages, "move" the to show 10 pages based on the current page.
    int start = currentPage - 5;
    start = (start < 0) ? 0 : start;
    int end = start + 10;
    end = (end > pages) ? pages : end;

    if (end - start < 10 && pages > 10) {
        start = end - 10;
    }

    if (overallPages == 0) {
        Label noEntryLabel = new Label("<i>No entries</i>", Label.CONTENT_XHTML);
        //noEntryLabel.setWidth("80px");
        noEntryLabel.setSizeUndefined();
        navigation.addComponent(noEntryLabel);
        navigation.setComponentAlignment(noEntryLabel, Alignment.MIDDLE_CENTER);
    }
    //build the actual page entries
    for (int i = start; i < end; i++) {
        if (i == currentPage) {
            //the current page is marked with a special style
            Label pageLink = new Label("<b>" + Integer.toString(i + 1) + "</b>", Label.CONTENT_XHTML);
            pageLink.setStyleName("currentpage");
            pageLink.setWidth("15px");
            navigation.addComponent(pageLink);
            navigation.setComponentAlignment(pageLink, Alignment.MIDDLE_CENTER);
        } else {
            //otherwise normal links are added, click-events are handled via LayoutClickListener 
            Link pageLink = new Link(Integer.toString(i + 1), null);
            navigation.addComponent(pageLink);
            navigation.setComponentAlignment(pageLink, Alignment.MIDDLE_CENTER);
        }
    }
    //add right navigation buttons
    navigation.addComponent(next);
    navigation.addComponent(last);
    //...and fill the remaining space 
    Label rightFiller = new Label();
    navigation.addComponent(rightFiller);
    //  navigation.setExpandRatio(leftFiller, 1.0f);
    navigation.setExpandRatio(rightFiller, 1.0f);
    navigation.setSpacing(true);

    //put everything ot the middle
    navigation.setComponentAlignment(first, Alignment.MIDDLE_CENTER);
    navigation.setComponentAlignment(prev, Alignment.MIDDLE_CENTER);
    navigation.setComponentAlignment(next, Alignment.MIDDLE_CENTER);
    navigation.setComponentAlignment(last, Alignment.MIDDLE_CENTER);

    //add layout click listener to be able to navigate by clicking the single pages
    navigation.addListener(new LayoutEvents.LayoutClickListener() {
        @Override
        public void layoutClick(LayoutEvents.LayoutClickEvent event) {

            // Get the child component which was clicked
            Component child = event.getChildComponent();

            if (child == null) {
                // Not over any child component
            } else {
                // Over a child component
                if (child instanceof Link) {
                    // Over a valid child element
                    currentPage = Integer.parseInt(((Link) child).getCaption()) - 1;
                    update();
                }
            }
        }
    });

    //finalize
    navigation.setWidth("100%");
    navigation.setHeight("25px");

    //add navigation and align it right below the result page
    addComponent(page);
    setExpandRatio(page, 1f);
    if (overallEntries > 0) {
        addComponent(navigation);
        setComponentAlignment(navigation, Alignment.BOTTOM_CENTER);
        setExpandRatio(navigation, .05f);
    }
    requestRepaint();
}

From source file:edu.kit.dama.ui.components.ConfirmationWindow7.java

License:Apache License

/**
 * Builds a customized subwindow <b>ConfirmationWindow</b> that allows the
 * user to confirm his previously requested action.
 *
 * @param pTitle The title of the window.
 * @param pMessage The message shown in the window.
 * @param pOptionType The type of the window (OK or YES_NO) which defines the
 * visible buttons./*from w  w  w  .  j  a  va 2  s . c  o  m*/
 * @param pMessageType The message type (INFORMATION, WARNING, ERROR) which
 * determines the icon. If pMessageType is null, no icon will be shown.
 * @param pListener The listener which receives the result if a button was
 * pressed or the window was closed.
 *
 */
ConfirmationWindow7(String pTitle, String pMessage, OPTION_TYPE pOptionType, MESSAGE_TYPE pMessageType,
        IConfirmationWindowListener7 pListener) {
    this.listener = pListener;
    //basic setup

    //set caption depending on type
    String caption = pTitle;
    if (caption == null) {
        if (pMessageType != null) {
            switch (pMessageType) {
            case QUESTION:
                caption = DEFAULT_TITLE;
                break;
            case INFORMATION:
                caption = "Information";
                break;
            case WARNING:
                caption = "Warning";
                break;
            case ERROR:
                caption = "Error";
                break;
            }
        } else {
            //no type provided...use default title
            caption = DEFAULT_TITLE;
        }
    }

    setCaption(caption);
    setModal(true);
    center();

    // Build line of buttons depending on pOptionType
    HorizontalLayout buttonLine = new HorizontalLayout();
    buttonLine.setSpacing(true);
    buttonLine.setWidth("100%");
    //add spacer
    Label spacer = new Label();
    buttonLine.addComponent(spacer);
    //add buttons
    if (OPTION_TYPE.YES_NO_OPTION.equals(pOptionType)) {
        buttonLine.addComponent(buildYesButton("Yes"));
        buttonLine.addComponent(buildNoButton());
        buttonLine.setComponentAlignment(yesButton, Alignment.MIDDLE_RIGHT);
        buttonLine.setComponentAlignment(noButton, Alignment.MIDDLE_RIGHT);
        //Assign ENTER to the YES button
        yesButton.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
        //Assign ESC to the NO button
        noButton.setClickShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    } else {
        buttonLine.addComponent(buildYesButton("OK"));
        buttonLine.setComponentAlignment(yesButton, Alignment.MIDDLE_RIGHT);
        //Assign ENTER to the OK button
        yesButton.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
        //Assign ESC to close the dialog
        setCloseShortcut(ShortcutAction.KeyCode.ESCAPE, null);
    }

    buttonLine.setExpandRatio(spacer, 1.0f);

    //determine the icon depending on pMessageType
    ThemeResource icon = null;

    if (pMessageType != null) {
        switch (pMessageType) {
        case QUESTION:
            icon = new ThemeResource("img/24x24/question.png");
            break;
        case INFORMATION:
            icon = new ThemeResource("img/24x24/information.png");
            break;
        case WARNING:
            icon = new ThemeResource("img/24x24/warning.png");
            break;
        case ERROR:
            icon = new ThemeResource("img/24x24/forbidden.png");
            break;
        }
    }
    Component iconComponent = new Label();
    if (icon != null) {
        //icon was set, overwrite icon component
        iconComponent = new Image(null, icon);
    }

    //build the message label
    Label message = new Label(pMessage, ContentMode.HTML);
    message.setSizeUndefined();
    //build the main layout
    GridLayout mainLayout = new UIUtils7.GridLayoutBuilder(2, 2)
            .addComponent(iconComponent, Alignment.TOP_LEFT, 0, 0, 1, 1).addComponent(message, 1, 0, 1, 1)
            .addComponent(buttonLine, 0, 1, 2, 1).getLayout();
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);
    mainLayout.setColumnExpandRatio(0, .05f);
    mainLayout.setColumnExpandRatio(1, 1f);
    mainLayout.setRowExpandRatio(0, 1f);
    mainLayout.setRowExpandRatio(1, .05f);
    setContent(mainLayout);

    //add the close listener
    addCloseListener(new CloseListener() {
        @Override
        public void windowClose(CloseEvent e) {
            fireCloseEvents(RESULT.CANCEL);
        }
    });
}

From source file:edu.kit.dama.ui.repo.components.EntryRenderPanel.java

License:Apache License

/**
 * Build the main layout of the representation of one digital object.
 *
 * @param pContext The authorization context used to decide whether special
 * administrative features are available or not.
 *//*from w  w  w .  ja  va 2s  .c om*/
private void buildMainLayout(IAuthorizationContext pContext) {
    //check if the object could be obtained or not, e.g. due to missing permissions. If not, show an error message.
    if (ERROR_PLACEHOLDER.equals(object.getLabel())) {
        Label warnLabel = new Label("<h3>Failed to obtain entry with identifier '"
                + object.getDigitalObjectIdentifier() + "' from database.</h3>", ContentMode.HTML);
        final Button cleanup = new Button("Cleanup");
        cleanup.setDescription("Click to remove object from search index.");
        cleanup.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                cleanup.setEnabled(false);
                new Notification("Information", "Cleanup not implemented, yet.",
                        Notification.Type.TRAY_NOTIFICATION).show(Page.getCurrent());
            }
        });
        if (pContext.getRoleRestriction().atLeast(Role.ADMINISTRATOR)) {
            //show cleanup button
            mainLayout = new HorizontalLayout(warnLabel, cleanup);
        } else {
            //no cleanup available
            mainLayout = new HorizontalLayout(warnLabel);
        }
        mainLayout.setSizeFull();
        return;
    }

    //initialize image field
    typeImage = new Image();
    typeImage.setSizeFull();
    setImage(object);

    //initialize title label/field
    titleField = UIUtils7.factoryTextField(null, "dc:title");
    titleField.addStyleName("basic_title");
    titleLabel = new Label("dc:title");
    titleLabel.setWidth("100%");
    titleLabel.addStyleName("basic_title");

    //initialize creator label
    if (object.getUploader() != null) {
        creatorLabel = new Label(StringUtils.abbreviate(object.getUploader().getFullname(), 100));
        creatorLabel.setEnabled(true);
    } else {
        creatorLabel = new Label("dc:creator");
        creatorLabel.setEnabled(false);
    }
    creatorLabel.setWidth("100%");
    creatorLabel.addStyleName("basic_left");

    //initialize creation label
    if (object.getStartDate() != null) {
        creationLabel = new Label(new SimpleDateFormat().format(object.getStartDate()));
        creationLabel.setEnabled(true);
    } else {
        creationLabel = new Label("dc:date");
        creationLabel.setEnabled(false);
    }

    creationLabel.setWidth("100%");

    //initialize identifier label
    objectIdLabel = new Label(StringUtils.abbreviate(object.getDigitalObjectIdentifier(), 100));
    objectIdLabel.setWidth("100%");
    //initialize description label/area
    descriptionLabel = new Label("dc:description");
    descriptionArea = UIUtils7.factoryTextArea(null, "dc:description");
    descriptionArea.setHeight("50px");
    descriptionLabel.setHeight("50px");
    descriptionLabel.setWidth("100%");

    //action buttons
    downloadButton = new NativeButton("Download");
    downloadButton.setIcon(new ThemeResource("img/32x32/download.png"));
    downloadButton.setStyleName(BaseTheme.BUTTON_LINK);
    downloadButton.setDescription("Download the data of this digital object.");
    downloadButton.setWidth("100%");

    shareButton = new NativeButton("Share");
    shareButton.setIcon(new ThemeResource("img/16x16/share.png"));
    shareButton.setStyleName(BaseTheme.BUTTON_LINK);
    shareButton.setDescription("Share this digital object.");
    Role eligibleRole = Role.GUEST;
    if (parent.getParentUI().isUserLoggedIn()) {
        //obtain role only if a user is logged in and we are not in ingest mode.
        //Otherwise, the dummy context of MyVaadinUI would be used and will cause unwanted access.
        try {
            //Determine eligible role of currently logged in user
            eligibleRole = ResourceServiceLocal.getSingleton().getGrantRole(object.getSecurableResourceId(),
                    parent.getParentUI().getAuthorizationContext().getUserId(),
                    AuthorizationContext.factorySystemContext());
        } catch (EntityNotFoundException | UnauthorizedAccessAttemptException ex) {
            LOGGER.warn("Failed to determine eligable role for context "
                    + parent.getParentUI().getAuthorizationContext() + ". Continue with GUEST permissions.",
                    ex);
        }
    }

    //Update share button depending on role. Only possessing the role MANAGER (being the owner) entitles to share an object. 
    if (eligibleRole.atLeast(Role.MANAGER)) {
        shareButton.setEnabled(true);
        shareButton.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                if (parent != null) {
                    parent.showSharingPopup(object);
                }
            }
        });
    } else {
        shareButton.setEnabled(false);
        shareButton.setDescription("Only the object owner is allowed to change sharing information.");
    }

    editButton = new NativeButton("Edit Metadata");
    editButton.setIcon(new ThemeResource("img/16x16/edit.png"));
    editButton.setStyleName(BaseTheme.BUTTON_LINK);
    editButton.setDescription("Edit this digital object's metadata.");

    //Update edit button depending on role. If the object is shared with or owned by the logged in user, editing will be allowed.
    if (eligibleRole.atLeast(Role.MEMBER)) {
        editButton.setEnabled(true);
        editButton.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                switchEditMode();
            }
        });
    } else {
        editButton.setEnabled(false);
        editButton.setDescription(
                "Only the object owner and users the object is shared with are allowed to change metadata information.");
    }

    starButton = new NativeButton("Favorite");
    starButton.setImmediate(true);
    starButton.setIcon(new ThemeResource("img/16x16/unstarred.png"));
    starButton.setStyleName(BaseTheme.BUTTON_LINK);
    starButton.setDescription("Add/remove digital object to/from favorites.");

    //Update star button depending on role. If the object is shared with or owned by the logged in user, "star'ing" will be allowed.
    if (eligibleRole.atLeast(Role.MEMBER)) {
        starButton.setEnabled(true);
        starButton.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
                mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());

                try {
                    DigitalObjectType favoriteType = mdm
                            .findSingleResult("SELECT t FROM DigitalObjectType t WHERE t.identifier='"
                                    + MyVaadinUI.FAVORITE_TYPE_IDENTIFIER + "' AND t.typeDomain='"
                                    + MyVaadinUI.FAVORITE_TYPE_DOMAIN + "'", DigitalObjectType.class);
                    if (DigitalObjectTypeHelper.isTypeAssignedToObject(object, favoriteType,
                            AuthorizationContext.factorySystemContext())) {
                        //remove favorite status
                        DigitalObjectTypeHelper.removeTypeFromObject(object, favoriteType,
                                AuthorizationContext.factorySystemContext());
                        starButton.setIcon(new ThemeResource("img/16x16/unstarred.png"));
                        new Notification("Information",
                                "Successfully removed favorite tag from object "
                                        + object.getDigitalObjectIdentifier() + ".",
                                Notification.Type.TRAY_NOTIFICATION).show(Page.getCurrent());
                    } else {
                        //assign favorite status
                        DigitalObjectTypeHelper.assignTypeToObject(object, favoriteType,
                                AuthorizationContext.factorySystemContext());
                        starButton.setIcon(new ThemeResource("img/16x16/starred.png"));
                        new Notification("Information",
                                "Successfully added favorite tag to object "
                                        + object.getDigitalObjectIdentifier() + ".",
                                Notification.Type.TRAY_NOTIFICATION).show(Page.getCurrent());
                    }
                } catch (Exception e) {
                    LOGGER.error("Failed to change 'favorite' status of digital object.", e);
                    new Notification("Warning", "Failed to update favorite status.",
                            Notification.Type.WARNING_MESSAGE).show(Page.getCurrent());
                }
            }
        });
    } else {
        starButton.setEnabled(false);
        starButton.setDescription(
                "Only the object owner and users the object is shared with are allowed to change the favorite state.");
    }

    dcLayout = new UIUtils7.GridLayoutBuilder(3, 5).addComponent(titleLabel, 0, 0, 2, 1)
            .addComponent(creationLabel, 2, 0, 1, 1).addComponent(creatorLabel, 0, 1, 3, 1)
            .addComponent(objectIdLabel, 0, 2, 3, 1).fill(descriptionLabel, 0, 3).getLayout();
    dcLayout.setSizeFull();

    Button.ClickListener saveCancelButtonListener = new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (saveEditButton.equals(event.getButton())) {
                //do save
                IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
                mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
                try {
                    String title = titleField.getValue();
                    String description = descriptionArea.getValue();
                    Investigation investigation = object.getInvestigation();
                    boolean wasError = false;
                    if (description != null && description.length() <= 1024 && investigation != null) {
                        if (!description.equals(investigation.getDescription())) {
                            investigation.setDescription(description);
                            //store investigation
                            mdm.save(investigation);
                        }
                    } else {
                        LOGGER.warn(
                                "Failed to commit updated description '{}'. Either length is exceeded or investigation '{}' is null.",
                                description, investigation);
                        wasError = true;
                    }
                    //store object
                    if (title != null && title.length() >= 3 && title.length() <= 255) {
                        if (!title.equals(object.getLabel())) {
                            //store object
                            object.setLabel(title);
                            object = mdm.save(object);
                        }
                    } else {
                        LOGGER.warn("Failed to commit updated title '{}'. Length is invalid (3<=l<=255).",
                                title);
                        wasError = true;
                    }
                    if (wasError) {
                        new Notification("Warning",
                                "Failed to update title and/or description. See logfile for details.",
                                Notification.Type.WARNING_MESSAGE).show(Page.getCurrent());
                    }

                    //As there is not automatic sync between database and search index the entry has to be reindexed at this point in order
                    //to keep both systems consistent. However, changes taking place in between are lost.
                    LOGGER.debug("Object committed to database. Updating index.");
                    ElasticsearchHelper.indexEntry(object);
                } catch (UnauthorizedAccessAttemptException ex) {
                    LOGGER.error("Failed to commit changes.", ex);
                    new Notification("Warning", "Failed to commit changes. See logfile for details.",
                            Notification.Type.WARNING_MESSAGE).show(Page.getCurrent());

                } finally {
                    mdm.close();
                }
            }
            //do cancel/reload and switch back to read-mode
            reset();
            switchEditMode();
        }
    };

    //save/cancel buttons
    saveEditButton = new NativeButton("Commit Update");
    saveEditButton.setIcon(new ThemeResource("img/16x16/save.png"));
    saveEditButton.setStyleName(BaseTheme.BUTTON_LINK);
    saveEditButton.setDescription("Save changes to this digital object's metadata.");
    saveEditButton.addClickListener(saveCancelButtonListener);
    cancelEditButton = new NativeButton("Cancel Update");
    cancelEditButton.setIcon(new ThemeResource("img/16x16/cancel.png"));
    cancelEditButton.setStyleName(BaseTheme.BUTTON_LINK);
    cancelEditButton.setDescription("Withdraw all changes to this digital object's metadata.");
    cancelEditButton.addClickListener(saveCancelButtonListener);

    //default action layout
    Label spacerMiscActionLayout = new Label();
    miscActionLayout = new HorizontalLayout(editButton, shareButton, starButton, spacerMiscActionLayout);
    miscActionLayout.setWidth("100%");
    miscActionLayout.setHeight("18px");
    miscActionLayout.setSpacing(false);
    miscActionLayout.setMargin(false);
    miscActionLayout.setExpandRatio(spacerMiscActionLayout, .9f);

    //edit action layout
    Label spacerEditActionLayout = new Label();
    editActionLayout = new HorizontalLayout(saveEditButton, cancelEditButton, spacerEditActionLayout);
    editActionLayout.setWidth("100%");
    editActionLayout.setHeight("18px");
    editActionLayout.setSpacing(false);
    editActionLayout.setMargin(false);
    editActionLayout.setExpandRatio(spacerEditActionLayout, .9f);

    //divider generation
    Label dividerTop = new Label();
    dividerTop.setHeight("5px");
    dividerTop.addStyleName("horizontal-line");
    dividerTop.setWidth("90%");
    Label dividerBottom = new Label();
    dividerBottom.setHeight("5px");
    dividerBottom.addStyleName("horizontal-line");
    dividerBottom.setWidth("90%");
    Label dividerLeft = new Label();
    dividerLeft.addStyleName("vertical-line");
    dividerLeft.setWidth("5px");
    dividerLeft.setHeight("90%");
    Label dividerRight = new Label();
    dividerRight.addStyleName("vertical-line");
    dividerRight.setWidth("5px");
    dividerRight.setHeight("90%");

    //build content layout
    HorizontalLayout contentLayout = new HorizontalLayout(typeImage, dividerLeft, dcLayout, dividerRight,
            downloadButton);
    contentLayout.setSizeFull();
    contentLayout.setSpacing(true);
    contentLayout.setComponentAlignment(typeImage, Alignment.TOP_RIGHT);
    contentLayout.setComponentAlignment(dividerLeft, Alignment.MIDDLE_CENTER);
    contentLayout.setComponentAlignment(dcLayout, Alignment.MIDDLE_CENTER);
    contentLayout.setComponentAlignment(dividerRight, Alignment.MIDDLE_CENTER);
    contentLayout.setComponentAlignment(downloadButton, Alignment.BOTTOM_CENTER);
    contentLayout.setExpandRatio(typeImage, .1f);
    contentLayout.setExpandRatio(dcLayout, .8f);
    contentLayout.setExpandRatio(downloadButton, .1f);

    //build main layout
    mainLayout = new VerticalLayout(dividerTop, contentLayout, dividerBottom, miscActionLayout);
    mainLayout.setExpandRatio(dividerTop, .05f);
    mainLayout.setComponentAlignment(dividerTop, Alignment.TOP_LEFT);
    mainLayout.setExpandRatio(contentLayout, .80f);
    mainLayout.setExpandRatio(dividerBottom, .05f);
    mainLayout.setComponentAlignment(dividerBottom, Alignment.BOTTOM_RIGHT);
    mainLayout.setExpandRatio(miscActionLayout, .1f);
    mainLayout.setSpacing(true);
    mainLayout.setMargin(true);
    mainLayout.addStyleName("basic");
    mainLayout.setWidth("100%");
    mainLayout.setHeight("185px");
    //do reset to load title and description
    reset();
    LOGGER.debug("Layout successfully build up.");
}

From source file:edu.kit.dama.ui.repo.components.PaginationPanel.java

License:Apache License

/**
 * Build the navigation layout including the appropriate buttons to navigate
 * through the pagination pages./*from   w  w w . j a va 2 s . co m*/
 *
 * @return The navigation layout component.
 */
private HorizontalLayout buildNavigationComponent() {
    HorizontalLayout result = new HorizontalLayout();
    //add "JumpToFirstPage" button
    final NativeButton first = new NativeButton();
    first.setIcon(new ThemeResource("img/16x16/beginning.png"));
    first.setDescription("First Page");
    first.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            currentPage = 0;
            updatePage();
        }
    });
    //add "PreviousPage" button
    final NativeButton prev = new NativeButton();
    prev.setIcon(new ThemeResource("img/16x16/prev.png"));
    prev.setDescription("Previous Page");
    prev.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (currentPage > 0) {
                currentPage--;
                updatePage();
            }
        }
    });
    //add "NextPage" button
    final NativeButton next = new NativeButton();
    next.setDescription("Next Page");
    next.setIcon(new ThemeResource("img/16x16/next.png"));
    next.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (currentPage + 1 < overallPages) {
                currentPage++;
                updatePage();
            }
        }
    });
    //add "JumpToLastPage" button
    final NativeButton last = new NativeButton();
    last.setDescription("Last Page");
    last.setIcon(new ThemeResource("img/16x16/end.png"));
    last.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            currentPage = overallPages - 1;
            updatePage();
        }
    });

    //enable/disable buttons depending on the current page
    if (overallPages == 0) {
        first.setEnabled(false);
        prev.setEnabled(false);
        next.setEnabled(false);
        last.setEnabled(false);
    } else {
        first.setEnabled(!(currentPage == 0) || !(overallPages < 2));
        prev.setEnabled(!(currentPage == 0) || !(overallPages < 2));
        next.setEnabled(!(currentPage == overallPages - 1) || !(overallPages < 2));
        last.setEnabled(!(currentPage == overallPages - 1) || !(overallPages < 2));
    }

    Label leftFiller = new Label();
    result.addComponent(leftFiller);
    result.setExpandRatio(leftFiller, 1.0f);
    result.addComponent(first);
    result.addComponent(prev);
    int start = currentPage - 5;
    start = (start < 0) ? 0 : start;
    int end = start + 10;
    end = (end > overallPages) ? overallPages : end;

    if (end - start < 10 && overallPages > 10) {
        start = end - 10;
    }

    if (overallPages == 0) {
        Label noEntryLabel = new Label("<i>No entries</i>", ContentMode.HTML);
        //noEntryLabel.setWidth("80px");
        noEntryLabel.setSizeUndefined();
        result.addComponent(noEntryLabel);
        result.setComponentAlignment(noEntryLabel, Alignment.MIDDLE_CENTER);
    }
    //build the actual page entries
    for (int i = start; i < end; i++) {
        if (i == currentPage) {
            //the current page is marked with a special style
            Label pageLink = new Label("<b>" + Integer.toString(i + 1) + "</b>", ContentMode.HTML);
            pageLink.setStyleName("currentpage");
            pageLink.setWidth("15px");
            result.addComponent(pageLink);
            result.setComponentAlignment(pageLink, Alignment.MIDDLE_CENTER);
        } else {
            //otherwise normal links are added, click-events are handled via LayoutClickListener 
            Link pageLink = new Link(Integer.toString(i + 1), null);
            result.addComponent(pageLink);
            result.setComponentAlignment(pageLink, Alignment.MIDDLE_CENTER);
        }
    }
    //add right navigation buttons
    result.addComponent(next);
    result.addComponent(last);
    //...and fill the remaining space 
    Label rightFiller = new Label();
    result.addComponent(rightFiller);
    result.setExpandRatio(rightFiller, 1.0f);
    result.setSpacing(true);

    //put everything ot the middle
    result.setComponentAlignment(first, Alignment.MIDDLE_CENTER);
    result.setComponentAlignment(prev, Alignment.MIDDLE_CENTER);
    result.setComponentAlignment(next, Alignment.MIDDLE_CENTER);
    result.setComponentAlignment(last, Alignment.MIDDLE_CENTER);

    //add layout click listener to be able to navigate by clicking the single pages
    result.addLayoutClickListener(new LayoutEvents.LayoutClickListener() {
        @Override
        public void layoutClick(LayoutEvents.LayoutClickEvent event) {

            // Get the child component which was clicked
            Component child = event.getChildComponent();

            if (child == null) {
                // Not over any child component
            } else // Over a child component
            {
                if (child instanceof Link) {
                }
            }
        }
    });

    //finalize
    result.setWidth("100%");
    result.setHeight("25px");
    return result;
}

From source file:edu.nps.moves.mmowgli.AbstractMmowgliControllerHelper.java

License:Open Source License

void handleShowActiveUsersActionTL(MenuBar menubar) {
    Session session = HSess.get();//  w  ww.  jav  a 2  s .c  o m

    Criteria criteria = session.createCriteria(User.class);
    criteria.setProjection(Projections.rowCount());
    criteria.add(Restrictions.eq("accountDisabled", false));
    int totcount = ((Long) criteria.list().get(0)).intValue();

    // new and improved
    int count = Mmowgli2UI.getGlobals().getSessionCount();

    Window countWin = new Window("Display Active User Count");
    countWin.setModal(true);

    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.setWidth("99%");
    countWin.setContent(layout);

    HorizontalLayout hl = new HorizontalLayout();
    hl.setSpacing(true);
    Label lab;
    hl.addComponent(lab = new HtmlLabel("Number of users* (including yourself)<br/>currently playing:"));
    hl.addComponent(lab = new Label());
    lab.setWidth("15px");

    Label countTf = new HtmlLabel();
    countTf.setWidth("50px");
    countTf.setValue("&nbsp;" + count);
    countTf.addStyleName("m-greyborder");
    hl.addComponent(countTf);
    hl.setComponentAlignment(countTf, Alignment.MIDDLE_LEFT);
    layout.addComponent(hl);

    layout.addComponent(new Label("* Count incremented on login, decremented on timeout or logout."));

    hl = new HorizontalLayout();
    hl.setSpacing(true);

    hl.addComponent(lab = new HtmlLabel("Total registered users:"));
    hl.addComponent(lab = new Label());
    lab.setWidth("15px");

    Label totalLab = new HtmlLabel();
    totalLab.setWidth("50px");
    totalLab.setValue("&nbsp;" + totcount);
    totalLab.addStyleName("m-greyborder");
    hl.addComponent(totalLab);
    hl.setComponentAlignment(totalLab, Alignment.MIDDLE_LEFT);
    layout.addComponent(hl);

    countWin.setWidth("325px");
    UI.getCurrent().addWindow(countWin);
    countWin.center();
}