Example usage for com.vaadin.ui Button addStyleName

List of usage examples for com.vaadin.ui Button addStyleName

Introduction

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

Prototype

@Override
    public void addStyleName(String style) 

Source Link

Usage

From source file:facs.components.BookAdmin.java

License:Open Source License

public BookAdmin(User user) {

    Date dNow = new Date();
    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    System.out.println(ft.format(dNow) + "  INFO  Calendar Admin accessed! - User: "
            + LiferayAndVaadinUtils.getUser().getScreenName());

    Label infoLabel = new Label(
            DBManager.getDatabaseInstance().getUserNameByUserID(LiferayAndVaadinUtils.getUser().getScreenName())
                    + "  " + LiferayAndVaadinUtils.getUser().getScreenName());
    infoLabel.addStyleName("h4");

    String buttonRefreshTitle = "Refresh";
    Button refresh = new Button(buttonRefreshTitle);
    refresh.setIcon(FontAwesome.REFRESH);
    refresh.setSizeFull();/*from  w ww .j  av a 2 s  . c om*/
    refresh.setDescription("Click here to reload the data from the database!");
    refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    String buttonUpdateTitle = "Update";
    Button updateUser = new Button(buttonUpdateTitle);
    updateUser.setIcon(FontAwesome.WRENCH);
    updateUser.setSizeFull();
    updateUser.setDescription("Click here to update your user role and group!");

    userDevice = new ListSelect("Select a device");
    userDevice.addItems(DBManager.getDatabaseInstance().getDeviceNames());
    userDevice.setRows(6);
    userDevice.setNullSelectionAllowed(false);
    userDevice.setSizeFull();
    userDevice.setImmediate(true);
    /*
     * userDevice.addValueChangeListener(e -> Notification.show("Device:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userGroup = new ListSelect("Select a user group");
    userGroup.addItems(DBManager.getDatabaseInstance().getUserGroups());
    userGroup.setRows(6);
    userGroup.setNullSelectionAllowed(false);
    userGroup.setSizeFull();
    userGroup.setImmediate(true);
    /*
     * userGroup.addValueChangeListener(e -> Notification.show("User Group:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userRole = new ListSelect("Select a user role");
    userRole.addItems(DBManager.getDatabaseInstance().getUserRoles());
    userRole.setRows(6);
    userRole.setNullSelectionAllowed(false);
    userRole.setSizeFull();
    userRole.setImmediate(true);
    /*
     * userRole.addValueChangeListener(e -> Notification.show("User Role:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    refresh.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();
        }
    });

    updateUser.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496909L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                if (userDevice.getValue().equals(null) || userRole.getValue().equals(null)
                        || userGroup.getValue().equals(null)) {
                    showErrorNotification("Something's missing!",
                            "Please make sure that you selected a Device, a Role and a Group! Each list has to have one highligthed option.'.");
                    // System.out.println("Device: "+userDevice.getValue()+" Group: "+userGroup.getValue()+" Role: "+userRole.getValue());
                } else {
                    DBManager.getDatabaseInstance().getShitDone(
                            DBManager.getDatabaseInstance().getUserRoleIDbyDesc(userRole.getValue().toString()),
                            DBManager.getDatabaseInstance()
                                    .getUserIDbyLDAPID(LiferayAndVaadinUtils.getUser().getScreenName()),
                            DBManager.getDatabaseInstance()
                                    .getDeviceIDByName(userDevice.getValue().toString()));

                    DBManager.getDatabaseInstance().getShitDoneAgain(
                            DBManager.getDatabaseInstance()
                                    .getUserGroupIDByName(userGroup.getValue().toString()),
                            LiferayAndVaadinUtils.getUser().getScreenName());

                }
            } catch (Exception e) {
                showErrorNotification("Something's missing!",
                        "Please make sure that you selected a Device, a Role and a Group! Each list has to have one highligthed option.'.");
            }
            refreshDataSources();
        }
    });

    // only admins are allowed to see the admin panel ;)
    if (!DBManager.getDatabaseInstance()
            .getUserAdminPanelAccessByLDAPId(LiferayAndVaadinUtils.getUser().getScreenName()).equals("1")) {
        VerticalLayout errorLayout = new VerticalLayout();
        infoLabel.setValue("ACCESS DENIED");
        errorLayout.addComponent(infoLabel);
        showErrorNotification("Access Denied!",
                "Sorry, you're not allowed to see anything here, at least your username told us so. Do you need assistance? Please contact 'info@qbic.uni-tuebingen.de'.");
        setCompositionRoot(errorLayout);
        return;
    }

    this.setCaption("Admin");

    final TabSheet bookAdmin = new TabSheet();
    bookAdmin.addStyleName(ValoTheme.TABSHEET_FRAMED);
    bookAdmin.addStyleName(ValoTheme.TABSHEET_EQUAL_WIDTH_TABS);

    ArrayList<String> deviceNames = new ArrayList<String>();
    deviceNames = DBManager.getDatabaseInstance().getDeviceNames();

    bookAdmin.addTab(awaitingRequestsGrid());

    for (int i = 0; i < deviceNames.size(); i++) {
        bookAdmin.addTab(newDeviceGrid(deviceNames.get(i)));
    }

    bookAdmin.addTab(deletedBookingsGrid());

    bookAdmin.addSelectedTabChangeListener(new SelectedTabChangeListener() {

        /**
         * 
         */
        private static final long serialVersionUID = 8987818794404251063L;

        @Override
        public void selectedTabChange(SelectedTabChangeEvent event) {
            userDevice.select(bookAdmin.getSelectedTab().getCaption());
            userRole.select(DBManager.getDatabaseInstance()
                    .getUserGroupDescriptionByLDAPId(LiferayAndVaadinUtils.getUser().getScreenName(), DBManager
                            .getDatabaseInstance().getDeviceIDByName(bookAdmin.getSelectedTab().getCaption())));
            userGroup.select(DBManager.getDatabaseInstance()
                    .getUserRoleNameByLDAPId(LiferayAndVaadinUtils.getUser().getScreenName()));

        }
    });

    gridLayout.setWidth("100%");

    // add components to the grid layout
    // gridLayout.addComponent(infoLabel, 0, 0, 3, 0);
    gridLayout.addComponent(bookAdmin, 0, 1, 5, 1);
    gridLayout.addComponent(refresh, 0, 2);
    gridLayout.addComponent(userDevice, 0, 4, 1, 4);
    gridLayout.addComponent(userRole, 2, 4, 3, 4);
    gridLayout.addComponent(userGroup, 4, 4, 5, 4);
    gridLayout.addComponent(updateUser, 0, 5, 5, 5);
    gridLayout.setSizeFull();

    gridLayout.setSpacing(true);
    setCompositionRoot(gridLayout);

    /*
     * JavaScript to update the Grid try { JDBCConnectionPool connectionPool = new
     * SimpleJDBCConnectionPool("com.mysql.jdbc.Driver",
     * "jdbc:mysql://localhost:8889/facs_facility", "facs", "facs"); QueryDelegate qd = new
     * FreeformQuery("select * from facs_facility", connectionPool, "id"); final SQLContainer c =
     * new SQLContainer(qd); bookAdmin.setContainerDataSource(c); }
     * 
     * JavaScript.getCurrent().execute("setInterval(function(){refreshTable();},5000);");
     * JavaScript.getCurrent().addFunction("refreshTable", new JavaScriptFunction() {
     * 
     * @Override public void call(JsonArray arguments) { // TODO Auto-generated method stub
     * 
     * } });
     */

}

From source file:facs.components.BookAdmin.java

License:Open Source License

private Component deletedBookingsGrid() {
    VerticalLayout devicesLayout = new VerticalLayout();
    devicesLayout.setCaption("Trash");
    // HorizontalLayout buttonLayout = new HorizontalLayout();

    // there will now be space around the test component
    // components added to the test component will now not stick together but have space between
    // them/*from w w  w.  ja v a2 s  .com*/
    devicesLayout.setMargin(true);
    devicesLayout.setSpacing(true);
    // buttonLayout.setMargin(true);
    // buttonLayout.setSpacing(true);

    // buttonLayout.addComponent(add);

    BeanItemContainer<BookingBean> booking = getDeletedBookings();

    GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(booking);

    gpc.addGeneratedProperty("restore", new PropertyValueGenerator<String>() {
        /**
         * 
         */
        private static final long serialVersionUID = 4082425701384202280L;

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            // return FontAwesome.TRASH_O.getHtml(); // The caption
            return "Restore"; // The caption

        }

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

    gpc.addGeneratedProperty("delete", new PropertyValueGenerator<String>() {
        /**
         * 
         */
        private static final long serialVersionUID = 1307493624895857513L;

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            // return FontAwesome.TRASH_O.getHtml(); // The caption
            return "Purge"; // The caption

        }

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

    devicesGridTrash = new Grid(gpc);
    // Create a grid

    devicesGridTrash.setWidth("100%");
    devicesGridTrash.setSelectionMode(SelectionMode.SINGLE);
    devicesGridTrash.getColumn("delete").setRenderer(new HtmlRenderer());
    devicesGridTrash.getColumn("restore").setRenderer(new HtmlRenderer());
    setRenderers(devicesGridTrash);
    devicesGridTrash.setColumnOrder("ID", "deviceName", "service", "start", "end", "username", "phone",
            "price");

    // Render a button that deletes the data row (item)

    /*
     * devicesGrid.addColumn("delete", FontIcon.class).setWidth(35) .setRenderer(new
     * FontIconRenderer(new RendererClickListener() {
     * 
     * @Override public void click(RendererClickEvent e) { Notification.show("Deleted item " +
     * e.getItemId()); } }));
     */

    devicesGridTrash.getColumn("delete")
            .setRenderer(new ButtonRenderer(new ClickableRenderer.RendererClickListener() {
                /**
                 * 
                 */
                private static final long serialVersionUID = 302628105070456680L;

                @Override
                public void click(RendererClickEvent event) {

                    try {

                        Window cd = new Window("Purge Booking");

                        cd.setHeight("200px");
                        cd.setWidth("400px");
                        cd.setResizable(false);

                        GridLayout dialogLayout = new GridLayout(3, 3);

                        Button okButton = new Button("Yes");
                        okButton.addStyleName(ValoTheme.BUTTON_DANGER);
                        Button cancelButton = new Button("No, I'm actually not sure!");
                        cancelButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
                        Label information = new Label("Are you sure you want to purge this item?");
                        information.addStyleName(ValoTheme.LABEL_NO_MARGIN);

                        okButton.addClickListener(new Button.ClickListener() {

                            /**
                             * 
                             */
                            private static final long serialVersionUID = 3739260172118651857L;

                            @Override
                            public void buttonClick(ClickEvent okEvent) {
                                purgeBooking((BookingBean) event.getItemId());
                                cd.close();
                                Notification("The booking was purged!",
                                        "At the end, you are the admin, you have the power.", "");
                            }
                        });

                        cancelButton.addClickListener(new Button.ClickListener() {

                            /**
                             * 
                             */
                            private static final long serialVersionUID = -3931200823633220160L;

                            @Override
                            public void buttonClick(ClickEvent okEvent) {
                                cd.close();
                            }
                        });

                        dialogLayout.addComponent(information, 0, 0, 2, 0);
                        dialogLayout.addComponent(okButton, 0, 1);
                        dialogLayout.addComponent(cancelButton, 1, 1);
                        dialogLayout.setMargin(true);
                        dialogLayout.setSpacing(true);
                        cd.setContent(dialogLayout);
                        cd.center();
                        UI.getCurrent().addWindow(cd);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    FieldGroup fieldGroup = devicesGridTrash.getEditorFieldGroup();
                    fieldGroup.addCommitHandler(new FieldGroup.CommitHandler() {
                        /**
                         * 
                         */
                        private static final long serialVersionUID = 3799806709907688919L;

                        @Override
                        public void preCommit(FieldGroup.CommitEvent commitEvent)
                                throws FieldGroup.CommitException {

                        }

                        @Override
                        public void postCommit(FieldGroup.CommitEvent commitEvent)
                                throws FieldGroup.CommitException {

                            Notification("Successfully Updated",
                                    "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                                    "success");

                            refreshGrid();
                        }

                        private void refreshGrid() {
                            getDeletedBookings();
                        }

                    });

                }
            }));

    devicesGridTrash.getColumn("restore")
            .setRenderer(new ButtonRenderer(new ClickableRenderer.RendererClickListener() {
                /**
                 * 
                 */
                private static final long serialVersionUID = -9104571186503913834L;

                @Override
                public void click(RendererClickEvent event) {
                    restoreBooking((BookingBean) event.getItemId());
                }
            }));

    // devicesGrid.setEditorEnabled(true);

    // devicesLayout.addComponent(buttonLayout);
    devicesLayout.addComponent(devicesGridTrash);

    // TODO filtering
    // HeaderRow filterRow = devicesGrid.prependHeaderRow();

    return devicesLayout;
}

From source file:facs.components.Booking.java

License:Open Source License

public Booking(final BookingModel bookingModel, Date referenceDate) {

    String[] sayHello = { "Kon'nichiwa", "Hello", "Halo", "Hiya", "Hej", "Hallo", "Hola", "Grezi", "Servus",
            "Merhaba", "Bonjour", "Ahoj", "Moi", "Ciao", "Buongiorno" };

    this.bookingModel = bookingModel;
    this.referenceDate = referenceDate;

    Label infoLabel = new Label();
    infoLabel.addStyleName("h4");

    Label selectDeviceLabel = new Label();
    selectDeviceLabel.addStyleName("h4");
    selectDeviceLabel.setValue("Please Select a Device");

    final Label versionLabel = new Label();
    versionLabel.addStyleName("h4");
    versionLabel.setValue("Version 0.1.160727");

    // showSuccessfulNotification(sayHello[(int) (Math.random() * sayHello.length)] + ", "
    // + bookingModel.userName() + "!", "");

    Date dNow = new Date();
    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    System.out.println(ft.format(dNow) + "  INFO  Calendar initiated! - User: " + bookingModel.getLDAP() + " "
            + versionLabel);//from w w w. j  a  v a 2  s  . c o m

    // only users who are allowed to book devices will be able to do so
    if (bookingModel.isNotAllowed()) {
        VerticalLayout errorLayout = new VerticalLayout();
        infoLabel.setValue("ACCESS DENIED");
        errorLayout.addComponent(infoLabel);
        showErrorNotification("Access Denied!",
                "Sorry, you're not allowed to see anything here, at least your username told us so. Do you need assistance? Please contact 'info@qbic.uni-tuebingen.de'.");
        setCompositionRoot(errorLayout);
        return;
    }

    Panel book = new Panel();
    book.addStyleName(ValoTheme.PANEL_BORDERLESS);

    DBManager.getDatabaseInstance();
    db = Database.Instance;
    db.userLogin(bookingModel.getLDAP());
    selectedDevice = initCalendars(bookingModel.getDevicesNames());

    selectedService = new NativeSelect("Please select a service:");
    selectedService.setDescription("Please select the service you would like to receive!");

    selectedKostenstelle = new NativeSelect("Please select konstenstelle:");
    selectedKostenstelle.setDescription("Please select the Kostenstelle you would like to use!");

    selectedDevice.addValueChangeListener(new ValueChangeListener() {
        private static final long serialVersionUID = 8153818693511960689L;

        @Override
        public void valueChange(ValueChangeEvent event) {
            versionLabel.setValue(db.getUserRoleDescByLDAPId(bookingModel.getLDAP(), getCurrentDevice()));

            selectedKostenstelle.setVisible(true);

            if (bookMap.containsKey(getCurrentDevice())) {
                cal.removeAllComponents();
                setCalendar();

                if (selectedDevice.getValue().equals("Aria")) {
                    selectedService.removeAllItems();
                    selectedService.addItems("Full Service", "Partial Service", "Self Service");
                    selectedService.setValue("Full Service");
                    selectedService.setVisible(true);
                } else if (selectedDevice.getValue().equals("Mac")) {
                    selectedService.removeAllItems();
                    selectedService.addItems("Self", "Service");
                    selectedService.setValue("Service");
                    selectedService.setVisible(true);
                } else {
                    selectedService.setValue(null);
                    selectedService.setVisible(false);
                }

            } else {

                bookMap.put(getCurrentDevice(), initCal(bookingModel, getCurrentDevice()));
                cal.removeAllComponents();
                setCalendar();

                if (selectedDevice.getValue().equals("Aria")) {
                    selectedService.removeAllItems();
                    selectedService.addItems("Full Service", "Partial Service", "Self Service");
                    selectedService.setValue("Full Service");
                    selectedService.setVisible(true);
                } else if (selectedDevice.getValue().equals("Mac")) {
                    selectedService.removeAllItems();
                    selectedService.addItems("Self", "Service");
                    selectedService.setValue("Service");
                    selectedService.setVisible(true);
                } else {
                    selectedService.setValue(null);
                    selectedService.setVisible(false);
                }
            }
        }
    });

    if (bookingModel.getProject().isEmpty()) {
        infoLabel.setValue(bookingModel.userName() + "  Kostenstelle: " + bookingModel.getKostenstelle()
                + "  Institute: " + bookingModel.getInstitute());

    } else {
        infoLabel.setValue(bookingModel.userName() + "  Kostenstelle: " + bookingModel.getKostenstelle()
                + "  Project: " + bookingModel.getProject() + "  Institute: "
                + bookingModel.getInstitute());
    }

    // bookDeviceLayout.addComponent(infoLabel);
    cal.setLocale(Locale.getDefault());
    cal.setImmediate(true);
    selectedService.setImmediate(true);
    cal.setSizeFull();

    String submitTitle = "Book";
    Button submit = new Button(submitTitle);
    submit.setIcon(FontAwesome.CALENDAR);
    submit.setDescription("Please select a device and a time frame at first then click 'BOOK'!");
    submit.setSizeFull();

    // submit.setVisible(false);

    submit.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            submit(bookingModel.getLDAP(), getCurrentDevice());
            newEvents.clear();
            refreshDataSources();
        }
    });

    String buttonTitle = "Refresh";
    Button refresh = new Button(buttonTitle);
    refresh.setIcon(FontAwesome.REFRESH);
    refresh.setSizeFull();
    refresh.setDescription("Click here to reload the data from the database!");
    refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    refresh.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {

            refreshDataSources();

        }
    });

    gridLayout.setWidth("100%");
    // add components to the grid layout
    gridLayout.addComponent(infoLabel, 0, 4, 3, 4);
    gridLayout.addComponent(versionLabel, 4, 4, 5, 4);

    // gridLayout.addComponent(selectDeviceLabel,0,1);
    gridLayout.addComponent(selectedDevice, 0, 0);
    gridLayout.addComponent(selectedService, 1, 0);
    gridLayout.addComponent(selectedKostenstelle, 2, 0);
    selectedService.setVisible(false);

    gridLayout.addComponent(cal, 0, 2, 5, 2);

    gridLayout.addComponent(refresh, 0, 3);
    gridLayout.addComponent(submit, 1, 3, 5, 3);

    // gridLayout.addComponent(myBookings(), 0, 5, 5, 5);

    gridLayout.setMargin(true);
    gridLayout.setSpacing(true);
    gridLayout.setSizeFull();

    book.setContent(gridLayout);

    booking = new TabSheet();

    booking.addStyleName(ValoTheme.TABSHEET_FRAMED);
    booking.addTab(book).setCaption("Calendar");
    booking.addTab(myNext24HoursBookings()).setCaption("Next 24 Hours");
    booking.addTab(myUpcomingBookings()).setCaption("Upcoming");
    booking.addTab(myPastBookings()).setCaption("Past Bookings");
    // booking.addTab(myUpcomingBookingsSQLContainer()).setCaption("Test");
    setCompositionRoot(booking);

}

From source file:facs.components.Booking.java

License:Open Source License

private Component myUpcomingBookings() {
    VerticalLayout devicesLayout = new VerticalLayout();
    // devicesLayout.setCaption("My Bookings");
    // there will now be space around the test component
    // components added to the test component will now not stick together but have space between
    // them//from w ww .j a v  a 2  s  .c  o m
    devicesLayout.setMargin(true);
    devicesLayout.setSpacing(true);

    Date serverTime = new WebBrowser().getCurrentDate();
    Date nextDayTime = new Date(serverTime.getTime() + (1000 * 60 * 60 * 24));

    BeanItemContainer<BookingBean> users = getMyUpcomingBookings(bookingModel.getLDAP(), nextDayTime);
    // System.out.println(bookingModel.getLDAP());

    GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(users);
    gpc.addGeneratedProperty("delete", new PropertyValueGenerator<String>() {
        /**
         * 
         */
        private static final long serialVersionUID = 1263377339178640406L;

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            // return FontAwesome.TRASH_O.getHtml(); // The caption
            return "Trash"; // The caption

        }

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

    /*
     * 
     * try {
     * 
     * FreeformQuery query = new FreeformQuery(
     * "SELECT * FROM booking INNER JOIN user ON booking.user_ldap = user.user_ldap WHERE deleted IS NULL AND booking.user_ldap ='"
     * + bookingModel.getLDAP() + "';", DBManager.getDatabaseInstanceAlternative(), "booking_id");
     * SQLContainer container = new SQLContainer(query);
     * 
     * // System.out.println("Print Container: " + container.size());
     * container.setAutoCommit(isEnabled());
     * 
     * myBookings = new Grid(container);
     * 
     * } catch (Exception e) { e.printStackTrace(); }
     * 
     * myBookings.setColumnOrder("booking_id", "confirmation", "device_name", "service", "start",
     * "end", "kostenstelle", "price", "project");
     * 
     * myBookings.removeColumn("user_ldap"); myBookings.removeColumn("timestamp");
     * myBookings.removeColumn("deleted"); myBookings.removeColumn("user_name");
     * myBookings.removeColumn("group_id"); myBookings.removeColumn("workgroup_id");
     * myBookings.removeColumn("email"); myBookings.removeColumn("phone");
     * myBookings.removeColumn("admin_panel"); myBookings.removeColumn("user_id");
     * 
     * myBookings.getColumn("booking_id").setHeaderCaption("Booking ID");
     */

    upcomingBookings = new Grid(gpc);
    // Create a grid
    upcomingBookings.setStyleName("my-style");
    upcomingBookings.setWidth("100%");
    upcomingBookings.setSelectionMode(SelectionMode.SINGLE);
    upcomingBookings.setEditorEnabled(false);

    upcomingBookings.setColumnOrder("ID", "confirmation", "deviceName", "service", "start", "end", "username",
            "phone", "price");
    upcomingBookings.getColumn("price").setHeaderCaption("Approx. Price");

    // System.out.println(myBookings.getColumns());
    setRenderers(upcomingBookings);
    devicesLayout.addComponent(upcomingBookings);

    upcomingBookings.getColumn("delete")
            .setRenderer(new ButtonRenderer(new ClickableRenderer.RendererClickListener() {
                /**
                 * 
                 */
                private static final long serialVersionUID = 302628105070456680L;

                @Override
                public void click(RendererClickEvent event) {

                    try {

                        Window cd = new Window("Delete Booking");

                        cd.setHeight("200px");
                        cd.setWidth("400px");
                        cd.setResizable(false);

                        GridLayout dialogLayout = new GridLayout(3, 3);

                        Button okButton = new Button("Yes");
                        okButton.addStyleName(ValoTheme.BUTTON_DANGER);
                        Button cancelButton = new Button("No, I'm actually not sure!");
                        cancelButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
                        Label information = new Label("Are you sure you want to trash this item?");
                        information.addStyleName(ValoTheme.LABEL_NO_MARGIN);

                        okButton.addClickListener(new Button.ClickListener() {
                            /**
                             * 
                             */
                            private static final long serialVersionUID = 1778157399909757369L;

                            @Override
                            public void buttonClick(ClickEvent okEvent) {

                                purgeBooking((BookingBean) event.getItemId());

                                booking.setSelectedTab(myUpcomingBookings());

                                cd.close();

                                showNotification("The booking was deleted!",
                                        "You wanted to delete an upcoming booking and it wasn't within the next 24 hours. All good, item purged.");
                            }
                        });

                        cancelButton.addClickListener(new Button.ClickListener() {
                            /**
                             * 
                             */
                            private static final long serialVersionUID = -8957620319158438769L;

                            @Override
                            public void buttonClick(ClickEvent okEvent) {
                                cd.close();
                            }
                        });

                        dialogLayout.addComponent(information, 0, 0, 2, 0);
                        dialogLayout.addComponent(okButton, 0, 1);
                        dialogLayout.addComponent(cancelButton, 1, 1);
                        dialogLayout.setMargin(true);
                        dialogLayout.setSpacing(true);
                        cd.setContent(dialogLayout);
                        cd.center();
                        UI.getCurrent().addWindow(cd);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            }));

    // TODO filtering
    // HeaderRow filterRow = devicesGrid.prependHeaderRow();

    return devicesLayout;
}

From source file:facs.components.Statistics.java

License:Open Source License

private Component initialGrid() {

    VerticalLayout gridLayout = new VerticalLayout();

    createInvoice.setEnabled(false);/*from ww  w  .  ja va  2 s  .  com*/
    downloadInvoice.setEnabled(false);

    String buttonRefreshTitle = "Refresh";
    Button refresh = new Button(buttonRefreshTitle);
    refresh.setIcon(FontAwesome.REFRESH);
    refresh.setDescription("Click here to reload the data from the database!");
    refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    refresh.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();

        }
    });

    Date dNow = new Date();
    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    System.out.println(ft.format(dNow) + "  INFO  Statistics accessed! - User: "
            + LiferayAndVaadinUtils.getUser().getScreenName());

    // Add some generated properties
    IndexedContainer container = getEmptyContainer();
    gpcontainer = new GeneratedPropertyContainer(container);

    Grid grid = new Grid(gpcontainer);

    grid.setWidth("100%");
    setRenderers(grid);
    fillRows(grid);

    // compute total costs
    float totalCosts = 0.0f;
    for (Object itemId : gpcontainer.getItemIds())
        totalCosts += ((Number) gpcontainer.getContainerProperty(itemId, costCaption).getValue()).floatValue();

    // compute total time in milliseconds
    long total = 0;
    for (Object itemId : gpcontainer.getItemIds()) {
        long s = ((Date) gpcontainer.getContainerProperty(itemId, startCaption).getValue()).getTime();
        long e = ((Date) gpcontainer.getContainerProperty(itemId, endCaption).getValue()).getTime();
        total += e - s;
    }

    // set footer to contain total cost and time in hours:minutes
    FooterRow footer = grid.appendFooterRow();
    FooterCell footerCellCost = footer.getCell(costCaption);
    footerCellCost.setText(String.format("%1$.2f  total", totalCosts));

    FooterCell footerCellEnd = footer.getCell(endCaption);
    footerCellEnd.setText(Formatter.toHoursAndMinutes(total)); // "%1$.0f hours"

    // Set up a filter for all columns
    HeaderRow filterRow = grid.appendHeaderRow();
    addRowFilter(filterRow, deviceCaption, container, footer, gpcontainer);
    addRowFilter(filterRow, kostenstelleCaption, container, footer, gpcontainer);

    Label infoLabel = new Label(
            DBManager.getDatabaseInstance().getUserNameByUserID(LiferayAndVaadinUtils.getUser().getScreenName())
                    + "  " + LiferayAndVaadinUtils.getUser().getScreenName());
    infoLabel.addStyleName("h4");

    // createInvoice.setSizeFull();
    // downloadInvoice.setSizeFull();

    gridLayout.setWidth("100%");
    gridLayout.setCaption("Statistics");
    // add components to the grid layout
    // gridLayout.addComponent(infoLabel, 0, 0, 3, 0);
    // gridLayout.addComponent(grid, 0, 1, 5, 1);
    // gridLayout.addComponent(createInvoice, 0, 3);
    // gridLayout.addComponent(downloadInvoice, 1, 3);

    gridLayout.addComponent(grid);
    gridLayout.addComponent(refresh);
    gridLayout.addComponent(createInvoice);
    gridLayout.addComponent(downloadInvoice);

    gridLayout.setMargin(true);
    gridLayout.setSpacing(true);

    // grid.setEditorEnabled(true);
    grid.setSelectionMode(SelectionMode.SINGLE);
    grid.addSelectionListener(new SelectionListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -2683274060620429050L;

        @Override
        public void select(SelectionEvent event) {
            // Notification.show("Select row: " + grid.getSelectedRow() + " Name: "
            // + gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption).getValue());
            downloadInvoice.setEnabled(false);
            ReceiverPI = (String) gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption)
                    .getValue();
            createInvoice.setEnabled(true);
        }
    });

    createInvoice.addClickListener(new ClickListener() {

        /**
         * 
         */
        private static final long serialVersionUID = 5512585967145932560L;
        private File bill;
        private FileDownloader fileDownloader;

        @Override
        public void buttonClick(ClickEvent event) {
            String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();

            Paths.get(basepath, "WEB-INF/billingTemplates");

            // System.out.println("Basepath: " + basepath);

            try {

                int setUserId = DBManager.getDatabaseInstance().findUserByFullName(ReceiverPI);

                if (setUserId > 0) {

                    Billing billing = new Billing(Paths.get(basepath, "WEB-INF/billingTemplates").toFile(),
                            "Angebot.tex");

                    UserBean user = setUserId > 0 ? DBManager.getDatabaseInstance().getUserById(setUserId)
                            : null;

                    billing.setReceiverPI(ReceiverPI);
                    billing.setReceiverInstitution(user.getInstitute());
                    billing.setReceiverStreet(user.getStreet());
                    billing.setReceiverPostalCode(user.getPostcode());
                    billing.setReceiverCity(user.getCity());

                    billing.setSenderName("Dr. rer. nat. Stella Autenrieth");
                    billing.setSenderFunction("Leiterin");
                    billing.setSenderPostalCode("72076");
                    billing.setSenderCity("Tbingen");
                    billing.setSenderStreet("Otfried-Mller-Strae 10");
                    billing.setSenderPhone("+49 (0) 7071 29-83156");
                    billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de");
                    billing.setSenderUrl("www.medizin.uni-tuebingen.de");
                    billing.setSenderFaculty("Medizinischen Fakultt");

                    if (user.getKostenstelle() != null)
                        billing.setProjectDescription("Kostenstelle: " + user.getKostenstelle());
                    else
                        billing.setProjectDescription("Keine kostenstelle verfgbar.");

                    billing.setProjectShortDescription("Dieses Angebot beinhaltet jede Menge Extras.");

                    if (user.getProject() != null)
                        billing.setProjectNumber("Kostenstelle: " + user.getKostenstelle());
                    else
                        billing.setProjectNumber("Keine project nummer verfgbar.");

                    float cost = ((Number) gpcontainer.getContainerProperty(grid.getSelectedRow(), costCaption)
                            .getValue()).floatValue();
                    long s = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), startCaption)
                            .getValue()).getTime();
                    long e = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), endCaption)
                            .getValue()).getTime();
                    long timeFrame = e - s;
                    Date start = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), startCaption)
                            .getValue());
                    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy");
                    String date = ft.format(start);
                    String description = "No Description is Available";
                    String time_frame = Formatter.toHoursAndMinutes(timeFrame);

                    ArrayList<CostEntry> entries = new ArrayList<CostEntry>();
                    entries.add(billing.new CostEntry(date, time_frame, description, cost));
                    billing.setCostEntries(entries);
                    float totalCosts = 0.0f;

                    // calculates the total cost of items
                    // for (Object itemId : gpcontainer.getItemIds()) {
                    // totalCosts +=
                    // ((Number) gpcontainer.getContainerProperty(itemId, costCaption).getValue())
                    // .floatValue();
                    // }

                    totalCosts = ((Number) gpcontainer.getContainerProperty(grid.getSelectedRow(), costCaption)
                            .getValue()).floatValue();

                    billing.setTotalCost(String.format("%1$.2f", totalCosts));

                    bill = billing.createPdf();
                    // System.out.println(bill.getAbsolutePath());
                    if (fileDownloader != null)
                        downloadInvoice.removeExtension(fileDownloader);
                    fileDownloader = new FileDownloader(new FileResource(bill));
                    fileDownloader.extend(downloadInvoice);
                    downloadInvoice.setEnabled(true);
                    showSuccessfulNotification("Congratulations!",
                            "Invoice is created and available for download.");
                    downloadInvoice.setEnabled(true);
                } else {
                    createInvoice.setEnabled(false);
                    downloadInvoice.setEnabled(false);
                    showErrorNotification("No such user found!",
                            "An error occured while trying to create the invoice. The common problem occurs to be: this no such user in the database.");
                }
            }

            catch (Exception e) {
                showErrorNotification("What the heck!",
                        "An error occured while trying to create the invoice. The common problem occurs to be: this no such user or it can not run program 'pdflatex'.");
                e.printStackTrace();
            }

            // for all entries
            /*
             * try { Billing billing = new Billing(Paths.get(basepath,
             * "WEB-INF/billingTemplates").toFile(), "Angebot.tex");
             * billing.setRecieverInstitution("BER - Berliner Flughafen");
             * billing.setRecieverPI("Klaus Something");
             * billing.setRecieverStreet("am berliner flughafen 12");
             * billing.setRecieverPostalCode("D-12345"); billing.setRecieverCity("Berlin");
             * 
             * billing.setSenderName("Dr. rer. nat. Stella Autenrieth");
             * billing.setSenderFunction("Leiterin"); billing.setSenderPostalCode("72076");
             * billing.setSenderCity("Tbingen"); billing.setSenderStreet("Otfried-Mller-Strae 10");
             * billing.setSenderPhone("+49 (0) 7071 29-83156");
             * billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de");
             * billing.setSenderUrl("www.medizin.uni-tuebingen.de");
             * billing.setSenderFaculty("Medizinischen Fakultt");
             * 
             * billing.setProjectDescription("Dieses Angebot beinhaltet jede Menge Extras.");
             * billing.setProjectShortDescription("jede Menge Extras.");
             * billing.setProjectNumber("QA2014016");
             * 
             * ArrayList<CostEntry> entries = new ArrayList<CostEntry>(); for (Object itemId :
             * gpcontainer.getItemIds()) { float cost = ((Number)
             * gpcontainer.getContainerProperty(itemId, costCaption).getValue()) .floatValue(); long s =
             * ((Date) gpcontainer.getContainerProperty(itemId, startCaption).getValue()) .getTime();
             * long e = ((Date) gpcontainer.getContainerProperty(itemId,
             * endCaption).getValue()).getTime(); long timeFrame = e - s; Date start = ((Date)
             * gpcontainer.getContainerProperty(itemId, startCaption).getValue()); SimpleDateFormat ft =
             * new SimpleDateFormat("dd.MM.yyyy"); String date = ft.format(start); String description =
             * "No Description is Available"; String time_frame =
             * Formatter.toHoursAndMinutes(timeFrame); entries.add(billing.new CostEntry(date,
             * time_frame, description, cost)); } billing.setCostEntries(entries); float totalCosts =
             * 0.0f; for (Object itemId : gpcontainer.getItemIds()) { totalCosts += ((Number)
             * gpcontainer.getContainerProperty(itemId, costCaption).getValue()) .floatValue(); }
             * 
             * billing.setTotalCost(String.format("%1$.2f", totalCosts));
             * 
             * bill = billing.createPdf(); System.out.println(bill.getAbsolutePath()); if
             * (fileDownloader != null) downloadBill.removeExtension(fileDownloader); fileDownloader =
             * new FileDownloader(new FileResource(bill)); fileDownloader.extend(downloadBill);
             * downloadBill.setEnabled(true); showSuccessfulNotification("Congratulations!",
             * "Invoice is created and available for download."); } catch (Exception e) {
             * showErrorNotification( "What the heck!",
             * "An error occured while trying to create the invoice. The common problem occurs to be: cannot run program 'pdflatex'"
             * ); e.printStackTrace(); }
             */

        }

    });

    return gridLayout;

}

From source file:facs.components.Statistics.java

License:Open Source License

private Component newMatchedGrid() {

    Button createInvoiceMatched = new Button("Create Invoice");
    Button downloadInvoiceMatched = new Button("Download Invoice");

    String buttonRefreshTitle = "Refresh";
    Button refreshMatched = new Button(buttonRefreshTitle);
    refreshMatched.setIcon(FontAwesome.REFRESH);
    refreshMatched.setDescription("Click here to reload the data from the database!");
    refreshMatched.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    createInvoiceMatched.setEnabled(false);
    downloadInvoiceMatched.setEnabled(false);

    Grid matchedGrid;/*from  www .java2  s .c  om*/

    refreshMatched.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();

        }
    });

    IndexedContainer mcontainer = getEmptyContainer();

    GeneratedPropertyContainer mpc = new GeneratedPropertyContainer(mcontainer);

    VerticalLayout matchedLayout = new VerticalLayout();

    matchedGrid = new Grid(mpc);

    setRenderers(matchedGrid);
    fillMatchedRows(matchedGrid);

    // compute total costs
    float totalCosts = 0.0f;
    for (Object itemId : mpc.getItemIds())
        totalCosts += ((Number) mpc.getContainerProperty(itemId, costCaption).getValue()).floatValue();

    // compute total time in milliseconds
    long total = 0;
    for (Object itemId : mpc.getItemIds()) {
        long s = ((Date) mpc.getContainerProperty(itemId, startCaption).getValue()).getTime();
        long e = ((Date) mpc.getContainerProperty(itemId, endCaption).getValue()).getTime();
        total += e - s;
    }

    // set footer to contain total cost and time in hours:minutes
    FooterRow footer = matchedGrid.appendFooterRow();
    FooterCell footerCellCost = footer.getCell(costCaption);
    footerCellCost.setText(String.format("%1$.2f  total", totalCosts));

    FooterCell footerCellEnd = footer.getCell(endCaption);
    footerCellEnd.setText(Formatter.toHoursAndMinutes(total)); // "%1$.0f hours"

    // Set up a filter for all columns
    HeaderRow filterRow = matchedGrid.appendHeaderRow();
    addRowFilter(filterRow, deviceCaption, mcontainer, footer, mpc);
    addRowFilter(filterRow, kostenstelleCaption, mcontainer, footer, mpc);

    matchedLayout.setMargin(true);
    matchedLayout.setSpacing(true);

    // devicesGrid.setWidth("100%");
    matchedGrid.setSizeFull();
    matchedGrid.setSelectionMode(SelectionMode.SINGLE);
    matchedLayout.addComponent(matchedGrid);

    matchedGrid.setSelectionMode(SelectionMode.SINGLE);
    matchedGrid.addSelectionListener(new SelectionListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -2683274060620429050L;

        @Override
        public void select(SelectionEvent event) {
            // Notification.show("Select row: " + grid.getSelectedRow() + " Name: "
            // + gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption).getValue());
            downloadInvoiceMatched.setEnabled(false);
            ReceiverPI = (String) mpc.getContainerProperty(matchedGrid.getSelectedRow(), nameCaption)
                    .getValue();
            createInvoiceMatched.setEnabled(true);
        }
    });
    createInvoiceMatched.addClickListener(new ClickListener() {

        private File bill;
        private FileDownloader fileDownloader;

        @Override
        public void buttonClick(ClickEvent event) {
            String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();

            Paths.get(basepath, "WEB-INF/billingTemplates");

            // System.out.println("Basepath: " + basepath);

            try {

                int setUserId = DBManager.getDatabaseInstance().findUserByFullName(ReceiverPI);

                if (setUserId > 0) {

                    Billing billing = new Billing(Paths.get(basepath, "WEB-INF/billingTemplates").toFile(),
                            "Angebot.tex");

                    UserBean user = setUserId > 0 ? DBManager.getDatabaseInstance().getUserById(setUserId)
                            : null;

                    billing.setReceiverPI(ReceiverPI);
                    billing.setReceiverInstitution(user.getInstitute());
                    billing.setReceiverStreet(user.getStreet());
                    billing.setReceiverPostalCode(user.getPostcode());
                    billing.setReceiverCity(user.getCity());

                    billing.setSenderName("Dr. rer. nat. Stella Autenrieth");
                    billing.setSenderFunction("Leiterin");
                    billing.setSenderPostalCode("72076");
                    billing.setSenderCity("Tbingen");
                    billing.setSenderStreet("Otfried-Mller-Strae 10");
                    billing.setSenderPhone("+49 (0) 7071 29-83156");
                    billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de");
                    billing.setSenderUrl("www.medizin.uni-tuebingen.de");
                    billing.setSenderFaculty("Medizinischen Fakultt");

                    if (user.getKostenstelle() != null)
                        billing.setProjectDescription("Kostenstelle: " + user.getKostenstelle());
                    else
                        billing.setProjectDescription("Keine kostenstelle verfgbar.");

                    billing.setProjectShortDescription("Dieses Angebot beinhaltet jede Menge Extras.");

                    if (user.getProject() != null)
                        billing.setProjectNumber("Kostenstelle: " + user.getKostenstelle());
                    else
                        billing.setProjectNumber("Keine project nummer verfgbar.");

                    float cost = ((Number) mpc.getContainerProperty(matchedGrid.getSelectedRow(), costCaption)
                            .getValue()).floatValue();
                    long s = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), startCaption)
                            .getValue()).getTime();
                    long e = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), endCaption)
                            .getValue()).getTime();
                    long timeFrame = e - s;
                    Date start = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), startCaption)
                            .getValue());
                    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy");
                    String date = ft.format(start);
                    String description = "No Description is Available";
                    String time_frame = Formatter.toHoursAndMinutes(timeFrame);

                    ArrayList<CostEntry> entries = new ArrayList<CostEntry>();
                    entries.add(billing.new CostEntry(date, time_frame, description, cost));
                    billing.setCostEntries(entries);

                    float totalCosts = 0.0f;

                    totalCosts = ((Number) mpc.getContainerProperty(matchedGrid.getSelectedRow(), costCaption)
                            .getValue()).floatValue();

                    billing.setTotalCost(String.format("%1$.2f", totalCosts));

                    bill = billing.createPdf();
                    // System.out.println(bill.getAbsolutePath());
                    if (fileDownloader != null)
                        downloadInvoiceMatched.removeExtension(fileDownloader);
                    fileDownloader = new FileDownloader(new FileResource(bill));
                    fileDownloader.extend(downloadInvoiceMatched);
                    downloadInvoiceMatched.setEnabled(true);
                    showSuccessfulNotification("Congratulations!",
                            "Invoice is created and available for download.");
                    downloadInvoiceMatched.setEnabled(true);
                } else {
                    createInvoiceMatched.setEnabled(false);
                    downloadInvoiceMatched.setEnabled(false);
                    showErrorNotification("No such user found!",
                            "An error occured while trying to create the invoice. The common problem occurs to be: this no such user in the database.");
                }
            }

            catch (Exception e) {
                showErrorNotification("What the heck!",
                        "An error occured while trying to create the invoice. The common problem occurs to be: this no such user or it can not run program 'pdflatex'.");
                e.printStackTrace();
            }

        }

    });

    matchedLayout.addComponent(refreshMatched);
    matchedLayout.addComponent(createInvoiceMatched);
    matchedLayout.addComponent(downloadInvoiceMatched);

    return matchedLayout;
}

From source file:facs.components.UserAdmin.java

License:Open Source License

public UserAdmin(User user) {

    Date dNow = new Date();
    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    System.out.println(ft.format(dNow) + "  INFO  Calendar User Manager accessed! - User: "
            + LiferayAndVaadinUtils.getUser().getScreenName());

    Label infoLabel = new Label(
            DBManager.getDatabaseInstance().getUserNameByUserID(LiferayAndVaadinUtils.getUser().getScreenName())
                    + "  " + LiferayAndVaadinUtils.getUser().getScreenName());
    infoLabel.addStyleName("h4");

    CheckBox isAdmin = new CheckBox("user has admin panel access");
    isAdmin.setEnabled(false);//from   ww w . j a v a2 s . c o  m

    String buttonGroupUpdateTitle = "Edit Group";
    Button updateUserGroup = new Button(buttonGroupUpdateTitle);
    updateUserGroup.setIcon(FontAwesome.EDIT);
    updateUserGroup.setSizeFull();
    updateUserGroup.setDescription("Click here to update the group of the user!");

    String buttonWorkgroupUpdateTitle = "Edit Workgroup";
    Button updateUserWorkgroup = new Button(buttonWorkgroupUpdateTitle);
    updateUserWorkgroup.setIcon(FontAwesome.EDIT);
    updateUserWorkgroup.setSizeFull();
    updateUserWorkgroup.setDescription("Click here to update the workgroup of the user!");

    String buttonUpdateTitle = "Update (user role & group for device)";
    Button updateUserRightsAndRoles = new Button(buttonUpdateTitle);
    updateUserRightsAndRoles.setIcon(FontAwesome.WRENCH);
    updateUserRightsAndRoles.setSizeFull();
    updateUserRightsAndRoles.setDescription("Click here to update the user's role and group for a device!");

    String buttonTitle = "Refresh";
    Button refresh = new Button(buttonTitle);
    refresh.setIcon(FontAwesome.REFRESH);
    refresh.setSizeFull();
    refresh.setDescription("Click here to reload the data from the database!");
    refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    // String buttonTitleSave = "Save";
    // Button save = new Button(buttonTitleSave);
    // save.setIcon(FontAwesome.SAVE);
    // save.setSizeFull();
    // save.setDescription("Click here to save all changes!");
    // save.addStyleName(ValoTheme.BUTTON_BORDERLESS);

    userDevice = new ListSelect("Devices");
    userDevice.addItems(DBManager.getDatabaseInstance().getDeviceNames());
    userDevice.setRows(6);
    userDevice.setNullSelectionAllowed(false);
    userDevice.setSizeFull();
    userDevice.setImmediate(true);
    /*
     * userDevice.addValueChangeListener(e -> Notification.show("Device:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userGroup = new ListSelect("User Groups");
    userGroup.addItems(DBManager.getDatabaseInstance().getUserGroups());
    userGroup.addItem("N/A");
    userGroup.setRows(6);
    userGroup.setNullSelectionAllowed(false);
    userGroup.setSizeFull();
    userGroup.setImmediate(true);
    /*
     * userGroup.addValueChangeListener(e -> Notification.show("User Group:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userRole = new ListSelect("User Roles");
    userRole.addItems(DBManager.getDatabaseInstance().getUserRoles());
    userRole.addItem("N/A");
    userRole.setRows(6);
    userRole.setNullSelectionAllowed(false);
    userRole.setSizeFull();
    userRole.setImmediate(true);
    /*
     * userRole.addValueChangeListener(e -> Notification.show("User Role:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userWorkgroup = new ListSelect("Workgroups");
    userWorkgroup.addItems(DBManager.getDatabaseInstance().getUserWorkgroups());
    userWorkgroup.setRows(6);
    userWorkgroup.setNullSelectionAllowed(false);
    userWorkgroup.setSizeFull();
    userWorkgroup.setImmediate(true);
    /*
     * userRole.addValueChangeListener(e -> Notification.show("User Role:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */

    Button updateUser = new Button(buttonTitle);
    updateUser.setIcon(FontAwesome.WRENCH);
    updateUser.setDescription("Click here to update your user role and group!");

    refresh.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();
        }
    });

    updateUser.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496909L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();
        }
    });

    updateUserWorkgroup.addClickListener(new ClickListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -295434651623561492L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userWorkgroup.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user and workgroup! Make sure they are highligthed.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserWorkgroup(
                            DBManager.getDatabaseInstance()
                                    .getUserGroupIDByName(userWorkgroup.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserLDAPIDbyID(selectedRow.toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(), "Admin edited Workgroup");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user and workgroup! Make sure they are highligthed.",
                        "error");
            }
            refreshDataSources();
        }
    });

    updateUserGroup.addClickListener(new ClickListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -5539382755814626288L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userWorkgroup.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user and group! Make sure they are highligthed.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserGroup(
                            DBManager.getDatabaseInstance()
                                    .getUserGroupIDByName(userGroup.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserIDbyLDAPID(selectedRow.toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(), "Admin edited User Group");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user and group! Make sure they are highligthed.",
                        "error");
            }
            refreshDataSources();
        }
    });

    updateUserRightsAndRoles.addClickListener(new ClickListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -295434651623561492L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userDevice.getValue().equals(null)
                        || userRole.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user, device and role! Each list has to have one highligthed option.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserRoleForDevice(
                            DBManager.getDatabaseInstance().getUserRoleIDbyDesc(userRole.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserIDbyLDAPID(
                                    DBManager.getDatabaseInstance().getUserLDAPIDbyID(selectedRow.toString())),
                            DBManager.getDatabaseInstance()
                                    .getDeviceIDByName(userDevice.getValue().toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(),
                            "Admin edited Device, Role, Group");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user, device and role! Each list has to have one highligthed option.",
                        "error");
            }
            refreshDataSources();
        }
    });

    try {
        TableQuery tq = new TableQuery("user", DBManager.getDatabaseInstanceAlternative());
        tq.setVersionColumn("OPTLOCK");
        SQLContainer container = new SQLContainer(tq);

        // System.out.println("Print Container: " + container.size());
        container.setAutoCommit(isEnabled());

        usersGrid = new Grid(container);

        FieldGroup fieldGroup = usersGrid.getEditorFieldGroup();
        fieldGroup.addCommitHandler(new FieldGroup.CommitHandler() {
            /**
             * 
             */
            private static final long serialVersionUID = 3799806709907688919L;

            @Override
            public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {

            }

            @Override
            public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {

                Notification("Successfully Updated",
                        "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                        "success");

                refreshGrid();
            }

            private void refreshGrid() {
                container.refresh();
            }

        });

        usersGrid.addSelectionListener(selectionEvent -> { // Java 8
            // Get selection from the selection model
            Object selected = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

            if (selected != null) {

                // userDevice.select(bookAdmin.getSelectedTab().getCaption());
                userWorkgroup.select(DBManager.getDatabaseInstance().getUserWorkgroupByUserId(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));
                userGroup.select(DBManager.getDatabaseInstance().getUserRoleByUserId(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));

                userDevice.addValueChangeListener(new ValueChangeListener() {

                    /**
                     * 
                     */
                    private static final long serialVersionUID = -8696555155016720475L;

                    @Override
                    public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
                        userRole.select(
                                DBManager.getDatabaseInstance().getUserGroupDescriptionByUserID(
                                        usersGrid.getContainerDataSource().getItem(selected)
                                                .getItemProperty("user_id").toString(),
                                        userDevice.getValue().toString()));

                    }
                });

                isAdmin.setValue(DBManager.getDatabaseInstance().hasAdminPanelAccess(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));

                Notification.show("Selected "
                        + usersGrid.getContainerDataSource().getItem(selected).getItemProperty("user_id"));
            } else
                Notification.show("Nothing selected");
        });

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Notification("Something went wrong!",
                "Unable to update/connect the database. There may be a connection problem, please check your internet connection settings then try it again.",
                "error");
        e.printStackTrace();
    }

    /*
     * // only admins are allowed to see the admin panel ;) if (!DBManager.getDatabaseInstance()
     * .getUserAdminPanelAccessByLDAPId(LiferayAndVaadinUtils.getUser().getScreenName())
     * .equals("1")) { VerticalLayout errorLayout = new VerticalLayout();
     * infoLabel.setValue("ACCESS DENIED"); errorLayout.addComponent(infoLabel);
     * showErrorNotification( "Access Denied!",
     * "Sorry, you're not allowed to see anything here, at least your username told us so. Do you need assistance? Please contact 'info@qbic.uni-tuebingen.de'."
     * ); setCompositionRoot(errorLayout); return; }
     */

    this.setCaption("User Manager");

    final TabSheet userAdmin = new TabSheet();
    userAdmin.addStyleName(ValoTheme.TABSHEET_FRAMED);
    userAdmin.addTab(usersGrid());
    /*
     * userAdmin.addSelectedTabChangeListener(new SelectedTabChangeListener() {
     * 
     * @Override public void selectedTabChange(SelectedTabChangeEvent event) {
     * 
     * } });
     */

    gridLayout.setWidth("100%");

    // add components to the grid layout
    // gridLayout.addComponent(infoLabel, 0, 0, 3, 0);
    gridLayout.addComponent(userAdmin, 0, 1, 5, 1);
    gridLayout.addComponent(refresh, 0, 2);
    gridLayout.addComponent(isAdmin, 5, 2);
    // gridLayout.addComponent(save);

    gridLayout.addComponent(userWorkgroup, 0, 4);
    gridLayout.addComponent(userDevice, 1, 4);
    gridLayout.addComponent(userRole, 2, 4, 4, 4);
    gridLayout.addComponent(userGroup, 5, 4);
    gridLayout.addComponent(updateUserWorkgroup, 0, 5);
    gridLayout.addComponent(updateUserRightsAndRoles, 1, 5, 4, 5);
    gridLayout.addComponent(updateUserGroup, 5, 5);
    // gridLayout.addComponent(newContainerGrid, 1, 4);

    gridLayout.setSpacing(true);
    gridLayout.setSizeFull();
    setCompositionRoot(gridLayout);

}

From source file:fi.semantum.strategia.Utils.java

License:Open Source License

public static void manage(final Main main) {

    final Database database = main.getDatabase();

    VerticalLayout content = new VerticalLayout();
    content.setSizeFull();/*from   ww w.  j  av  a2s . c  o m*/
    content.setSpacing(true);

    HorizontalLayout hl1 = new HorizontalLayout();
    hl1.setSpacing(true);
    hl1.setWidth("100%");

    final ComboBox users = new ComboBox();
    users.setWidth("100%");
    users.setNullSelectionAllowed(false);
    users.addStyleName(ValoTheme.COMBOBOX_SMALL);
    users.setCaption("Valitse kyttj:");

    final Map<String, Account> accountMap = new HashMap<String, Account>();
    makeAccountCombo(main, accountMap, users);

    for (Account a : Account.enumerate(database)) {
        accountMap.put(a.getId(database), a);
        users.addItem(a.getId(database));
        users.select(a.getId(database));
    }

    final Table table = new Table();
    table.setSelectable(true);
    table.setMultiSelect(true);
    table.addStyleName(ValoTheme.TABLE_SMALL);
    table.addStyleName(ValoTheme.TABLE_SMALL);
    table.addStyleName(ValoTheme.TABLE_COMPACT);

    users.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 5036991262418844060L;

        @Override
        public void valueChange(ValueChangeEvent event) {
            users.removeValueChangeListener(this);
            makeAccountCombo(main, accountMap, users);
            makeAccountTable(database, users, accountMap, table);
            users.addValueChangeListener(this);
        }

    });

    final TextField tf = new TextField();

    Validator nameValidator = new Validator() {

        private static final long serialVersionUID = -4779239111120669168L;

        @Override
        public void validate(Object value) throws InvalidValueException {
            String s = (String) value;
            if (s.isEmpty())
                throw new InvalidValueException("Nimi ei saa olla tyhj");
            if (accountMap.containsKey(s))
                throw new InvalidValueException("Nimi on jo kytss");
        }

    };

    final Button save = new Button("Luo", new Button.ClickListener() {

        private static final long serialVersionUID = -6053708137324681886L;

        public void buttonClick(ClickEvent event) {

            if (!tf.isValid())
                return;

            String pass = Long.toString(Math.abs(UUID.randomUUID().getLeastSignificantBits()), 36);
            Account.create(database, tf.getValue(), "", Utils.hash(pass));

            Updates.update(main, true);

            makeAccountCombo(main, accountMap, users);
            makeAccountTable(database, users, accountMap, table);

            Dialogs.infoDialog(main, "Uusi kyttj '" + tf.getValue() + "' luotu",
                    "Kyttjn salasana on " + pass + "", null);

        }

    });
    save.addStyleName(ValoTheme.BUTTON_SMALL);

    final Button remove = new Button("Poista", new Button.ClickListener() {

        private static final long serialVersionUID = -5359199320445328801L;

        public void buttonClick(ClickEvent event) {

            Object selection = users.getValue();
            Account state = accountMap.get(selection);

            // System cannot be removed
            if ("System".equals(state.getId(database)))
                return;

            state.remove(database);

            Updates.update(main, true);

            makeAccountCombo(main, accountMap, users);
            makeAccountTable(database, users, accountMap, table);

        }

    });
    remove.addStyleName(ValoTheme.BUTTON_SMALL);

    tf.setWidth("100%");
    tf.addStyleName(ValoTheme.TEXTFIELD_SMALL);
    tf.setCaption("Luo uusi kyttj nimell:");
    tf.setValue(findFreshUserName(nameValidator));
    tf.setCursorPosition(tf.getValue().length());
    tf.setValidationVisible(true);
    tf.setInvalidCommitted(true);
    tf.setImmediate(true);
    tf.addTextChangeListener(new TextChangeListener() {

        private static final long serialVersionUID = -8274588731607481635L;

        @Override
        public void textChange(TextChangeEvent event) {
            tf.setValue(event.getText());
            try {
                tf.validate();
            } catch (InvalidValueException e) {
                save.setEnabled(false);
                return;
            }
            save.setEnabled(true);
        }

    });
    tf.addValidator(nameValidator);
    if (!tf.isValid())
        save.setEnabled(false);

    hl1.addComponent(users);
    hl1.setExpandRatio(users, 1.0f);
    hl1.setComponentAlignment(users, Alignment.BOTTOM_CENTER);

    hl1.addComponent(tf);
    hl1.setExpandRatio(tf, 1.0f);
    hl1.setComponentAlignment(tf, Alignment.BOTTOM_CENTER);

    hl1.addComponent(save);
    hl1.setExpandRatio(save, 0.0f);
    hl1.setComponentAlignment(save, Alignment.BOTTOM_CENTER);

    hl1.addComponent(remove);
    hl1.setExpandRatio(remove, 0.0f);
    hl1.setComponentAlignment(remove, Alignment.BOTTOM_CENTER);

    content.addComponent(hl1);
    content.setExpandRatio(hl1, 0.0f);

    table.addContainerProperty("Kartta", String.class, null);
    table.addContainerProperty("Oikeus", String.class, null);
    table.addContainerProperty("Laajuus", String.class, null);

    table.setWidth("100%");
    table.setHeight("100%");
    table.setNullSelectionAllowed(true);
    table.setMultiSelect(true);
    table.setCaption("Kyttjn oikeudet");

    makeAccountTable(database, users, accountMap, table);

    content.addComponent(table);
    content.setExpandRatio(table, 1.0f);

    final Button removeRights = new Button("Poista valitut rivit", new Button.ClickListener() {

        private static final long serialVersionUID = 4699670345358079045L;

        public void buttonClick(ClickEvent event) {

            Object user = users.getValue();
            Account state = accountMap.get(user);

            Object selection = table.getValue();
            Collection<?> sel = (Collection<?>) selection;

            List<Right> toRemove = new ArrayList<Right>();

            for (Object s : sel) {
                Integer index = (Integer) s;
                toRemove.add(state.rights.get(index - 1));
            }

            for (Right r : toRemove)
                state.rights.remove(r);

            Updates.update(main, true);

            makeAccountTable(database, users, accountMap, table);

        }

    });
    removeRights.addStyleName(ValoTheme.BUTTON_SMALL);

    table.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1188285609779556446L;

        @Override
        public void valueChange(ValueChangeEvent event) {

            Object selection = table.getValue();
            Collection<?> sel = (Collection<?>) selection;
            if (sel.isEmpty())
                removeRights.setEnabled(false);
            else
                removeRights.setEnabled(true);

        }

    });

    final ComboBox mapSelect = new ComboBox();
    mapSelect.setWidth("100%");
    mapSelect.setNullSelectionAllowed(false);
    mapSelect.addStyleName(ValoTheme.COMBOBOX_SMALL);
    mapSelect.setCaption("Valitse kartta:");
    for (Strategiakartta a : Strategiakartta.enumerate(database)) {
        mapSelect.addItem(a.uuid);
        mapSelect.setItemCaption(a.uuid, a.getText(database));
        mapSelect.select(a.uuid);
    }

    final ComboBox rightSelect = new ComboBox();
    rightSelect.setWidth("100px");
    rightSelect.setNullSelectionAllowed(false);
    rightSelect.addStyleName(ValoTheme.COMBOBOX_SMALL);
    rightSelect.setCaption("Valitse oikeus:");
    rightSelect.addItem("Muokkaus");
    rightSelect.addItem("Luku");
    rightSelect.select("Luku");

    final ComboBox propagateSelect = new ComboBox();
    propagateSelect.setWidth("130px");
    propagateSelect.setNullSelectionAllowed(false);
    propagateSelect.addStyleName(ValoTheme.COMBOBOX_SMALL);
    propagateSelect.setCaption("Valitse laajuus:");
    propagateSelect.addItem(VALITTU_KARTTA);
    propagateSelect.addItem(ALATASON_KARTAT);
    propagateSelect.select(VALITTU_KARTTA);

    final Button addRight = new Button("Lis rivi", new Button.ClickListener() {

        private static final long serialVersionUID = -4841787792917761055L;

        public void buttonClick(ClickEvent event) {

            Object user = users.getValue();
            Account state = accountMap.get(user);

            String mapUUID = (String) mapSelect.getValue();
            Strategiakartta map = database.find(mapUUID);
            String right = (String) rightSelect.getValue();
            String propagate = (String) propagateSelect.getValue();

            Right r = new Right(map, right.equals("Muokkaus"), propagate.equals(ALATASON_KARTAT));
            state.rights.add(r);

            Updates.update(main, true);

            makeAccountTable(database, users, accountMap, table);

        }

    });
    addRight.addStyleName(ValoTheme.BUTTON_SMALL);

    table.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 6439090862804667322L;

        @Override
        public void valueChange(ValueChangeEvent event) {

            Object selection = table.getValue();
            Collection<?> selected = (Collection<?>) selection;
            if (!selected.isEmpty()) {
                removeRights.setEnabled(true);
            } else {
                removeRights.setEnabled(false);
            }

        }

    });

    HorizontalLayout hl2 = new HorizontalLayout();
    hl2.setSpacing(true);
    hl2.setWidth("100%");

    hl2.addComponent(removeRights);
    hl2.setComponentAlignment(removeRights, Alignment.TOP_LEFT);
    hl2.setExpandRatio(removeRights, 0.0f);

    hl2.addComponent(addRight);
    hl2.setComponentAlignment(addRight, Alignment.BOTTOM_LEFT);
    hl2.setExpandRatio(addRight, 0.0f);

    hl2.addComponent(mapSelect);
    hl2.setComponentAlignment(mapSelect, Alignment.BOTTOM_LEFT);
    hl2.setExpandRatio(mapSelect, 1.0f);

    hl2.addComponent(rightSelect);
    hl2.setComponentAlignment(rightSelect, Alignment.BOTTOM_LEFT);
    hl2.setExpandRatio(rightSelect, 0.0f);

    hl2.addComponent(propagateSelect);
    hl2.setComponentAlignment(propagateSelect, Alignment.BOTTOM_LEFT);
    hl2.setExpandRatio(propagateSelect, 0.0f);

    content.addComponent(hl2);
    content.setComponentAlignment(hl2, Alignment.BOTTOM_LEFT);
    content.setExpandRatio(hl2, 0.0f);

    final VerticalLayout vl = new VerticalLayout();

    final Panel p = new Panel();
    p.setWidth("100%");
    p.setHeight("200px");
    p.setContent(vl);

    final TimeConfiguration tc = TimeConfiguration.getInstance(database);

    final TextField tf2 = new TextField();
    tf2.setWidth("200px");
    tf2.addStyleName(ValoTheme.TEXTFIELD_SMALL);
    tf2.setCaption("Strategiakartan mritysaika:");
    tf2.setValue(tc.getRange());
    tf2.setCursorPosition(tf.getValue().length());
    tf2.setValidationVisible(true);
    tf2.setInvalidCommitted(true);
    tf2.setImmediate(true);
    tf2.addTextChangeListener(new TextChangeListener() {

        private static final long serialVersionUID = -8274588731607481635L;

        @Override
        public void textChange(TextChangeEvent event) {
            tf2.setValue(event.getText());
            try {
                tf2.validate();
                tc.setRange(event.getText());
                updateYears(database, vl);
                Updates.update(main, true);
            } catch (InvalidValueException e) {
                return;
            }
        }

    });
    tf2.addValidator(new Validator() {

        private static final long serialVersionUID = -4779239111120669168L;

        @Override
        public void validate(Object value) throws InvalidValueException {
            String s = (String) value;
            TimeInterval ti = TimeInterval.parse(s);
            long start = ti.startYear;
            long end = ti.endYear;
            if (start < 2015)
                throw new InvalidValueException("Alkuvuosi ei voi olla aikaisempi kuin 2015.");
            if (end > 2025)
                throw new InvalidValueException("Pttymisvuosi ei voi olla myhisempi kuin 2025.");
            if (end - start > 9)
                throw new InvalidValueException("Strategiakartta ei tue yli 10 vuoden tarkasteluja.");
        }

    });

    content.addComponent(tf2);
    content.setComponentAlignment(tf2, Alignment.BOTTOM_LEFT);
    content.setExpandRatio(tf2, 0.0f);

    updateYears(database, vl);

    content.addComponent(p);
    content.setComponentAlignment(p, Alignment.BOTTOM_LEFT);
    content.setExpandRatio(p, 0.0f);

    HorizontalLayout buttons = new HorizontalLayout();
    buttons.setSpacing(true);
    buttons.setMargin(false);

    Dialogs.makeDialog(main, main.dialogWidth(), main.dialogHeight(0.8), "Hallinnoi strategiakarttaa", "Sulje",
            content, buttons);

}

From source file:fi.semantum.strategia.Utils.java

License:Open Source License

public static void updateYears(final Database database, final VerticalLayout vl) {

    vl.removeAllComponents();/*from  ww w  .j  a va 2  s  .c  o  m*/

    final TimeConfiguration tc = TimeConfiguration.getInstance(database);
    TimeInterval ti = TimeInterval.parse(tc.getRange());
    for (int i = ti.startYear; i <= ti.endYear; i++) {
        final int year = i;
        HorizontalLayout hl = new HorizontalLayout();
        hl.setSpacing(true);
        String caption = Integer.toString(i) + (tc.isFrozen(i) ? " Muutokset estetty" : " Muokattavissa");
        Label l = new Label(caption);
        l.setWidth("250px");
        l.setHeight("100%");
        hl.addComponent(l);
        Button b = new Button(tc.isFrozen(i) ? "Avaa muokattavaksi" : "Est muutokset");
        b.addStyleName(ValoTheme.BUTTON_SMALL);
        b.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 556680407448842136L;

            @Override
            public void buttonClick(ClickEvent event) {
                if (tc.isFrozen(year)) {
                    tc.unfreeze(year);
                } else {
                    tc.freeze(year);
                }
                updateYears(database, vl);
            }

        });
        b.setWidth("200px");
        hl.addComponent(b);
        //hl.setWidth("100%");
        vl.addComponent(hl);
    }

}

From source file:fi.semantum.strategia.Utils.java

License:Open Source License

public static Button tagButton(final Database database, String prefix, String tag, final int index) {

    Tag t = database.getOrCreateTag(tag);

    Styles styles = Page.getCurrent().getStyles();

    styles.add(".fi_semantum_strategia div.v-button." + prefix + "tag" + index
            + " { opacity: 1.0; box-shadow:none; color: #000000; background-image: linear-gradient(" + t.color
            + " 0%, " + t.color + " 100%); }");

    Button tagButton = new Button();
    tagButton.setEnabled(false);//from   w  w  w .  j a  v a 2s  . c o m
    tagButton.setCaption(tag);
    tagButton.addStyleName(prefix + "tag" + index);

    return tagButton;

}