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);
}
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();
}
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;
}
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;
}
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;
}
Aggregations