Search in sources :

Example 96 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project data-prep by Talend.

the class DataSetService method updateDataSet.

/**
 * Updates a data set metadata. If no data set exists for given id, a {@link TDPException} is thrown.
 *
 * @param dataSetId The id of data set to be updated.
 * @param dataSetMetadata The new content for the data set. If empty, existing content will <b>not</b> be replaced.
 * For delete operation, look at {@link #delete(String)}.
 */
@RequestMapping(value = "/datasets/{id}", method = PUT)
@ApiOperation(value = "Update a data set metadata by id", notes = "Update a data set metadata according to the content of the PUT body. Id should be a UUID returned by the list operation. Not valid or non existing data set id return an error response.")
@Timed
public void updateDataSet(@PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the data set to update") String dataSetId, @RequestBody DataSetMetadata dataSetMetadata) {
    if (dataSetMetadata != null && dataSetMetadata.getName() != null) {
        checkDataSetName(dataSetMetadata.getName());
    }
    final DistributedLock lock = dataSetMetadataRepository.createDatasetMetadataLock(dataSetId);
    lock.lock();
    try {
        DataSetMetadata metadataForUpdate = dataSetMetadataRepository.get(dataSetId);
        if (metadataForUpdate == null) {
            // No need to silently create the data set metadata: associated content will most likely not exist.
            throw new TDPException(DataSetErrorCodes.DATASET_DOES_NOT_EXIST, build().put("id", dataSetId));
        }
        LOG.debug("updateDataSet: {}", dataSetMetadata);
        publisher.publishEvent(new DatasetUpdatedEvent(dataSetMetadata));
        // 
        // Only part of the metadata can be updated, so the original dataset metadata is loaded and updated
        // 
        DataSetMetadata original = metadataBuilder.metadata().copy(metadataForUpdate).build();
        try {
            // update the name
            metadataForUpdate.setName(dataSetMetadata.getName());
            // update the sheet content (in case of a multi-sheet excel file)
            if (metadataForUpdate.getSchemaParserResult() != null) {
                Optional<Schema.SheetContent> sheetContentFound = metadataForUpdate.getSchemaParserResult().getSheetContents().stream().filter(sheetContent -> dataSetMetadata.getSheetName().equals(sheetContent.getName())).findFirst();
                if (sheetContentFound.isPresent()) {
                    List<ColumnMetadata> columnMetadatas = sheetContentFound.get().getColumnMetadatas();
                    if (metadataForUpdate.getRowMetadata() == null) {
                        metadataForUpdate.setRowMetadata(new RowMetadata(emptyList()));
                    }
                    metadataForUpdate.getRowMetadata().setColumns(columnMetadatas);
                }
                metadataForUpdate.setSheetName(dataSetMetadata.getSheetName());
                metadataForUpdate.setSchemaParserResult(null);
            }
            // Location updates
            metadataForUpdate.setLocation(dataSetMetadata.getLocation());
            // update parameters & encoding (so that user can change import parameters for CSV)
            metadataForUpdate.getContent().setParameters(dataSetMetadata.getContent().getParameters());
            metadataForUpdate.setEncoding(dataSetMetadata.getEncoding());
            // update limit
            final Optional<Long> newLimit = dataSetMetadata.getContent().getLimit();
            newLimit.ifPresent(limit -> metadataForUpdate.getContent().setLimit(limit));
            // Validate that the new data set metadata and removes the draft status
            final String formatFamilyId = dataSetMetadata.getContent().getFormatFamilyId();
            if (formatFamilyFactory.hasFormatFamily(formatFamilyId)) {
                FormatFamily format = formatFamilyFactory.getFormatFamily(formatFamilyId);
                try {
                    DraftValidator draftValidator = format.getDraftValidator();
                    DraftValidator.Result result = draftValidator.validate(dataSetMetadata);
                    if (result.isDraft()) {
                        // This is not an exception case: data set may remain a draft after update (although rather
                        // unusual)
                        LOG.warn("Data set #{} is still a draft after update.", dataSetId);
                        return;
                    }
                    // Data set metadata to update is no longer a draft
                    metadataForUpdate.setDraft(false);
                } catch (UnsupportedOperationException e) {
                // no need to validate draft here
                }
            }
            // update schema
            formatAnalyzer.update(original, metadataForUpdate);
            // save the result
            dataSetMetadataRepository.save(metadataForUpdate);
            // all good mate!! so send that to jms
            // Asks for a in depth schema analysis (for column type information).
            analyzeDataSet(dataSetId, true, singletonList(FormatAnalysis.class));
        } catch (TDPException e) {
            throw e;
        } catch (Exception e) {
            throw new TDPException(UNABLE_TO_CREATE_OR_UPDATE_DATASET, e);
        }
    } finally {
        lock.unlock();
    }
}
Also used : VolumeMetered(org.talend.dataprep.metrics.VolumeMetered) RequestParam(org.springframework.web.bind.annotation.RequestParam) ImportBuilder(org.talend.dataprep.api.dataset.Import.ImportBuilder) FormatFamilyFactory(org.talend.dataprep.schema.FormatFamilyFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) SortAndOrderHelper.getDataSetMetadataComparator(org.talend.dataprep.util.SortAndOrderHelper.getDataSetMetadataComparator) Collections.singletonList(java.util.Collections.singletonList) SemanticDomain(org.talend.dataprep.api.dataset.statistics.SemanticDomain) BeanConversionService(org.talend.dataprep.conversions.BeanConversionService) PipedInputStream(java.io.PipedInputStream) DistributedLock(org.talend.dataprep.lock.DistributedLock) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) DataprepBundle.message(org.talend.dataprep.i18n.DataprepBundle.message) UserData(org.talend.dataprep.api.user.UserData) TaskExecutor(org.springframework.core.task.TaskExecutor) MAX_STORAGE_MAY_BE_EXCEEDED(org.talend.dataprep.exception.error.DataSetErrorCodes.MAX_STORAGE_MAY_BE_EXCEEDED) DataSet(org.talend.dataprep.api.dataset.DataSet) LocalStoreLocation(org.talend.dataprep.api.dataset.location.LocalStoreLocation) FormatFamily(org.talend.dataprep.schema.FormatFamily) Resource(javax.annotation.Resource) Set(java.util.Set) DatasetUpdatedEvent(org.talend.dataprep.dataset.event.DatasetUpdatedEvent) RestController(org.springframework.web.bind.annotation.RestController) QuotaService(org.talend.dataprep.dataset.store.QuotaService) Stream(java.util.stream.Stream) StreamSupport.stream(java.util.stream.StreamSupport.stream) FlagNames(org.talend.dataprep.api.dataset.row.FlagNames) UNEXPECTED_CONTENT(org.talend.dataprep.exception.error.CommonErrorCodes.UNEXPECTED_CONTENT) Analyzers(org.talend.dataquality.common.inference.Analyzers) DataSetLocatorService(org.talend.dataprep.api.dataset.location.locator.DataSetLocatorService) Callable(java.util.concurrent.Callable) Schema(org.talend.dataprep.schema.Schema) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) DataSetLocationService(org.talend.dataprep.api.dataset.location.DataSetLocationService) AnalyzerService(org.talend.dataprep.quality.AnalyzerService) UserDataRepository(org.talend.dataprep.user.store.UserDataRepository) Markers(org.talend.dataprep.log.Markers) Api(io.swagger.annotations.Api) DraftValidator(org.talend.dataprep.schema.DraftValidator) HttpResponseContext(org.talend.dataprep.http.HttpResponseContext) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) IOException(java.io.IOException) PipedOutputStream(java.io.PipedOutputStream) FormatAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.FormatAnalysis) ContentAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.ContentAnalysis) SchemaAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.SchemaAnalysis) HttpStatus(org.springframework.http.HttpStatus) FilterService(org.talend.dataprep.api.filter.FilterService) Marker(org.slf4j.Marker) NullOutputStream(org.apache.commons.io.output.NullOutputStream) StatisticsAdapter(org.talend.dataprep.dataset.StatisticsAdapter) Timed(org.talend.dataprep.metrics.Timed) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) PathVariable(org.springframework.web.bind.annotation.PathVariable) DataSetMetadataBuilder(org.talend.dataprep.dataset.DataSetMetadataBuilder) URLDecoder(java.net.URLDecoder) DataSetErrorCodes(org.talend.dataprep.exception.error.DataSetErrorCodes) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) LoggerFactory(org.slf4j.LoggerFactory) SEMANTIC(org.talend.dataprep.quality.AnalyzerService.Analysis.SEMANTIC) ApiOperation(io.swagger.annotations.ApiOperation) UNABLE_TO_CREATE_OR_UPDATE_DATASET(org.talend.dataprep.exception.error.DataSetErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET) DataSetRow(org.talend.dataprep.api.dataset.row.DataSetRow) StrictlyBoundedInputStream(org.talend.dataprep.dataset.store.content.StrictlyBoundedInputStream) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) UNSUPPORTED_CONTENT(org.talend.dataprep.exception.error.DataSetErrorCodes.UNSUPPORTED_CONTENT) TimeToLive(org.talend.dataprep.cache.ContentCache.TimeToLive) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) Collections.emptyList(java.util.Collections.emptyList) PublicAPI(org.talend.dataprep.security.PublicAPI) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ContentCache(org.talend.dataprep.cache.ContentCache) INVALID_DATASET_NAME(org.talend.dataprep.exception.error.DataSetErrorCodes.INVALID_DATASET_NAME) List(java.util.List) Optional(java.util.Optional) Analyzer(org.talend.dataquality.common.inference.Analyzer) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) Pattern(java.util.regex.Pattern) Security(org.talend.dataprep.security.Security) Spliterator(java.util.Spliterator) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata) ComponentProperties(org.talend.dataprep.parameters.jsonschema.ComponentProperties) TDPException(org.talend.dataprep.exception.TDPException) JsonErrorCodeDescription(org.talend.dataprep.exception.json.JsonErrorCodeDescription) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) UNABLE_CREATE_DATASET(org.talend.dataprep.exception.error.DataSetErrorCodes.UNABLE_CREATE_DATASET) HashMap(java.util.HashMap) GET(org.springframework.web.bind.annotation.RequestMethod.GET) Import(org.talend.dataprep.api.dataset.Import) ExceptionContext.build(org.talend.daikon.exception.ExceptionContext.build) ExceptionContext(org.talend.daikon.exception.ExceptionContext) Charset(java.nio.charset.Charset) UpdateColumnParameters(org.talend.dataprep.dataset.service.api.UpdateColumnParameters) VersionService(org.talend.dataprep.api.service.info.VersionService) POST(org.springframework.web.bind.annotation.RequestMethod.POST) OutputStream(java.io.OutputStream) DataSetLocation(org.talend.dataprep.api.dataset.DataSetLocation) Logger(org.slf4j.Logger) LocaleContextHolder.getLocale(org.springframework.context.i18n.LocaleContextHolder.getLocale) UpdateDataSetCacheKey(org.talend.dataprep.dataset.service.cache.UpdateDataSetCacheKey) IOUtils(org.apache.commons.compress.utils.IOUtils) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Certification(org.talend.dataprep.api.dataset.DataSetGovernance.Certification) EncodingSupport(org.talend.dataprep.configuration.EncodingSupport) Comparator(java.util.Comparator) InputStream(java.io.InputStream) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) FormatAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.FormatAnalysis) FormatFamily(org.talend.dataprep.schema.FormatFamily) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) IOException(java.io.IOException) TDPException(org.talend.dataprep.exception.TDPException) TDPException(org.talend.dataprep.exception.TDPException) DistributedLock(org.talend.dataprep.lock.DistributedLock) DatasetUpdatedEvent(org.talend.dataprep.dataset.event.DatasetUpdatedEvent) DraftValidator(org.talend.dataprep.schema.DraftValidator) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 97 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project bisq-desktop by bisq-network.

the class WithdrawalView method setSelectColumnCellFactory.

private void setSelectColumnCellFactory() {
    selectColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper<>(addressListItem.getValue()));
    selectColumn.setCellFactory(new Callback<TableColumn<WithdrawalListItem, WithdrawalListItem>, TableCell<WithdrawalListItem, WithdrawalListItem>>() {

        @Override
        public TableCell<WithdrawalListItem, WithdrawalListItem> call(TableColumn<WithdrawalListItem, WithdrawalListItem> column) {
            return new TableCell<WithdrawalListItem, WithdrawalListItem>() {

                CheckBox checkBox = new AutoTooltipCheckBox();

                @Override
                public void updateItem(final WithdrawalListItem item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null && !empty) {
                        checkBox.setOnAction(e -> {
                            item.setSelected(checkBox.isSelected());
                            selectForWithdrawal(item);
                            // If all are selected we select useAllInputsRadioButton
                            if (observableList.size() == selectedItems.size()) {
                                inputsToggleGroup.selectToggle(useAllInputsRadioButton);
                            } else {
                                // We don't want to get deselected all when we activate the useCustomInputsRadioButton
                                // so we temporarily disable the listener
                                inputsToggleGroup.selectedToggleProperty().removeListener(inputsToggleGroupListener);
                                inputsToggleGroup.selectToggle(useCustomInputsRadioButton);
                                useAllInputs.set(false);
                                inputsToggleGroup.selectedToggleProperty().addListener(inputsToggleGroupListener);
                            }
                        });
                        setGraphic(checkBox);
                        checkBox.setSelected(item.isSelected());
                    } else {
                        checkBox.setOnAction(null);
                        setGraphic(null);
                    }
                }
            };
        }
    });
}
Also used : AutoTooltipCheckBox(bisq.desktop.components.AutoTooltipCheckBox) Button(javafx.scene.control.Button) Transaction(org.bitcoinj.core.Transaction) HyperlinkWithIcon(bisq.desktop.components.HyperlinkWithIcon) Coin(org.bitcoinj.core.Coin) VBox(javafx.scene.layout.VBox) StringUtils(org.apache.commons.lang3.StringUtils) BSFormatter(bisq.desktop.util.BSFormatter) ReadOnlyObjectWrapper(javafx.beans.property.ReadOnlyObjectWrapper) Res(bisq.core.locale.Res) TableView(javafx.scene.control.TableView) KeyParameter(org.spongycastle.crypto.params.KeyParameter) SortedList(javafx.collections.transformation.SortedList) AddressFormatException(org.bitcoinj.core.AddressFormatException) Popup(bisq.desktop.main.overlays.popups.Popup) AddressEntryException(bisq.core.btc.AddressEntryException) ClosedTradableManager(bisq.core.trade.closed.ClosedTradableManager) TextField(javafx.scene.control.TextField) WalletPasswordWindow(bisq.desktop.main.overlays.windows.WalletPasswordWindow) P2PService(bisq.network.p2p.P2PService) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) Set(java.util.Set) Collectors(java.util.stream.Collectors) FXML(javafx.fxml.FXML) BooleanProperty(javafx.beans.property.BooleanProperty) List(java.util.List) AddressEntry(bisq.core.btc.AddressEntry) WalletsSetup(bisq.core.btc.wallet.WalletsSetup) TradeManager(bisq.core.trade.TradeManager) RadioButton(javafx.scene.control.RadioButton) Preferences(bisq.core.user.Preferences) UserThread(bisq.common.UserThread) Optional(java.util.Optional) Toggle(javafx.scene.control.Toggle) ObservableList(javafx.collections.ObservableList) AwesomeIcon(de.jensd.fx.fontawesome.AwesomeIcon) NotNull(org.jetbrains.annotations.NotNull) Restrictions(bisq.core.btc.Restrictions) GUIUtil(bisq.desktop.util.GUIUtil) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) ActivatableView(bisq.desktop.common.view.ActivatableView) Wallet(org.bitcoinj.wallet.Wallet) FXCollections(javafx.collections.FXCollections) Tradable(bisq.core.trade.Tradable) FxmlView(bisq.desktop.common.view.FxmlView) TableColumn(javafx.scene.control.TableColumn) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) HashSet(java.util.HashSet) BalanceListener(bisq.core.btc.listeners.BalanceListener) TableCell(javafx.scene.control.TableCell) Callback(javafx.util.Callback) Tooltip(javafx.scene.control.Tooltip) Label(javafx.scene.control.Label) Trade(bisq.core.trade.Trade) FailedTradesManager(bisq.core.trade.failed.FailedTradesManager) CheckBox(javafx.scene.control.CheckBox) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) InsufficientMoneyException(org.bitcoinj.core.InsufficientMoneyException) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) ToggleGroup(javafx.scene.control.ToggleGroup) SelectionMode(javafx.scene.control.SelectionMode) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) BtcAddressValidator(bisq.desktop.util.validation.BtcAddressValidator) AutoTooltipCheckBox(bisq.desktop.components.AutoTooltipCheckBox) ChangeListener(javafx.beans.value.ChangeListener) CoinUtil(bisq.core.util.CoinUtil) TableCell(javafx.scene.control.TableCell) CheckBox(javafx.scene.control.CheckBox) AutoTooltipCheckBox(bisq.desktop.components.AutoTooltipCheckBox) TableColumn(javafx.scene.control.TableColumn)

Example 98 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project bisq-desktop by bisq-network.

the class PreferencesView method initializeDisplayCurrencies.

private void initializeDisplayCurrencies() {
    TitledGroupBg titledGroupBg = addTitledGroupBg(root, ++gridRow, 3, Res.get("setting.preferences.currenciesInList"), Layout.GROUP_DISTANCE);
    GridPane.setColumnSpan(titledGroupBg, 4);
    // noinspection unchecked
    preferredTradeCurrencyComboBox = addLabelComboBox(root, gridRow, Res.get("setting.preferences.prefCurrency"), Layout.FIRST_ROW_AND_GROUP_DISTANCE).second;
    preferredTradeCurrencyComboBox.setConverter(new StringConverter<TradeCurrency>() {

        @Override
        public String toString(TradeCurrency tradeCurrency) {
            // http://boschista.deviantart.com/journal/Cool-ASCII-Symbols-214218618
            return tradeCurrency.getDisplayPrefix() + tradeCurrency.getNameAndCode();
        }

        @Override
        public TradeCurrency fromString(String s) {
            return null;
        }
    });
    Tuple2<Label, ListView> fiatTuple = addLabelListView(root, ++gridRow, Res.get("setting.preferences.displayFiat"));
    GridPane.setValignment(fiatTuple.first, VPos.TOP);
    // noinspection unchecked
    fiatCurrenciesListView = fiatTuple.second;
    fiatCurrenciesListView.setMinHeight(2 * Layout.LIST_ROW_HEIGHT + 2);
    fiatCurrenciesListView.setPrefHeight(3 * Layout.LIST_ROW_HEIGHT + 2);
    Label placeholder = new AutoTooltipLabel(Res.get("setting.preferences.noFiat"));
    placeholder.setWrapText(true);
    fiatCurrenciesListView.setPlaceholder(placeholder);
    fiatCurrenciesListView.setCellFactory(new Callback<ListView<FiatCurrency>, ListCell<FiatCurrency>>() {

        @Override
        public ListCell<FiatCurrency> call(ListView<FiatCurrency> list) {
            return new ListCell<FiatCurrency>() {

                final Label label = new AutoTooltipLabel();

                final ImageView icon = ImageUtil.getImageViewById(ImageUtil.REMOVE_ICON);

                final Button removeButton = new AutoTooltipButton("", icon);

                final AnchorPane pane = new AnchorPane(label, removeButton);

                {
                    label.setLayoutY(5);
                    removeButton.setId("icon-button");
                    AnchorPane.setRightAnchor(removeButton, 0d);
                }

                @Override
                public void updateItem(final FiatCurrency item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null && !empty) {
                        label.setText(item.getNameAndCode());
                        removeButton.setOnAction(e -> {
                            if (item.equals(preferences.getPreferredTradeCurrency())) {
                                new Popup<>().warning(Res.get("setting.preferences.cannotRemovePrefCurrency")).show();
                            } else {
                                preferences.removeFiatCurrency(item);
                                if (!allFiatCurrencies.contains(item))
                                    allFiatCurrencies.add(item);
                            }
                        });
                        setGraphic(pane);
                    } else {
                        setGraphic(null);
                        removeButton.setOnAction(null);
                    }
                }
            };
        }
    });
    Tuple2<Label, ListView> cryptoCurrenciesTuple = addLabelListView(root, gridRow, Res.get("setting.preferences.displayAltcoins"));
    GridPane.setValignment(cryptoCurrenciesTuple.first, VPos.TOP);
    GridPane.setMargin(cryptoCurrenciesTuple.first, new Insets(0, 0, 0, 20));
    // noinspection unchecked
    cryptoCurrenciesListView = cryptoCurrenciesTuple.second;
    GridPane.setColumnIndex(cryptoCurrenciesTuple.first, 2);
    GridPane.setColumnIndex(cryptoCurrenciesListView, 3);
    cryptoCurrenciesListView.setMinHeight(2 * Layout.LIST_ROW_HEIGHT + 2);
    cryptoCurrenciesListView.setPrefHeight(3 * Layout.LIST_ROW_HEIGHT + 2);
    placeholder = new AutoTooltipLabel(Res.get("setting.preferences.noAltcoins"));
    placeholder.setWrapText(true);
    cryptoCurrenciesListView.setPlaceholder(placeholder);
    cryptoCurrenciesListView.setCellFactory(new Callback<ListView<CryptoCurrency>, ListCell<CryptoCurrency>>() {

        @Override
        public ListCell<CryptoCurrency> call(ListView<CryptoCurrency> list) {
            return new ListCell<CryptoCurrency>() {

                final Label label = new AutoTooltipLabel();

                final ImageView icon = ImageUtil.getImageViewById(ImageUtil.REMOVE_ICON);

                final Button removeButton = new AutoTooltipButton("", icon);

                final AnchorPane pane = new AnchorPane(label, removeButton);

                {
                    label.setLayoutY(5);
                    removeButton.setId("icon-button");
                    AnchorPane.setRightAnchor(removeButton, 0d);
                }

                @Override
                public void updateItem(final CryptoCurrency item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null && !empty) {
                        label.setText(item.getNameAndCode());
                        removeButton.setOnAction(e -> {
                            if (item.equals(preferences.getPreferredTradeCurrency())) {
                                new Popup<>().warning(Res.get("setting.preferences.cannotRemovePrefCurrency")).show();
                            } else {
                                preferences.removeCryptoCurrency(item);
                                if (!allCryptoCurrencies.contains(item))
                                    allCryptoCurrencies.add(item);
                            }
                        });
                        setGraphic(pane);
                    } else {
                        setGraphic(null);
                        removeButton.setOnAction(null);
                    }
                }
            };
        }
    });
    // noinspection unchecked
    fiatCurrenciesComboBox = addLabelComboBox(root, ++gridRow).second;
    fiatCurrenciesComboBox.setPromptText(Res.get("setting.preferences.addFiat"));
    fiatCurrenciesComboBox.setConverter(new StringConverter<FiatCurrency>() {

        @Override
        public String toString(FiatCurrency tradeCurrency) {
            return tradeCurrency.getNameAndCode();
        }

        @Override
        public FiatCurrency fromString(String s) {
            return null;
        }
    });
    Tuple2<Label, ComboBox> labelComboBoxTuple2 = addLabelComboBox(root, gridRow);
    // noinspection unchecked
    cryptoCurrenciesComboBox = labelComboBoxTuple2.second;
    GridPane.setColumnIndex(cryptoCurrenciesComboBox, 3);
    cryptoCurrenciesComboBox.setPromptText(Res.get("setting.preferences.addAltcoin"));
    cryptoCurrenciesComboBox.setConverter(new StringConverter<CryptoCurrency>() {

        @Override
        public String toString(CryptoCurrency tradeCurrency) {
            return tradeCurrency.getNameAndCode();
        }

        @Override
        public CryptoCurrency fromString(String s) {
            return null;
        }
    });
}
Also used : Button(javafx.scene.control.Button) Arrays(java.util.Arrays) Coin(org.bitcoinj.core.Coin) ListCell(javafx.scene.control.ListCell) Layout(bisq.desktop.util.Layout) StringUtils(org.apache.commons.lang3.StringUtils) BSFormatter(bisq.desktop.util.BSFormatter) InputTextField(bisq.desktop.components.InputTextField) ComboBox(javafx.scene.control.ComboBox) Res(bisq.core.locale.Res) BisqApp(bisq.desktop.app.BisqApp) Popup(bisq.desktop.main.overlays.popups.Popup) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) FormBuilder(bisq.desktop.util.FormBuilder) BlockChainExplorer(bisq.core.user.BlockChainExplorer) BaseCurrencyNetwork(bisq.core.btc.BaseCurrencyNetwork) Collectors(java.util.stream.Collectors) List(java.util.List) CryptoCurrency(bisq.core.locale.CryptoCurrency) DevEnv(bisq.common.app.DevEnv) AnchorPane(javafx.scene.layout.AnchorPane) AutoTooltipButton(bisq.desktop.components.AutoTooltipButton) Preferences(bisq.core.user.Preferences) UserThread(bisq.common.UserThread) CountryUtil(bisq.core.locale.CountryUtil) Activatable(bisq.desktop.common.model.Activatable) FeeService(bisq.core.provider.fee.FeeService) ObservableList(javafx.collections.ObservableList) TradeCurrency(bisq.core.locale.TradeCurrency) ListView(javafx.scene.control.ListView) FXCollections(javafx.collections.FXCollections) FiatCurrency(bisq.core.locale.FiatCurrency) FxmlView(bisq.desktop.common.view.FxmlView) Inject(javax.inject.Inject) Tuple2(bisq.common.util.Tuple2) Tuple3(bisq.common.util.Tuple3) Insets(javafx.geometry.Insets) Country(bisq.core.locale.Country) VPos(javafx.geometry.VPos) CurrencyUtil(bisq.core.locale.CurrencyUtil) Callback(javafx.util.Callback) TitledGroupBg(bisq.desktop.components.TitledGroupBg) GridPane(javafx.scene.layout.GridPane) Label(javafx.scene.control.Label) CheckBox(javafx.scene.control.CheckBox) BisqEnvironment(bisq.core.app.BisqEnvironment) StringConverter(javafx.util.StringConverter) TimeUnit(java.util.concurrent.TimeUnit) ImageUtil(bisq.desktop.util.ImageUtil) ImageView(javafx.scene.image.ImageView) LanguageUtil(bisq.core.locale.LanguageUtil) ActivatableViewAndModel(bisq.desktop.common.view.ActivatableViewAndModel) ChangeListener(javafx.beans.value.ChangeListener) Insets(javafx.geometry.Insets) ListCell(javafx.scene.control.ListCell) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) Label(javafx.scene.control.Label) CryptoCurrency(bisq.core.locale.CryptoCurrency) ListView(javafx.scene.control.ListView) Button(javafx.scene.control.Button) AutoTooltipButton(bisq.desktop.components.AutoTooltipButton) FiatCurrency(bisq.core.locale.FiatCurrency) ImageView(javafx.scene.image.ImageView) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) AnchorPane(javafx.scene.layout.AnchorPane) TradeCurrency(bisq.core.locale.TradeCurrency) ComboBox(javafx.scene.control.ComboBox) AutoTooltipButton(bisq.desktop.components.AutoTooltipButton) TitledGroupBg(bisq.desktop.components.TitledGroupBg)

Example 99 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project syncope by apache.

the class GroupDataBinderImpl method update.

@Override
public PropagationByResource update(final Group toBeUpdated, final GroupPatch groupPatch) {
    // Re-merge any pending change from workflow tasks
    Group group = groupDAO.save(toBeUpdated);
    PropagationByResource propByRes = new PropagationByResource();
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    AnyUtils anyUtils = anyUtilsFactory.getInstance(AnyTypeKind.GROUP);
    // fetch connObjectKeys before update
    Map<String, String> oldConnObjectKeys = getConnObjectKeys(group, anyUtils);
    // realm
    setRealm(group, groupPatch);
    // name
    if (groupPatch.getName() != null && StringUtils.isNotBlank(groupPatch.getName().getValue())) {
        propByRes.addAll(ResourceOperation.UPDATE, groupDAO.findAllResourceKeys(group.getKey()));
        group.setName(groupPatch.getName().getValue());
    }
    // owner
    if (groupPatch.getUserOwner() != null) {
        group.setUserOwner(groupPatch.getUserOwner().getValue() == null ? null : userDAO.find(groupPatch.getUserOwner().getValue()));
    }
    if (groupPatch.getGroupOwner() != null) {
        group.setGroupOwner(groupPatch.getGroupOwner().getValue() == null ? null : groupDAO.find(groupPatch.getGroupOwner().getValue()));
    }
    // attributes and resources
    propByRes.merge(fill(group, groupPatch, anyUtils, scce));
    // check if some connObjectKey was changed by the update above
    Map<String, String> newConnObjectKeys = getConnObjectKeys(group, anyUtils);
    oldConnObjectKeys.entrySet().stream().filter(entry -> newConnObjectKeys.containsKey(entry.getKey()) && !entry.getValue().equals(newConnObjectKeys.get(entry.getKey()))).forEach(entry -> {
        propByRes.addOldConnObjectKey(entry.getKey(), entry.getValue());
        propByRes.add(ResourceOperation.UPDATE, entry.getKey());
    });
    group = groupDAO.save(group);
    // dynamic membership
    if (groupPatch.getUDynMembershipCond() == null) {
        if (group.getUDynMembership() != null) {
            group.getUDynMembership().setGroup(null);
            group.setUDynMembership(null);
            groupDAO.clearUDynMembers(group);
        }
    } else {
        setDynMembership(group, anyTypeDAO.findUser(), groupPatch.getUDynMembershipCond());
    }
    for (Iterator<? extends ADynGroupMembership> itor = group.getADynMemberships().iterator(); itor.hasNext(); ) {
        ADynGroupMembership memb = itor.next();
        memb.setGroup(null);
        itor.remove();
    }
    groupDAO.clearADynMembers(group);
    for (Map.Entry<String, String> entry : groupPatch.getADynMembershipConds().entrySet()) {
        AnyType anyType = anyTypeDAO.find(entry.getKey());
        if (anyType == null) {
            LOG.warn("Ignoring invalid {}: {}", AnyType.class.getSimpleName(), entry.getKey());
        } else {
            setDynMembership(group, anyType, entry.getValue());
        }
    }
    // type extensions
    for (TypeExtensionTO typeExtTO : groupPatch.getTypeExtensions()) {
        AnyType anyType = anyTypeDAO.find(typeExtTO.getAnyType());
        if (anyType == null) {
            LOG.warn("Ignoring invalid {}: {}", AnyType.class.getSimpleName(), typeExtTO.getAnyType());
        } else {
            TypeExtension typeExt = group.getTypeExtension(anyType).orElse(null);
            if (typeExt == null) {
                typeExt = entityFactory.newEntity(TypeExtension.class);
                typeExt.setAnyType(anyType);
                typeExt.setGroup(group);
                group.add(typeExt);
            }
            // add all classes contained in the TO
            for (String name : typeExtTO.getAuxClasses()) {
                AnyTypeClass anyTypeClass = anyTypeClassDAO.find(name);
                if (anyTypeClass == null) {
                    LOG.warn("Ignoring invalid {}: {}", AnyTypeClass.class.getSimpleName(), name);
                } else {
                    typeExt.add(anyTypeClass);
                }
            }
            // remove all classes not contained in the TO
            typeExt.getAuxClasses().removeIf(anyTypeClass -> !typeExtTO.getAuxClasses().contains(anyTypeClass.getKey()));
            // only consider non-empty type extensions
            if (typeExt.getAuxClasses().isEmpty()) {
                group.getTypeExtensions().remove(typeExt);
                typeExt.setGroup(null);
            }
        }
    }
    // remove all type extensions not contained in the TO
    group.getTypeExtensions().removeIf(typeExt -> !groupPatch.getTypeExtension(typeExt.getAnyType().getKey()).isPresent());
    // Throw composite exception if there is at least one element set in the composing exceptions
    if (scce.hasExceptions()) {
        throw scce;
    }
    return propByRes;
}
Also used : SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Realm(org.apache.syncope.core.persistence.api.entity.Realm) UDynGroupMembership(org.apache.syncope.core.persistence.api.entity.user.UDynGroupMembership) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Entity(org.apache.syncope.core.persistence.api.entity.Entity) ResourceOperation(org.apache.syncope.common.lib.types.ResourceOperation) StringUtils(org.apache.commons.lang3.StringUtils) GroupDataBinder(org.apache.syncope.core.provisioning.api.data.GroupDataBinder) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) GroupPatch(org.apache.syncope.common.lib.patch.GroupPatch) DerSchema(org.apache.syncope.core.persistence.api.entity.DerSchema) Map(java.util.Map) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) SearchCondConverter(org.apache.syncope.core.persistence.api.search.SearchCondConverter) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass) TypeExtension(org.apache.syncope.core.persistence.api.entity.group.TypeExtension) Iterator(java.util.Iterator) SearchCond(org.apache.syncope.core.persistence.api.dao.search.SearchCond) User(org.apache.syncope.core.persistence.api.entity.user.User) ADynGroupMembership(org.apache.syncope.core.persistence.api.entity.anyobject.ADynGroupMembership) GroupTO(org.apache.syncope.common.lib.to.GroupTO) Collectors(java.util.stream.Collectors) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) DynGroupMembership(org.apache.syncope.core.persistence.api.entity.DynGroupMembership) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) List(java.util.List) Component(org.springframework.stereotype.Component) TypeExtensionTO(org.apache.syncope.common.lib.to.TypeExtensionTO) Group(org.apache.syncope.core.persistence.api.entity.group.Group) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) Collections(java.util.Collections) Any(org.apache.syncope.core.persistence.api.entity.Any) Transactional(org.springframework.transaction.annotation.Transactional) Group(org.apache.syncope.core.persistence.api.entity.group.Group) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) TypeExtension(org.apache.syncope.core.persistence.api.entity.group.TypeExtension) ADynGroupMembership(org.apache.syncope.core.persistence.api.entity.anyobject.ADynGroupMembership) TypeExtensionTO(org.apache.syncope.common.lib.to.TypeExtensionTO) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) HashMap(java.util.HashMap) Map(java.util.Map) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass)

Example 100 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project bullet-storm by yahoo.

the class JoinBoltTest method testGroupBy.

@Test
public void testGroupBy() {
    final int entries = 16;
    BulletConfig bulletConfig = GroupByTest.makeConfiguration(entries);
    GroupBy groupBy = GroupByTest.makeGroupBy(bulletConfig, singletonMap("fieldA", "A"), entries, AggregationUtils.makeGroupOperation(COUNT, null, "cnt"), AggregationUtils.makeGroupOperation(SUM, "fieldB", "sumB"));
    IntStream.range(0, 256).mapToObj(i -> RecordBox.get().add("fieldA", i % 16).add("fieldB", i / 16).getRecord()).forEach(groupBy::consume);
    byte[] first = groupBy.getData();
    groupBy = GroupByTest.makeGroupBy(bulletConfig, singletonMap("fieldA", "A"), entries, AggregationUtils.makeGroupOperation(COUNT, null, "cnt"), AggregationUtils.makeGroupOperation(SUM, "fieldB", "sumB"));
    IntStream.range(256, 1024).mapToObj(i -> RecordBox.get().add("fieldA", i % 16).add("fieldB", i / 16).getRecord()).forEach(groupBy::consume);
    byte[] second = groupBy.getData();
    // Send generated data to JoinBolt
    bolt = new DonableJoinBolt(config, 2, true);
    setup(bolt);
    List<GroupOperation> operations = asList(new GroupOperation(COUNT, null, "cnt"), new GroupOperation(SUM, "fieldB", "sumB"));
    String queryString = makeGroupFilterQuery("ts", singletonList("1"), EQUALS, GROUP, entries, operations, Pair.of("fieldA", "A"));
    Tuple query = TupleUtils.makeIDTuple(TupleClassifier.Type.QUERY_TUPLE, "42", queryString, EMPTY);
    bolt.execute(query);
    sendRawByteTuplesTo(bolt, "42", asList(first, second));
    Tuple tick = TupleUtils.makeTuple(TupleClassifier.Type.TICK_TUPLE);
    bolt.execute(tick);
    for (int i = 0; i < BulletStormConfig.DEFAULT_JOIN_BOLT_QUERY_TICK_TIMEOUT - 1; ++i) {
        bolt.execute(tick);
        Assert.assertEquals(collector.getEmittedCount(), 0);
    }
    bolt.execute(tick);
    Assert.assertEquals(collector.getEmittedCount(), 2);
    String response = (String) collector.getMthElementFromNthTupleEmittedTo(TopologyConstants.RESULT_STREAM, 1, 1).get();
    JsonParser parser = new JsonParser();
    JsonObject actual = parser.parse(response).getAsJsonObject();
    JsonArray actualRecords = actual.get(Clip.RECORDS_KEY).getAsJsonArray();
    Assert.assertEquals(actualRecords.size(), 16);
}
Also used : JsonObject(com.google.gson.JsonObject) GROUP(com.yahoo.bullet.parsing.Aggregation.Type.GROUP) COUNT(com.yahoo.bullet.aggregations.grouping.GroupOperation.GroupOperationType.COUNT) TopK(com.yahoo.bullet.aggregations.TopK) BulletError(com.yahoo.bullet.common.BulletError) Concept(com.yahoo.bullet.result.Meta.Concept) ParsingError(com.yahoo.bullet.parsing.ParsingError) Test(org.testng.annotations.Test) RecordBox(com.yahoo.bullet.result.RecordBox) ErrorType(com.yahoo.sketches.frequencies.ErrorType) EQUALS(com.yahoo.bullet.parsing.Clause.Operation.EQUALS) PROBABILITY_FIELD(com.yahoo.bullet.aggregations.sketches.QuantileSketch.PROBABILITY_FIELD) Collections.singletonList(java.util.Collections.singletonList) CustomCollector(com.yahoo.bullet.storm.testing.CustomCollector) Pair(org.apache.commons.lang3.tuple.Pair) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Metadata(com.yahoo.bullet.pubsub.Metadata) Mockito.doReturn(org.mockito.Mockito.doReturn) GroupData(com.yahoo.bullet.aggregations.grouping.GroupData) QueryUtils.makeAggregationQuery(com.yahoo.bullet.parsing.QueryUtils.makeAggregationQuery) GroupBy(com.yahoo.bullet.aggregations.GroupBy) ComponentUtils(com.yahoo.bullet.storm.testing.ComponentUtils) BulletRecord(com.yahoo.bullet.record.BulletRecord) AggregationUtils(com.yahoo.bullet.parsing.AggregationUtils) BeforeMethod(org.testng.annotations.BeforeMethod) GroupByTest(com.yahoo.bullet.aggregations.GroupByTest) Fields(org.apache.storm.tuple.Fields) CustomTopologyContext(com.yahoo.bullet.storm.testing.CustomTopologyContext) SlidingRecord(com.yahoo.bullet.windowing.SlidingRecord) DistributionTest(com.yahoo.bullet.aggregations.DistributionTest) Serializable(java.io.Serializable) RateLimitError(com.yahoo.bullet.querying.RateLimitError) GroupOperation(com.yahoo.bullet.aggregations.grouping.GroupOperation) Querier(com.yahoo.bullet.querying.Querier) JsonArray(com.google.gson.JsonArray) List(java.util.List) Distribution(com.yahoo.bullet.aggregations.Distribution) NEGATIVE_INFINITY_START(com.yahoo.bullet.aggregations.sketches.QuantileSketch.NEGATIVE_INFINITY_START) BulletConfig(com.yahoo.bullet.common.BulletConfig) AdditionalAnswers.returnsElementsOf(org.mockito.AdditionalAnswers.returnsElementsOf) Window(com.yahoo.bullet.parsing.Window) IRichBolt(org.apache.storm.topology.IRichBolt) END_EXCLUSIVE(com.yahoo.bullet.aggregations.sketches.QuantileSketch.END_EXCLUSIVE) TupleUtils(com.yahoo.bullet.storm.testing.TupleUtils) IntStream(java.util.stream.IntStream) TopKTest(com.yahoo.bullet.aggregations.TopKTest) Setter(lombok.Setter) TestHelpers.assertJSONEquals(com.yahoo.bullet.storm.testing.TestHelpers.assertJSONEquals) SerializerDeserializer(com.yahoo.bullet.common.SerializerDeserializer) HashMap(java.util.HashMap) JsonParser(com.google.gson.JsonParser) Mockito.spy(org.mockito.Mockito.spy) TestHelpers.getListBytes(com.yahoo.bullet.storm.testing.TestHelpers.getListBytes) Clip(com.yahoo.bullet.result.Clip) SUM(com.yahoo.bullet.aggregations.grouping.GroupOperation.GroupOperationType.SUM) SEPARATOR(com.yahoo.bullet.aggregations.sketches.QuantileSketch.SEPARATOR) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Tuple(org.apache.storm.tuple.Tuple) Assert(org.testng.Assert) CountDistinct(com.yahoo.bullet.aggregations.CountDistinct) AggregationUtils.makeAttributes(com.yahoo.bullet.parsing.AggregationUtils.makeAttributes) Collections.singletonMap(java.util.Collections.singletonMap) TOP_K(com.yahoo.bullet.parsing.Aggregation.Type.TOP_K) Aggregation(com.yahoo.bullet.parsing.Aggregation) Meta(com.yahoo.bullet.result.Meta) COUNT_FIELD(com.yahoo.bullet.aggregations.sketches.QuantileSketch.COUNT_FIELD) POSITIVE_INFINITY_END(com.yahoo.bullet.aggregations.sketches.QuantileSketch.POSITIVE_INFINITY_END) COUNT_DISTINCT(com.yahoo.bullet.parsing.Aggregation.Type.COUNT_DISTINCT) CustomOutputFieldsDeclarer(com.yahoo.bullet.storm.testing.CustomOutputFieldsDeclarer) START_INCLUSIVE(com.yahoo.bullet.aggregations.sketches.QuantileSketch.START_INCLUSIVE) CountDistinctTest(com.yahoo.bullet.aggregations.CountDistinctTest) RAW(com.yahoo.bullet.parsing.Aggregation.Type.RAW) DISTRIBUTION(com.yahoo.bullet.parsing.Aggregation.Type.DISTRIBUTION) QueryUtils.makeGroupFilterQuery(com.yahoo.bullet.parsing.QueryUtils.makeGroupFilterQuery) RANGE_FIELD(com.yahoo.bullet.aggregations.sketches.QuantileSketch.RANGE_FIELD) GroupBy(com.yahoo.bullet.aggregations.GroupBy) JsonObject(com.google.gson.JsonObject) JsonArray(com.google.gson.JsonArray) BulletConfig(com.yahoo.bullet.common.BulletConfig) GroupOperation(com.yahoo.bullet.aggregations.grouping.GroupOperation) Tuple(org.apache.storm.tuple.Tuple) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test) GroupByTest(com.yahoo.bullet.aggregations.GroupByTest) DistributionTest(com.yahoo.bullet.aggregations.DistributionTest) TopKTest(com.yahoo.bullet.aggregations.TopKTest) CountDistinctTest(com.yahoo.bullet.aggregations.CountDistinctTest)

Aggregations

List (java.util.List)44 Map (java.util.Map)42 ArrayList (java.util.ArrayList)41 StringUtils (org.apache.commons.lang3.StringUtils)38 Collectors (java.util.stream.Collectors)37 HashMap (java.util.HashMap)33 IOException (java.io.IOException)27 Set (java.util.Set)25 HashSet (java.util.HashSet)22 LoggerFactory (org.slf4j.LoggerFactory)22 Pair (org.apache.commons.lang3.tuple.Pair)20 Logger (org.slf4j.Logger)20 Optional (java.util.Optional)19 Collections (java.util.Collections)17 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)17 java.util (java.util)15 Arrays.asList (java.util.Arrays.asList)14 Collection (java.util.Collection)14 Stream (java.util.stream.Stream)14 Arrays (java.util.Arrays)12