Example usage for com.vaadin.ui Label addStyleName

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

Introduction

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

Prototype

@Override
    public void addStyleName(String style) 

Source Link

Usage

From source file:edu.nps.moves.mmowgliMobile.ui.UserRenderer2.java

License:Open Source License

public void setMessage(FullEntryView2 mView, ListEntry message, ListView2 messageList,
        AbstractOrderedLayout layout) {/*from  w w w.java 2  s .  co  m*/
    // messageList can be null if coming in from ActionPlan
    Object key = HSess.checkInit();
    UserListEntry wu = (UserListEntry) message;
    User u = wu.getUser();
    layout.removeAllComponents();

    HorizontalLayout hlay = new HorizontalLayout();
    layout.addComponent(hlay);
    hlay.addStyleName("m-userview-top");
    hlay.setWidth("100%");
    hlay.setMargin(true);
    hlay.setSpacing(true);

    Image img = new Image();
    img.addStyleName("m-ridgeborder");
    img.setSource(mediaLocator.locate(u.getAvatar().getMedia()));
    img.setWidth("90px");
    img.setHeight("90px");
    hlay.addComponent(img);
    hlay.setComponentAlignment(img, Alignment.MIDDLE_CENTER);

    Label lab;
    hlay.addComponent(lab = new Label());
    lab.setWidth("5px");

    VerticalLayout vlay = new VerticalLayout();
    vlay.setSpacing(true);
    hlay.addComponent(vlay);
    hlay.setComponentAlignment(vlay, Alignment.MIDDLE_LEFT);
    vlay.setWidth("100%");
    hlay.setExpandRatio(vlay, 1.0f);
    HorizontalLayout horl = new HorizontalLayout();
    horl.setSpacing(false);
    vlay.addComponent(horl);
    vlay.setComponentAlignment(horl, Alignment.BOTTOM_LEFT);
    horl.addComponent(lab = new Label("name"));
    lab.addStyleName("m-user-top-label"); //light-text");
    horl.addComponent(lab = new HtmlLabel("  " + u.getUserName()));
    lab.addStyleName("m-user-top-value");
    horl = new HorizontalLayout();
    horl.setSpacing(false);
    vlay.addComponent(horl);
    vlay.setComponentAlignment(horl, Alignment.TOP_LEFT);

    horl.addComponent(lab = new Label("level"));
    lab.addStyleName("m-user-top-label"); //light-text");
    Level lev = u.getLevel();
    if (u.isGameMaster()) {
        Level l = Level.getLevelByOrdinal(Level.GAME_MASTER_ORDINAL, HSess.get());
        if (l != null)
            lev = l;
    }
    horl.addComponent(lab = new HtmlLabel("   " + lev.getDescription()));
    lab.addStyleName("m-user-top-value");

    GridLayout gLay = new GridLayout();
    // gLay.setHeight("155px");  // won't size properly
    gLay.setMargin(true);
    gLay.addStyleName("m-userview-mid");
    gLay.setColumns(2);
    gLay.setRows(11);
    gLay.setSpacing(true);
    gLay.setWidth("100%");
    gLay.setColumnExpandRatio(1, 1.0f);
    layout.addComponent(gLay);

    addRow(gLay, "user ID:", "" + getPojoId(message));
    addRow(gLay, "location:", u.getLocation());
    addRow(gLay, "expertise:", u.getExpertise());
    addRow(gLay, "affiliation:", u.getAffiliation());
    addRow(gLay, "date registered:", formatter.format(u.getRegisterDate()));

    gLay.addComponent(new Hr(), 0, 5, 1, 5);

    Container cntr = new CardsByUserContainer<Card>(u); // expects ThreadLocal session to be setup
    numCards = cntr.size();
    addRow(gLay, "cards played:", "" + numCards);
    cntr = new ActionPlansByUserContainer<Card>(u); // expects ThreadLocal session to be setup
    numAps = cntr.size();
    addRow(gLay, "action plans:", "" + numAps);

    gLay.addComponent(new Hr(), 0, 8, 1, 8);

    addRow(gLay, "exploration points:", "" + u.getBasicScore());
    addRow(gLay, "innovation points:", "" + u.getInnovationScore());

    cardListener = new CardLis(u, mView);
    apListener = new AppLis(u, mView);

    layout.addComponent(makeButtons());

    HSess.checkClose(key);
}

From source file:edu.nps.moves.security.PasswordResetUI.java

License:Open Source License

private void handleChangeTL(User user) {
    this.user = user;
    Game g = Game.getTL();//from w ww .  j  av a2  s.c om

    String brand = g.getCurrentMove().getTitle();
    Page.getCurrent().setTitle("Password reset for " + brand + " mmowgli");

    HorizontalLayout hLay = new HorizontalLayout();
    hLay.setMargin(true);
    hLay.setWidth("100%");
    setContent(hLay);

    GameLinks gl = GameLinks.getTL();
    String blog = gl.getBlogLink();
    Label lab;
    hLay.addComponent(lab = new Label());
    hLay.setExpandRatio(lab, 0.5f);

    VerticalLayout vl = new VerticalLayout();
    hLay.addComponent(vl);
    vl.setWidth(bannerWidthPx);

    hLay.addComponent(lab = new Label());
    hLay.setExpandRatio(lab, 0.5f);

    vl.addStyleName("m-greyborder");
    vl.setMargin(true);
    vl.setSpacing(true);

    vl.addComponent(lab = new HtmlLabel(""));
    lab.addStyleName("m-font-21-bold");
    lab.setSizeUndefined();
    vl.setComponentAlignment(lab, Alignment.MIDDLE_CENTER);
    StringBuilder sb = new StringBuilder();
    sb.append(thanksHdr1);
    sb.append(blog);
    sb.append(thanksHdr2);
    sb.append(brand);
    sb.append(thanksHdr3);
    lab.setValue(sb.toString());

    vl.addComponent(lab = new HtmlLabel(""));
    lab.setHeight("15px");
    vl.setComponentAlignment(lab, Alignment.MIDDLE_CENTER);

    FormLayout fLay = new FormLayout();
    fLay.setSizeUndefined();
    fLay.addStyleName("m-login-form"); // to allow styling contents (v-textfield)
    vl.addComponent(fLay);
    vl.setComponentAlignment(fLay, Alignment.MIDDLE_CENTER);

    newPw = new PasswordField("New Password");
    newPw.setWidth("99%");
    fLay.addComponent(newPw);

    newPw2 = new PasswordField("Again, please");
    newPw2.setWidth("99%");
    fLay.addComponent(newPw2);

    HorizontalLayout buttLay = new HorizontalLayout();
    buttLay.setSpacing(true);
    vl.addComponent(buttLay);
    vl.setComponentAlignment(buttLay, Alignment.TOP_CENTER);

    NativeButton cancelButt = new NativeButton();
    cancelButt.setStyleName("m-cancelButton");
    buttLay.addComponent(cancelButt);
    buttLay.setComponentAlignment(cancelButt, Alignment.BOTTOM_RIGHT);

    saveButt = new NativeButton();
    saveButt.setClickShortcut(ShortcutAction.KeyCode.ENTER);
    saveButt.setStyleName("m-continueButton"); //m-saveChangesButton");
    buttLay.addComponent(saveButt);
    buttLay.setComponentAlignment(saveButt, Alignment.BOTTOM_RIGHT);

    cancelButt.addClickListener(this);
    saveButt.addClickListener(this);
}

From source file:eu.maxschuster.vaadin.buttonlink.demo.DemoUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {

    final VerticalLayout wrapper = new VerticalLayout();
    wrapper.setSizeFull();/*  ww  w  .j a  v  a 2  s  .c  o  m*/
    setContent(wrapper);

    // Show it in the middle of the screen
    final VerticalLayout layout = new VerticalLayout();
    layout.setSpacing(true);
    layout.setSizeUndefined();
    wrapper.addComponent(layout);
    wrapper.setComponentAlignment(layout, Alignment.MIDDLE_CENTER);

    final Label themeName = new Label();
    themeName.setCaption("Current Theme:");
    themeName.addStyleName("h1");
    layout.addComponent(themeName);

    Label waring = new Label("<strong>Attention:</strong><br />\nChanging the theme may take a few seconds!");
    waring.setContentMode(ContentMode.HTML);
    layout.addComponent(waring);

    getPage().addUriFragmentChangedListener(new UriFragmentChangedListener() {

        @Override
        public void uriFragmentChanged(UriFragmentChangedEvent event) {
            String fragment = event.getUriFragment().replace("!", "");
            if (fragment.isEmpty()) {
                fragment = defaultTheme;
            }
            loadTheme(fragment);
        }
    });

    themeSelect.setSizeFull();
    themeSelect.setNullSelectionAllowed(false);
    themeSelect.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            String fragment = "!" + themeSelect.getValue();
            getPage().setUriFragment(fragment);
        }
    });
    layout.addComponent(themeSelect);
    layout.setComponentAlignment(themeSelect, Alignment.BOTTOM_CENTER);

    final CheckBox useIcon = new CheckBox("Use icons");
    useIcon.setValue(false);
    layout.addComponent(useIcon);

    final HorizontalLayout comparsionLayout = new HorizontalLayout();
    comparsionLayout.setSpacing(true);
    layout.addComponent(comparsionLayout);
    layout.setComponentAlignment(comparsionLayout, Alignment.TOP_CENTER);

    final Button button = new Button("This is a \"normal\" Button", new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            Notification.show("Hello World!");
        }
    });
    comparsionLayout.addComponent(button);
    comparsionLayout.setComponentAlignment(button, Alignment.MIDDLE_RIGHT);

    // Initialize our new UI component
    final ButtonLink buttonLink = new ButtonLink("This is a ButtonLink",
            new ExternalResource("https://vaadin.com"));
    buttonLink.setTargetName("_blank");
    buttonLink.setDescription("Visit vaadin.com in a new tab or window.");
    buttonLink.addStyleName("test-stylename");
    comparsionLayout.addComponent(buttonLink);
    comparsionLayout.setComponentAlignment(buttonLink, Alignment.MIDDLE_LEFT);

    themeName.setPropertyDataSource(themeSelect);

    useIcon.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean b = (Boolean) event.getProperty().getValue();
            if (b) {
                button.setIcon(vaadinIcon, "Vaadin Logo");
                buttonLink.setIcon(vaadinIcon, "Vaadin Logo");
            } else {
                button.setIcon(null);
                buttonLink.setIcon(null);
            }
        }
    });

    String fragment = getPage().getUriFragment();

    loadTheme(
            fragment == null || fragment.replace("!", "").isEmpty() ? defaultTheme : fragment.replace("!", ""));
}

From source file:eu.maxschuster.vaadin.signaturefield.demo.DemoUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {

    getPage().setTitle(pageTitle);/*from  w ww. jav a  2 s . c o  m*/

    final VerticalLayout margin = new VerticalLayout();
    setContent(margin);

    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.setWidth("658px");
    margin.addComponent(layout);
    margin.setComponentAlignment(layout, Alignment.TOP_CENTER);

    final Label header1 = new Label(pageTitle);
    header1.addStyleName("h1");
    header1.setSizeUndefined();
    layout.addComponent(header1);
    layout.setComponentAlignment(header1, Alignment.TOP_CENTER);

    final TabSheet tabSheet = new TabSheet();
    tabSheet.setWidth("100%");
    layout.addComponent(tabSheet);
    layout.setComponentAlignment(tabSheet, Alignment.TOP_CENTER);

    final Panel signaturePanel = new Panel();
    signaturePanel.addStyleName("signature-panel");
    signaturePanel.setWidth("100%");
    tabSheet.addTab(signaturePanel, "Demo");

    final VerticalLayout signatureLayout = new VerticalLayout();
    signatureLayout.setMargin(true);
    signatureLayout.setSpacing(true);
    signatureLayout.setSizeFull();
    signaturePanel.setContent(signatureLayout);

    final SignatureField signatureField = new SignatureField();
    signatureField.setWidth("100%");
    signatureField.setHeight("318px");
    signatureField.setPenColor(Color.ULTRAMARINE);
    signatureField.setBackgroundColor("white");
    signatureField.setConverter(new StringToDataUrlConverter());
    signatureField.setPropertyDataSource(dataUrlProperty);
    signatureField.setVelocityFilterWeight(0.7);
    signatureLayout.addComponent(signatureField);
    signatureLayout.setComponentAlignment(signatureField, Alignment.MIDDLE_CENTER);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setWidth("100%");
    signatureLayout.addComponent(buttonLayout);

    final Button clearButton = new Button("Clear", new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            signatureField.clear();
        }
    });
    buttonLayout.addComponent(clearButton);
    buttonLayout.setComponentAlignment(clearButton, Alignment.MIDDLE_LEFT);

    final Label message = new Label("Sign above");
    message.setSizeUndefined();
    buttonLayout.addComponent(message);
    buttonLayout.setComponentAlignment(message, Alignment.MIDDLE_CENTER);

    final ButtonLink saveButtonLink = new ButtonLink("Save", null);
    saveButtonLink.setTargetName("_blank");
    buttonLayout.addComponent(saveButtonLink);
    buttonLayout.setComponentAlignment(saveButtonLink, Alignment.MIDDLE_RIGHT);

    final Panel optionsPanel = new Panel();
    optionsPanel.setSizeFull();
    tabSheet.addTab(optionsPanel, "Options");

    final FormLayout optionsLayout = new FormLayout();
    optionsLayout.setMargin(true);
    optionsLayout.setSpacing(true);
    optionsPanel.setContent(optionsLayout);

    final ComboBox mimeTypeComboBox = new ComboBox(null, mimeTypeContainer);
    optionsLayout.addComponent(mimeTypeComboBox);
    mimeTypeComboBox.setItemCaptionPropertyId("mimeType");
    mimeTypeComboBox.setNullSelectionAllowed(false);
    mimeTypeComboBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            MimeType mimeType = (MimeType) event.getProperty().getValue();
            signatureField.setMimeType(mimeType);
        }
    });
    mimeTypeComboBox.setValue(MimeType.PNG);
    mimeTypeComboBox.setCaption("Result MIME-Type");

    final CheckBox immediateCheckBox = new CheckBox("immediate", false);
    optionsLayout.addComponent(immediateCheckBox);
    immediateCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean immediate = (Boolean) event.getProperty().getValue();
            signatureField.setImmediate(immediate);
        }
    });

    final CheckBox readOnlyCheckBox = new CheckBox("readOnly", false);
    optionsLayout.addComponent(readOnlyCheckBox);
    readOnlyCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean readOnly = (Boolean) event.getProperty().getValue();
            signatureField.setReadOnly(readOnly);
            mimeTypeComboBox.setReadOnly(readOnly);
            clearButton.setEnabled(!readOnly);
        }
    });

    final CheckBox requiredCheckBox = new CheckBox("required (causes bug that clears field)", false);
    optionsLayout.addComponent(requiredCheckBox);
    requiredCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean required = (Boolean) event.getProperty().getValue();
            signatureField.setRequired(required);
        }
    });

    final CheckBox clearButtonEnabledButton = new CheckBox("clearButtonEnabled", false);
    optionsLayout.addComponent(clearButtonEnabledButton);
    clearButtonEnabledButton.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean clearButtonEnabled = (Boolean) event.getProperty().getValue();
            signatureField.setClearButtonEnabled(clearButtonEnabled);
        }
    });

    final Panel resultPanel = new Panel("Results:");
    resultPanel.setWidth("100%");
    layout.addComponent(resultPanel);

    final VerticalLayout resultLayout = new VerticalLayout();
    resultLayout.setMargin(true);
    resultPanel.setContent(resultLayout);

    final Image stringPreviewImage = new Image("String preview image:");
    stringPreviewImage.setWidth("500px");
    resultLayout.addComponent(stringPreviewImage);

    final Image dataUrlPreviewImage = new Image("DataURL preview image:");
    dataUrlPreviewImage.setWidth("500px");
    resultLayout.addComponent(dataUrlPreviewImage);

    final TextArea textArea = new TextArea("DataURL:");
    textArea.setWidth("100%");
    textArea.setHeight("300px");
    resultLayout.addComponent(textArea);

    final Label emptyLabel = new Label();
    emptyLabel.setCaption("Is Empty:");
    emptyLabel.setValue(String.valueOf(signatureField.isEmpty()));
    resultLayout.addComponent(emptyLabel);

    signatureField.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            String signature = (String) event.getProperty().getValue();
            stringPreviewImage.setSource(signature != null ? new ExternalResource(signature) : null);
            textArea.setValue(signature);
            emptyLabel.setValue(String.valueOf(signatureField.isEmpty()));
        }
    });
    dataUrlProperty.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            try {
                final DataUrl signature = (DataUrl) event.getProperty().getValue();
                dataUrlPreviewImage.setSource(
                        signature != null ? new ExternalResource(serializer.serialize(signature)) : null);
                StreamResource streamResource = null;
                if (signature != null) {
                    StreamSource streamSource = new StreamSource() {

                        @Override
                        public InputStream getStream() {
                            return new ByteArrayInputStream(signature.getData());
                        }
                    };
                    MimeType mimeType = MimeType.valueOfMimeType(signature.getMimeType());
                    String extension = null;

                    switch (mimeType) {
                    case JPEG:
                        extension = "jpg";
                        break;
                    case PNG:
                        extension = "png";
                        break;
                    }

                    streamResource = new StreamResource(streamSource, "signature." + extension);
                    streamResource.setMIMEType(signature.getMimeType());
                    streamResource.setCacheTime(0);
                }
                saveButtonLink.setResource(streamResource);
            } catch (MalformedURLException e) {
                logger.error(e.getMessage(), e);
            }
        }
    });
}

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  www.ja  v  a 2  s  .c o  m
    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   ww  w  .j a  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);/* w w w . j  av a2s  .  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  w  w .j  av  a  2  s .  co 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 www.  j ava  2  s.co m*/
    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.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);/*w ww. j a  v a 2  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);

}