Example usage for com.vaadin.ui ComboBox addValueChangeListener

List of usage examples for com.vaadin.ui ComboBox addValueChangeListener

Introduction

In this page you can find the example usage for com.vaadin.ui ComboBox addValueChangeListener.

Prototype

@Override
    public Registration addValueChangeListener(HasValue.ValueChangeListener<T> listener) 

Source Link

Usage

From source file:com.terralcode.gestion.frontend.view.widgets.desplegable.ComponenteDesplegableView.java

private Component buildCustomerDetail() {
    GridLayout miGrid = new GridLayout(3, 2);

    ComboBox combo = new ComboBox();
    combo.addValueChangeListener(new Property.ValueChangeListener() {

        @Override/*w  w w.j av a  2 s  . com*/
        public void valueChange(Property.ValueChangeEvent event) {
            seleccion = (String) event.getProperty().getValue();

        }
    });
    combo.addItems("Pocino Ibrico", "Pocino Blanco", "Ovino", "Vacuno", "Avicultura", "Otros");
    //        combo.addItem(especies);
    Label informacion = new Label("datos");
    Button botonMas = new Button("+");
    botonMas.addClickListener(new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            Integer clave;
            if (valores.containsValue(seleccion)) {
                clave = 1;
                if (!valores.isEmpty()) {
                    clave = valores.size() + 1;
                }

                valores.put(clave, seleccion);
            }
            informacion.setValue(mostrarValores());
            Notification.show(seleccion + " aadido");
        }
    });
    Button botonMenos = new Button("-");
    miGrid.addComponent(informacion, 0, 0);
    miGrid.addComponent(combo, 0, 1);
    miGrid.addComponent(botonMas, 1, 1);
    miGrid.addComponent(botonMenos, 2, 1);

    return miGrid;

}

From source file:com.wcs.wcslib.vaadin.widget.multifileupload.WidgetTestApplication.java

License:Apache License

private void addWindowPositionSwitcher() {
    final ComboBox cb = new ComboBox("Window position");
    cb.setNullSelectionAllowed(false);//ww w .j a va 2s . c  om
    for (UploadStateWindow.WindowPosition windowPosition : UploadStateWindow.WindowPosition.values()) {
        cb.addItem(windowPosition);
        cb.setItemCaption(windowPosition, windowPosition.name());
    }
    cb.setValue(UploadStateWindow.WindowPosition.BOTTOM_RIGHT);
    cb.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent event) {
            uploadStateWindow.setWindowPosition((UploadStateWindow.WindowPosition) cb.getValue());
        }
    });
    form.addComponent(cb);
}

From source file:de.catma.ui.repository.wizard.ComboBoxColumnGenerator.java

License:Open Source License

public Component generateCell(Table source, Object itemId, Object columnId) {
    // Get the object stored in the cell as a property
    Property prop = source.getItem(itemId).getItemProperty(columnId);

    ComboBox comboBox = new ComboBox(null, options);
    comboBox.setNullSelectionAllowed(false);
    comboBox.setPropertyDataSource(prop);
    comboBox.setImmediate(true);/*from  w ww  .ja  v  a 2s  .c  o  m*/

    if (valueChangeListenerGenerator != null) {
        comboBox.addValueChangeListener(
                valueChangeListenerGenerator.generateValueChangeListener(source, itemId, columnId));
    }

    return comboBox;
}

From source file:de.symeda.sormas.ui.configuration.DevModeView.java

License:Open Source License

public DevModeView() {
    super(VIEW_NAME);

    contentLayout = new VerticalLayout();
    contentLayout.setMargin(true);//w ww .  j  a  v  a 2  s  . c  om
    contentLayout.setSpacing(true);
    contentLayout.setSizeFull();
    contentLayout.setStyleName("crud-main-layout");

    HorizontalLayout caseGeneratorLayout = new HorizontalLayout();

    TextField caseCountField = new TextField();
    caseCountField.setCaption(I18nProperties.getCaption(Captions.devModeCaseCount));
    caseGeneratorConfigBinder.forField(caseCountField)
            .withConverter(new StringToIntegerConverter("Must be a number"))
            .bind(CaseGenerationConfig::getCaseCount, CaseGenerationConfig::setCaseCount);
    caseGeneratorLayout.addComponent(caseCountField);

    DateField startDateField = new DateField();
    startDateField.setCaption(I18nProperties.getCaption(Captions.devModeStartDate));
    startDateField.setDateFormat(DateHelper.getLocalDatePattern());
    startDateField.setLenient(true);
    caseGeneratorConfigBinder.bind(startDateField, CaseGenerationConfig::getStartDate,
            CaseGenerationConfig::setStartDate);
    caseGeneratorLayout.addComponent(startDateField);

    DateField endDateField = new DateField();
    endDateField.setCaption(I18nProperties.getCaption(Captions.devModeEndDate));
    endDateField.setDateFormat(DateHelper.getLocalDatePattern());
    endDateField.setLenient(true);
    caseGeneratorConfigBinder.bind(endDateField, CaseGenerationConfig::getEndDate,
            CaseGenerationConfig::setEndDate);
    caseGeneratorLayout.addComponent(endDateField);

    ComboBox<Disease> diseaseField = new ComboBox<>(null,
            FacadeProvider.getDiseaseConfigurationFacade().getAllActivePrimaryDiseases());
    diseaseField.setCaption(I18nProperties.getCaption(Captions.devModeDisease));
    caseGeneratorConfigBinder.bind(diseaseField, CaseGenerationConfig::getDisease,
            CaseGenerationConfig::setDisease);
    caseGeneratorLayout.addComponent(diseaseField);

    List<RegionReferenceDto> regions = FacadeProvider.getRegionFacade().getAllAsReference();
    ComboBox<RegionReferenceDto> regionField = new ComboBox<RegionReferenceDto>(null, regions);
    regionField.setCaption(I18nProperties.getCaption(Captions.devModeRegion));
    caseGeneratorConfigBinder.bind(regionField, CaseGenerationConfig::getRegion,
            CaseGenerationConfig::setRegion);
    caseGeneratorLayout.addComponent(regionField);

    ComboBox<DistrictReferenceDto> districtField = new ComboBox<DistrictReferenceDto>();
    districtField.setCaption(I18nProperties.getCaption(Captions.devModeDistrict));
    caseGeneratorConfigBinder.bind(districtField, CaseGenerationConfig::getDistrict,
            CaseGenerationConfig::setDistrict);
    caseGeneratorLayout.addComponent(districtField);

    regionField.addValueChangeListener(event -> {
        RegionReferenceDto region = event.getValue();
        if (region != null) {
            districtField.setItems(FacadeProvider.getDistrictFacade().getAllByRegion(region.getUuid()));
        } else {
            districtField.setItems(new ArrayList<DistrictReferenceDto>());
        }
    });

    Button generateButton = new Button("generate cases");
    CssStyles.style(generateButton, CssStyles.FORCE_CAPTION);
    generateButton.addClickListener(e -> generateCases());
    caseGeneratorLayout.addComponent(generateButton);

    contentLayout.addComponent(caseGeneratorLayout);

    CaseGenerationConfig config = new CaseGenerationConfig();
    config.setRegion(regions.get(0));
    caseGeneratorConfigBinder.setBean(config);

    addComponent(contentLayout);
}

From source file:dhbw.clippinggorilla.userinterface.views.ClippingView.java

public ClippingView(Clipping clipping) {
    User user = UserUtils.getCurrent();/* w w w.j a  v  a2 s. c  o m*/

    clippingArticlesLayout = new VerticalLayout();
    clippingArticlesLayout.setSpacing(true);
    clippingArticlesLayout.setMargin(false);
    clippingArticlesLayout.setSizeFull();

    HorizontalLayout clippingOptionsLayout = new HorizontalLayout();
    clippingOptionsLayout.setSpacing(true);
    clippingOptionsLayout.setMargin(false);
    clippingOptionsLayout.setWidth("100%");

    ComboBox<SortOptions> comboBoxSortOptions = new ComboBox<>(Language.get(Word.SORT_BY));
    Language.setCustom(Word.SORT_BY, s -> {
        comboBoxSortOptions.setCaption(s);
        comboBoxSortOptions.getDataProvider().refreshAll();
    });
    comboBoxSortOptions.setItems(EnumSet.allOf(SortOptions.class));
    comboBoxSortOptions.setItemCaptionGenerator(s -> s.getName());
    comboBoxSortOptions.setItemIconGenerator(s -> s.getIcon());
    comboBoxSortOptions.setValue(SortOptions.BYPROFILE);
    comboBoxSortOptions.setTextInputAllowed(false);
    comboBoxSortOptions.setEmptySelectionAllowed(false);
    comboBoxSortOptions.addStyleName("comboboxsort");
    comboBoxSortOptions.addValueChangeListener(e -> {
        switch (e.getValue()) {
        case BYDATE:
            createClippingViewByDate(clipping);
            break;
        case BYPROFILE:
            createClippingViewByProfile(clipping);
            break;
        case BYSOURCE:
            createClippingViewBySource(clipping);
            break;
        }
    });

    Button buttonRegenerateClipping = new Button(VaadinIcons.REFRESH);
    buttonRegenerateClipping.addStyleName(ValoTheme.BUTTON_PRIMARY);
    buttonRegenerateClipping.addClickListener(ce -> {
        user.setLastClipping(ClippingUtils.generateClipping(user, false));
        ClippingGorillaUI.getCurrent().setMainContent(ClippingView.getCurrent());
    });

    clippingOptionsLayout.addComponents(comboBoxSortOptions, buttonRegenerateClipping);
    clippingOptionsLayout.setExpandRatio(comboBoxSortOptions, 5);
    clippingOptionsLayout.setComponentAlignment(buttonRegenerateClipping, Alignment.BOTTOM_CENTER);

    addComponents(clippingOptionsLayout, clippingArticlesLayout);

    createClippingViewByProfile(clipping);
    if (clipping.getArticles().keySet().isEmpty() && clipping.getArticlesFromGroup().keySet().isEmpty()) {
        Label labelNoProfile = new Label();
        Language.setCustom(Word.NO_PROFILE_PRESENT, s -> labelNoProfile.setValue(s));
        labelNoProfile.addStyleName(ValoTheme.LABEL_H2);
        clippingArticlesLayout.addComponent(labelNoProfile);
    }
}

From source file:dhbw.clippinggorilla.userinterface.views.FooterBar.java

public FooterBar() {
    setColumns(6);//  w  w  w.ja v  a  2s .  co  m
    setRows(1);
    addStyleName("menubar");
    setWidth("100%");
    setHeightUndefined();
    setColumnExpandRatio(4, 5);
    setSpacing(true);
    setMargin(true);

    Image logo = new Image();
    try {
        logo.setSource(new FileResource(FileUtils.getFile("images/logo_small.png").toFile()));
    } catch (FileNotFoundException ex) {
        Log.error("Could not find logo!", ex);
    }
    logo.setHeight("100%");
    addComponent(logo);
    setComponentAlignment(logo, Alignment.MIDDLE_CENTER);

    Button aboutUs = new Button();
    Language.set(Word.ABOUT_US, aboutUs);
    aboutUs.addClickListener((ce) -> {
        ClippingGorillaUI.getCurrent().setMainContent(AboutUsView.getCurrent());
    });
    aboutUs.setIcon(VaadinIcons.USERS);
    aboutUs.addStyleName(ValoTheme.BUTTON_BORDERLESS);
    addComponent(aboutUs);
    setComponentAlignment(aboutUs, Alignment.MIDDLE_CENTER);

    Button docs = new Button();
    Language.set(Word.DOCUMENTS, docs);
    docs.addClickListener(ce -> {
        ClippingGorillaUI.getCurrent().setMainContent(DocumentsView.getCurrent());
    });
    docs.setIcon(VaadinIcons.ARCHIVE);
    docs.addStyleName(ValoTheme.BUTTON_BORDERLESS);
    addComponent(docs);
    setComponentAlignment(docs, Alignment.MIDDLE_CENTER);

    Button impressum = new Button();
    Language.set(Word.IMPRESSUM, impressum);
    impressum.addClickListener(ce -> {
        ClippingGorillaUI.getCurrent().setMainContent(ImpressumView.getCurrent());
    });
    impressum.setIcon(VaadinIcons.SCALE);
    impressum.addStyleName(ValoTheme.BUTTON_BORDERLESS);
    addComponent(impressum);
    setComponentAlignment(impressum, Alignment.MIDDLE_CENTER);

    Label spacing = new Label();
    addComponent(spacing);
    setComponentAlignment(spacing, Alignment.MIDDLE_CENTER);

    ComboBox<Locale> languages = new ComboBox<>(null, Language.getAllLanguages().keySet());
    languages.setItemCaptionGenerator(loc -> loc.getDisplayLanguage(loc));
    if (!Language.getAllLanguages().containsKey(VaadinSession.getCurrent().getLocale())) {
        languages.setValue(Locale.ENGLISH);
    } else {
        languages.setValue(VaadinSession.getCurrent().getLocale());
    }
    languages.setEmptySelectionAllowed(false);
    languages.setItemIconGenerator(FooterBar::getIcon);
    languages.addValueChangeListener(
            (HasValue.ValueChangeEvent<Locale> loc) -> Language.setLanguage(loc.getValue()));
    languages.setTextInputAllowed(false);
    addComponent(languages);
    setComponentAlignment(languages, Alignment.MIDDLE_CENTER);

    SESSIONS.put(VaadinSession.getCurrent(), this);
}

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

License:Apache License

/**
 * Setup the login form including its logic.
 *//*from   w ww  . ja v a 2 s.  c  o  m*/
private void setupLoginForm(AbstractLoginComponent.AUTH_MODE type, String pendingAuth, VaadinRequest request) {
    ComboBox authSelection = new ComboBox();
    authSelection.setWidth("400px");
    authSelection.setNullSelectionAllowed(false);
    authSelection.setStyleName("auth_selection");
    Label spacer = new Label("<br/>", ContentMode.HTML);
    spacer.setWidth("400px");

    String orcidClientId = DataManagerSettings.getSingleton()
            .getStringProperty(OrcidLoginComponent.ORCID_CLIENT_ID_PROPERTY, null);
    String orcidClientSecret = DataManagerSettings.getSingleton()
            .getStringProperty(OrcidLoginComponent.ORCID_CLIENT_SECRET_PROPERTY, null);

    /// String b2AccessClientId = DataManagerSettings.getSingleton().getStringProperty(B2AccessLoginComponent.B2ACCESS_CLIENT_ID_PROPERTY, null);
    // String b2AccessClientSecret = DataManagerSettings.getSingleton().getStringProperty(B2AccessLoginComponent.B2ACCESS_CLIENT_SECRET_PROPERTY, null);
    List<AbstractLoginComponent> components = new ArrayList<>();

    if (orcidClientId != null && !orcidClientId.equals("ORCID_CLIENT_ID") && orcidClientSecret != null
            && !orcidClientSecret.equals("ORCID_CLIENT_SECRET")) {
        components.add(new OrcidLoginComponent());
    }

    /*B2Access is currently not supported. 
    if (b2AccessClientId != null && b2AccessClientSecret != null) {
    components.add(new B2AccessLoginComponent());
    }*/
    components.add(new EmailPasswordLoginComponent());

    loginComponents = components.toArray(new AbstractLoginComponent[] {});

    //default login component has index 0
    loginComponent = loginComponents[0];
    for (AbstractLoginComponent component : loginComponents) {
        //add new login component
        authSelection.addItem(component.getLoginIdentifier());
        authSelection.setItemCaption(component.getLoginIdentifier(), component.getLoginLabel());

        if (pendingAuth != null && pendingAuth.equals(component.getLoginIdentifier())) {
            //login or registration process in pending, continue process
            loginComponent = component;
            try {
                switch (type) {
                case REGISTRATION:
                    loginComponent.doRegistration(request);
                    break;
                default:
                    loginComponent.doLogin(request);
                    break;
                }

            } catch (UnauthorizedAccessAttemptException ex) {
                //failed to continue auth...cancel.
                String message = "Failed to continue pending "
                        + (AbstractLoginComponent.AUTH_MODE.LOGIN.equals(type) ? "login" : "registration")
                        + " for authentication #" + pendingAuth + ".";
                LOGGER.error(message, ex);
                UIComponentTools.showError(message);
                VaadinSession.getCurrent().setAttribute("auth_pending", null);
                VaadinSession.getCurrent().setAttribute("registration_pending", null);
                loginComponent.reset();
            }
        }
    }

    authSelection.select(loginComponent.getLoginIdentifier());

    authSelection.addValueChangeListener((Property.ValueChangeEvent event) -> {
        String value = (String) event.getProperty().getValue();
        if (value != null) {
            for (AbstractLoginComponent component : loginComponents) {
                if (value.equals(component.getLoginIdentifier())) {
                    loginForm.replaceComponent(loginComponent, component);
                    loginComponent = component;
                }
            }
        }
    });

    loginForm = new VerticalLayout(authSelection, spacer, loginComponent);
    loginForm.setComponentAlignment(authSelection, Alignment.TOP_CENTER);
    loginForm.setComponentAlignment(spacer, Alignment.TOP_CENTER);
    loginForm.setComponentAlignment(loginComponent, Alignment.TOP_CENTER);
}

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

License:Apache License

@Override
protected void init(VaadinRequest request) {

    getPage().setTitle(pageTitle);//from   w  w w.ja va 2s .  c  om

    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:fi.racetrace.adminpanel.ui.columngenerator.DeviceIconGC.java

License:Open Source License

@Override
public Object generateCell(Table source, Object itemId, Object columnId) {
    Component c = null;//from ww  w .j  a v a2s .  co  m

    if (source.isEditable() && itemId.equals(source.getValue())) {
        // TODO bindaus modeliin
        ComboBox cb = new ComboBox("Icon", new BeanItemContainer<fi.racetrace.adminpanel.data.DeviceIcon>(
                fi.racetrace.adminpanel.data.DeviceIcon.class, icons));
        cb.setWidth(100, Unit.PIXELS);

        final Item sdItem = source.getItem(itemId);

        cb.setValue(sdItem.getItemProperty("icon"));

        cb.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                sdItem.getItemProperty("icon").setValue(event.getProperty().getValue());
            }
        });

        c = cb;
    } else {
        Item item = source.getItem(itemId);
        DeviceIcon di = ((DeviceIcon) item.getItemProperty("icon").getValue());
        if (di != null) {
            String icon = di.getPath();
            Embedded e = new Embedded("icon", new ThemeResource("img/" + icon));
            c = e;
        } else {
            Label l = new Label("N/A");
            c = l;
        }
    }
    return c;
}

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();//  ww  w  .  j  av  a  2s  . c om
    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);

}