Search in sources :

Example 26 with EMPTY

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

the class ZKSessionLock method processLockWaiters.

/**
 * Check Lock Owner Phase 2 : check all lock waiters to get current owner and wait for ownership if necessary.
 *
 * @param lockWatcher
 *          lock watcher.
 * @param wait
 *          whether to wait for ownership.
 * @param getChildrenRc
 *          result of getting all lock waiters
 * @param children
 *          current lock waiters.
 * @param promise
 *          promise to satisfy with current lock owner.
 */
private void processLockWaiters(final LockWatcher lockWatcher, final boolean wait, final int getChildrenRc, final List<String> children, final CompletableFuture<String> promise) {
    executeLockAction(lockWatcher.epoch, new LockAction() {

        @Override
        public void execute() {
            if (!lockState.inState(State.PREPARED)) {
                // e.g. lock closed or session expired after prepared
                promise.completeExceptionally(new LockStateChangedException(lockPath, lockId, State.PREPARED, lockState.getState()));
                return;
            }
            if (KeeperException.Code.OK.intValue() != getChildrenRc) {
                promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(getChildrenRc)));
                return;
            }
            if (children.isEmpty()) {
                LOG.error("Error, member list is empty for lock {}.", lockPath);
                promise.completeExceptionally(new UnexpectedException("Empty member list for lock " + lockPath));
                return;
            }
            // sort the children
            Collections.sort(children, MEMBER_COMPARATOR);
            final String cid = currentId;
            final int memberIndex = children.indexOf(cid);
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} is the number {} member in the list.", cid, memberIndex);
            }
            // If we hold the lock
            if (memberIndex == 0) {
                LOG.info("{} acquired the lock {}.", cid, lockPath);
                claimOwnership(lockWatcher.epoch);
                promise.complete(cid);
            } else if (memberIndex > 0) {
                // we are in the member list but we didn't hold the lock
                // get ownership of current owner
                asyncParseClientID(zk, lockPath, children.get(0)).whenComplete(new FutureEventListener<Pair<String, Long>>() {

                    @Override
                    public void onSuccess(Pair<String, Long> currentOwner) {
                        watchLockOwner(lockWatcher, wait, cid, children.get(memberIndex - 1), children.get(0), currentOwner, promise);
                    }

                    @Override
                    public void onFailure(final Throwable cause) {
                        // ensure promise is satisfied in lock thread
                        executeLockAction(lockWatcher.epoch, new LockAction() {

                            @Override
                            public void execute() {
                                promise.completeExceptionally(cause);
                            }

                            @Override
                            public String getActionName() {
                                return "handleFailureOnParseClientID(lockPath=" + lockPath + ")";
                            }
                        }, promise);
                    }
                });
            } else {
                LOG.error("Member {} doesn't exist in the members list {} for lock {}.", new Object[] { cid, children, lockPath });
                promise.completeExceptionally(new UnexpectedException("Member " + cid + " doesn't exist in member list " + children + " for lock " + lockPath));
            }
        }

        @Override
        public String getActionName() {
            return "processLockWaiters(rc=" + getChildrenRc + ", waiters=" + children + ")";
        }
    }, promise);
}
Also used : UnexpectedException(org.apache.distributedlog.exceptions.UnexpectedException) Pair(org.apache.commons.lang3.tuple.Pair)

Example 27 with EMPTY

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

the class CS6DiskRendererService method execWaitAndCollect.

@Override
public String execWaitAndCollect(String[] args, File currentWorkingDirectory) {
    initialize();
    Csound csound = new Csound();
    blueCallbackWrapper = new BlueCallbackWrapper(csound);
    blueCallbackWrapper.SetMessageCallback();
    StrBuilder buffer = new StrBuilder();
    blueCallbackWrapper.setStringBuffer(buffer);
    CsoundArgVList argsList = new CsoundArgVList();
    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("\"") && args[i].endsWith("\"")) {
            args[i] = args[i].substring(1, args[i].length() - 1);
        }
        argsList.Append(args[i]);
    }
    if (currentWorkingDirectory != null) {
        String sfdir = "--env:SFDIR=" + currentWorkingDirectory.getAbsolutePath();
        argsList.Append(sfdir);
    }
    int retVal = csound.Compile(argsList.argc(), argsList.argv());
    if (retVal != 0) {
        blueCallbackWrapper.setStringBuffer(null);
        csound.Stop();
        csound.Cleanup();
        csound.SetMessageCallback(null);
        csound.Reset();
        return buffer.toString();
    }
    while (csound.PerformKsmps() == 0 && keepRunning) {
    // empty
    }
    csound.Stop();
    csound.Cleanup();
    csound.SetMessageCallback(null);
    csound.Reset();
    keepRunning = false;
    blueCallbackWrapper.setStringBuffer(null);
    return buffer.toString();
}
Also used : Csound(csnd6.Csound) StrBuilder(org.apache.commons.lang3.text.StrBuilder) CsoundArgVList(csnd6.CsoundArgVList)

Example 28 with EMPTY

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

the class Utils method tokenize.

/**
 * Split string x in tokens. Effectively just a friendly wrapper around StrTokenizer.
 * Use *single* quotes for avoiding splitting.
 */
public static ArrayList<String> tokenize(String x, String delimiterString) {
    if (x == null) {
        return null;
    }
    // This is a hack to allow empty tokens to be passed at the command line.
    // An empty
    x = x.replace("''", "' '");
    // See also http://stackoverflow.com/questions/38161437/inconsistent-behaviour-of-strtokenizer-to-split-string
    StrTokenizer str = new StrTokenizer(x);
    str.setTrimmerMatcher(StrMatcher.spaceMatcher());
    str.setDelimiterString(delimiterString);
    str.setQuoteChar('\'');
    // str.setIgnoreEmptyTokens(false);
    ArrayList<String> tokens = (ArrayList<String>) str.getTokenList();
    for (int i = 0; i < tokens.size(); i++) {
        String tok = tokens.get(i).trim();
        tokens.set(i, tok);
    }
    return tokens;
}
Also used : ArrayList(java.util.ArrayList) StrTokenizer(org.apache.commons.lang3.text.StrTokenizer)

Example 29 with EMPTY

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

the class TextUtils method isSplitSelect.

/**
 * Helper method to check for string that matches ONLY a comma-separated string of numeric values.
 *
 * @param arg the string to test.
 * @return whether the string matches
 */
public static boolean isSplitSelect(@Nonnull String arg) {
    String cleaned = SPLIT_SELECT_ALLOWED.negate().collapseFrom(arg, ' ');
    int numberOfCollapsed = arg.length() - cleaned.length();
    if (numberOfCollapsed >= 2) {
        // when enough changes happen, it's not a split select
        return false;
    }
    AtomicBoolean empty = new AtomicBoolean(true);
    boolean allDigits = splitSelectStream(arg).peek(__ -> empty.set(false)).allMatch(NumberUtils::isDigits);
    return !empty.get() && allDigits;
}
Also used : java.util(java.util) Member(net.dv8tion.jda.core.entities.Member) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtils(org.apache.commons.lang3.StringUtils) Message(net.dv8tion.jda.core.entities.Message) Matcher(java.util.regex.Matcher) BotConstants(fredboat.shared.constant.BotConstants) Splitter(com.google.common.base.Splitter) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) BotController(fredboat.main.BotController) CentralMessaging(fredboat.messaging.CentralMessaging) CharMatcher(com.google.common.base.CharMatcher) DecimalFormat(java.text.DecimalFormat) RandomStringGenerator(org.apache.commons.text.RandomStringGenerator) Streams(com.google.common.collect.Streams) InsufficientPermissionException(net.dv8tion.jda.core.exceptions.InsufficientPermissionException) CharacterPredicates(org.apache.commons.text.CharacterPredicates) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) Context(fredboat.messaging.internal.Context) DateTimeFormatter(java.time.format.DateTimeFormatter) NumberUtils(org.apache.commons.lang3.math.NumberUtils) MessagingException(fredboat.commandmeta.MessagingException) Metrics(fredboat.feature.metrics.Metrics) Pattern(java.util.regex.Pattern) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NumberUtils(org.apache.commons.lang3.math.NumberUtils)

Example 30 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project incubator-pulsar by apache.

the class PersistentTopic method subscribe.

@Override
public CompletableFuture<Consumer> subscribe(final ServerCnx cnx, String subscriptionName, long consumerId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageId startMessageId, Map<String, String> metadata, boolean readCompacted, InitialPosition initialPosition) {
    final CompletableFuture<Consumer> future = new CompletableFuture<>();
    if (readCompacted && !(subType == SubType.Failover || subType == SubType.Exclusive)) {
        future.completeExceptionally(new NotAllowedException("readCompacted only allowed on failover or exclusive subscriptions"));
        return future;
    }
    if (isBlank(subscriptionName)) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Empty subscription name", topic);
        }
        future.completeExceptionally(new NamingException("Empty subscription name"));
        return future;
    }
    if (hasBatchMessagePublished && !cnx.isBatchMessageCompatibleVersion()) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Consumer doesn't support batch-message {}", topic, subscriptionName);
        }
        future.completeExceptionally(new UnsupportedVersionException("Consumer doesn't support batch-message"));
        return future;
    }
    if (subscriptionName.startsWith(replicatorPrefix) || subscriptionName.equals(DEDUPLICATION_CURSOR_NAME)) {
        log.warn("[{}] Failed to create subscription for {}", topic, subscriptionName);
        future.completeExceptionally(new NamingException("Subscription with reserved subscription name attempted"));
        return future;
    }
    lock.readLock().lock();
    try {
        if (isFenced) {
            log.warn("[{}] Attempting to subscribe to a fenced topic", topic);
            future.completeExceptionally(new TopicFencedException("Topic is temporarily unavailable"));
            return future;
        }
        USAGE_COUNT_UPDATER.incrementAndGet(this);
        if (log.isDebugEnabled()) {
            log.debug("[{}] [{}] [{}] Added consumer -- count: {}", topic, subscriptionName, consumerName, USAGE_COUNT_UPDATER.get(this));
        }
    } finally {
        lock.readLock().unlock();
    }
    CompletableFuture<? extends Subscription> subscriptionFuture = // 
    isDurable ? // 
    getDurableSubscription(subscriptionName, initialPosition) : getNonDurableSubscription(subscriptionName, startMessageId);
    int maxUnackedMessages = isDurable ? brokerService.pulsar().getConfiguration().getMaxUnackedMessagesPerConsumer() : 0;
    subscriptionFuture.thenAccept(subscription -> {
        try {
            Consumer consumer = new Consumer(subscription, subType, topic, consumerId, priorityLevel, consumerName, maxUnackedMessages, cnx, cnx.getRole(), metadata, readCompacted, initialPosition);
            subscription.addConsumer(consumer);
            if (!cnx.isActive()) {
                consumer.close();
                if (log.isDebugEnabled()) {
                    log.debug("[{}] [{}] [{}] Subscribe failed -- count: {}", topic, subscriptionName, consumer.consumerName(), USAGE_COUNT_UPDATER.get(PersistentTopic.this));
                }
                future.completeExceptionally(new BrokerServiceException("Connection was closed while the opening the cursor "));
            } else {
                log.info("[{}][{}] Created new subscription for {}", topic, subscriptionName, consumerId);
                future.complete(consumer);
            }
        } catch (BrokerServiceException e) {
            if (e instanceof ConsumerBusyException) {
                log.warn("[{}][{}] Consumer {} {} already connected", topic, subscriptionName, consumerId, consumerName);
            } else if (e instanceof SubscriptionBusyException) {
                log.warn("[{}][{}] {}", topic, subscriptionName, e.getMessage());
            }
            USAGE_COUNT_UPDATER.decrementAndGet(PersistentTopic.this);
            future.completeExceptionally(e);
        }
    }).exceptionally(ex -> {
        log.warn("[{}] Failed to create subscription for {}: ", topic, subscriptionName, ex.getMessage());
        USAGE_COUNT_UPDATER.decrementAndGet(PersistentTopic.this);
        future.completeExceptionally(new PersistenceException(ex));
        return null;
    });
    return future;
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) Topic(org.apache.pulsar.broker.service.Topic) LedgerInfo(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.LedgerInfo) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) AdminResource(org.apache.pulsar.broker.admin.AdminResource) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) SchemaVersion(org.apache.pulsar.common.schema.SchemaVersion) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) UnsupportedVersionException(org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) LoggerFactory(org.slf4j.LoggerFactory) ObjectObjectHashMap(com.carrotsearch.hppc.ObjectObjectHashMap) ProducerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ProducerBusyException) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) StatsOutputStream(org.apache.pulsar.utils.StatsOutputStream) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ReplicationMetrics(org.apache.pulsar.broker.stats.ReplicationMetrics) ManagedLedgerAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerAlreadyClosedException) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) BrokerService(org.apache.pulsar.broker.service.BrokerService) ReplicatorStats(org.apache.pulsar.common.policies.data.ReplicatorStats) IndividualDeletedEntries(org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries) NamespaceStats(org.apache.pulsar.broker.stats.NamespaceStats) Sets(com.google.common.collect.Sets) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) ServerCnx(org.apache.pulsar.broker.service.ServerCnx) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) TopicTerminatedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicTerminatedException) SchemaData(org.apache.pulsar.common.schema.SchemaData) Optional(java.util.Optional) ManagedLedgerTerminatedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerTerminatedException) PersistentTopicInternalStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) PublisherStats(org.apache.pulsar.common.policies.data.PublisherStats) Subscription(org.apache.pulsar.broker.service.Subscription) TopicName(org.apache.pulsar.common.naming.TopicName) CursorStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BacklogQuota(org.apache.pulsar.common.policies.data.BacklogQuota) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Consumer(org.apache.pulsar.broker.service.Consumer) TerminateCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.TerminateCallback) TopicClosedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicClosedException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) DateFormatter(org.apache.pulsar.common.util.DateFormatter) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) CompactedTopicImpl(org.apache.pulsar.compaction.CompactedTopicImpl) FastThreadLocal(io.netty.util.concurrent.FastThreadLocal) ClusterReplicationMetrics(org.apache.pulsar.broker.stats.ClusterReplicationMetrics) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) Logger(org.slf4j.Logger) SubType(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) KeeperException(org.apache.zookeeper.KeeperException) CompactedTopic(org.apache.pulsar.compaction.CompactedTopic) BrokerServiceException(org.apache.pulsar.broker.service.BrokerServiceException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) MoreObjects(com.google.common.base.MoreObjects) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Producer(org.apache.pulsar.broker.service.Producer) TopicFencedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) Policies(org.apache.pulsar.common.policies.data.Policies) TopicBusyException(org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException) MessageId(org.apache.pulsar.client.api.MessageId) Compactor(org.apache.pulsar.compaction.Compactor) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) Codec(org.apache.pulsar.common.util.Codec) ConsumerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) Replicator(org.apache.pulsar.broker.service.Replicator) ConsumerStats(org.apache.pulsar.common.policies.data.ConsumerStats) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) Collections(java.util.Collections) TopicFencedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) BrokerServiceException(org.apache.pulsar.broker.service.BrokerServiceException) CompletableFuture(java.util.concurrent.CompletableFuture) ConsumerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) Consumer(org.apache.pulsar.broker.service.Consumer) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) UnsupportedVersionException(org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException)

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