use of java.util.NoSuchElementException in project hbase by apache.
the class AsyncAggregationClient method findMedian.
private static <R, S, P extends Message, Q extends Message, T extends Message> void findMedian(CompletableFuture<R> future, RawAsyncTable table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan, NavigableMap<byte[], S> sumByRegion) {
double halfSum = ci.divideForAvg(sumByRegion.values().stream().reduce(ci::add).get(), 2L);
S movingSum = null;
byte[] startRow = null;
for (Map.Entry<byte[], S> entry : sumByRegion.entrySet()) {
startRow = entry.getKey();
S newMovingSum = ci.add(movingSum, entry.getValue());
if (ci.divideForAvg(newMovingSum, 1L) > halfSum) {
break;
}
movingSum = newMovingSum;
}
if (startRow != null) {
scan.withStartRow(startRow);
}
// we can not pass movingSum directly to an anonymous class as it is not final.
S baseSum = movingSum;
byte[] family = scan.getFamilies()[0];
NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(family);
byte[] weightQualifier = qualifiers.last();
byte[] valueQualifier = qualifiers.first();
table.scan(scan, new RawScanResultConsumer() {
private S sum = baseSum;
private R value = null;
@Override
public void onNext(Result[] results, ScanController controller) {
try {
for (Result result : results) {
Cell weightCell = result.getColumnLatestCell(family, weightQualifier);
R weight = ci.getValue(family, weightQualifier, weightCell);
sum = ci.add(sum, ci.castToReturnType(weight));
if (ci.divideForAvg(sum, 1L) > halfSum) {
if (value != null) {
future.complete(value);
} else {
future.completeExceptionally(new NoSuchElementException());
}
controller.terminate();
return;
}
Cell valueCell = result.getColumnLatestCell(family, valueQualifier);
value = ci.getValue(family, valueQualifier, valueCell);
}
} catch (IOException e) {
future.completeExceptionally(e);
controller.terminate();
}
}
@Override
public void onError(Throwable error) {
future.completeExceptionally(error);
}
@Override
public void onComplete() {
if (!future.isDone()) {
// we should not reach here as the future should be completed in onNext.
future.completeExceptionally(new NoSuchElementException());
}
}
});
}
use of java.util.NoSuchElementException in project kafka by apache.
the class AbstractMergedSortedCacheStoreIterator method next.
@Override
public KeyValue<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
final Bytes nextCacheKey = cacheIterator.hasNext() ? cacheIterator.peekNextKey() : null;
final KS nextStoreKey = storeIterator.hasNext() ? storeIterator.peekNextKey() : null;
if (nextCacheKey == null) {
return nextStoreValue(nextStoreKey);
}
if (nextStoreKey == null) {
return nextCacheValue(nextCacheKey);
}
final int comparison = compare(nextCacheKey, nextStoreKey);
if (comparison > 0) {
return nextStoreValue(nextStoreKey);
} else if (comparison < 0) {
return nextCacheValue(nextCacheKey);
} else {
// skip the same keyed element
storeIterator.next();
return nextCacheValue(nextCacheKey);
}
}
use of java.util.NoSuchElementException in project kafka by apache.
the class AbstractMergedSortedCacheStoreIterator method peekNextKey.
@Override
public K peekNextKey() {
if (!hasNext()) {
throw new NoSuchElementException();
}
final Bytes nextCacheKey = cacheIterator.hasNext() ? cacheIterator.peekNextKey() : null;
final KS nextStoreKey = storeIterator.hasNext() ? storeIterator.peekNextKey() : null;
if (nextCacheKey == null) {
return deserializeStoreKey(nextStoreKey);
}
if (nextStoreKey == null) {
return serdes.keyFrom(nextCacheKey.get());
}
final int comparison = compare(nextCacheKey, nextStoreKey);
if (comparison > 0) {
return deserializeStoreKey(nextStoreKey);
} else if (comparison < 0) {
return deserializeCacheKey(nextCacheKey);
} else {
// skip the same keyed element
storeIterator.next();
return deserializeCacheKey(nextCacheKey);
}
}
use of java.util.NoSuchElementException in project tomcat by apache.
the class ExpiresFilter method parseExpiresConfiguration.
/**
* Parse configuration lines like
* '{@code access plus 1 month 15 days 2 hours}' or
* '{@code modification 1 day 2 hours 5 seconds}'
*
* @param inputLine the input
* @return the parsed expires
*/
protected ExpiresConfiguration parseExpiresConfiguration(String inputLine) {
String line = inputLine.trim();
StringTokenizer tokenizer = new StringTokenizer(line, " ");
String currentToken;
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
throw new IllegalStateException(sm.getString("expiresFilter.startingPointNotFound", line));
}
StartingPoint startingPoint;
if ("access".equalsIgnoreCase(currentToken) || "now".equalsIgnoreCase(currentToken)) {
startingPoint = StartingPoint.ACCESS_TIME;
} else if ("modification".equalsIgnoreCase(currentToken)) {
startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
} else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "a")) {
startingPoint = StartingPoint.ACCESS_TIME;
// trick : convert duration configuration from old to new style
tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
} else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "m")) {
startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
// trick : convert duration configuration from old to new style
tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
} else {
throw new IllegalStateException(sm.getString("expiresFilter.startingPointInvalid", currentToken, line));
}
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
}
if ("plus".equalsIgnoreCase(currentToken)) {
// skip
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
}
}
List<Duration> durations = new ArrayList<>();
while (currentToken != null) {
int amount;
try {
amount = Integer.parseInt(currentToken);
} catch (NumberFormatException e) {
throw new IllegalStateException(sm.getString("expiresFilter.invalidDurationNumber", currentToken, line));
}
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
throw new IllegalStateException(sm.getString("expiresFilter.noDurationUnitAfterAmount", Integer.valueOf(amount), line));
}
DurationUnit durationUnit;
if ("year".equalsIgnoreCase(currentToken) || "years".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.YEAR;
} else if ("month".equalsIgnoreCase(currentToken) || "months".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.MONTH;
} else if ("week".equalsIgnoreCase(currentToken) || "weeks".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.WEEK;
} else if ("day".equalsIgnoreCase(currentToken) || "days".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.DAY;
} else if ("hour".equalsIgnoreCase(currentToken) || "hours".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.HOUR;
} else if ("minute".equalsIgnoreCase(currentToken) || "minutes".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.MINUTE;
} else if ("second".equalsIgnoreCase(currentToken) || "seconds".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.SECOND;
} else {
throw new IllegalStateException(sm.getString("expiresFilter.invalidDurationUnit", currentToken, line));
}
Duration duration = new Duration(amount, durationUnit);
durations.add(duration);
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
} else {
currentToken = null;
}
}
return new ExpiresConfiguration(startingPoint, durations);
}
use of java.util.NoSuchElementException in project tomcat by apache.
the class GenericKeyedObjectPool method borrowObject.
/**
* Borrows an object from the sub-pool associated with the given key using
* the specified waiting time which only applies if
* {@link #getBlockWhenExhausted()} is true.
* <p>
* If there is one or more idle instances available in the sub-pool
* associated with the given key, then an idle instance will be selected
* based on the value of {@link #getLifo()}, activated and returned. If
* activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set to
* <code>true</code> and validation fails, the instance is destroyed and the
* next available instance is examined. This continues until either a valid
* instance is returned or there are no more idle instances available.
* <p>
* If there are no idle instances available in the sub-pool associated with
* the given key, behavior depends on the {@link #getMaxTotalPerKey()
* maxTotalPerKey}, {@link #getMaxTotal() maxTotal}, and (if applicable)
* {@link #getBlockWhenExhausted()} and the value passed in to the
* <code>borrowMaxWaitMillis</code> parameter. If the number of instances checked
* out from the sub-pool under the given key is less than
* <code>maxTotalPerKey</code> and the total number of instances in
* circulation (under all keys) is less than <code>maxTotal</code>, a new
* instance is created, activated and (if applicable) validated and returned
* to the caller. If validation fails, a <code>NoSuchElementException</code>
* will be thrown.
* <p>
* If the associated sub-pool is exhausted (no available idle instances and
* no capacity to create new ones), this method will either block
* ({@link #getBlockWhenExhausted()} is true) or throw a
* <code>NoSuchElementException</code>
* ({@link #getBlockWhenExhausted()} is false).
* The length of time that this method will block when
* {@link #getBlockWhenExhausted()} is true is determined by the value
* passed in to the <code>borrowMaxWait</code> parameter.
* <p>
* When <code>maxTotal</code> is set to a positive value and this method is
* invoked when at the limit with no idle instances available under the requested
* key, an attempt is made to create room by clearing the oldest 15% of the
* elements from the keyed sub-pools.
* <p>
* When the pool is exhausted, multiple calling threads may be
* simultaneously blocked waiting for instances to become available. A
* "fairness" algorithm has been implemented to ensure that threads receive
* available instances in request arrival order.
*
* @param key pool key
* @param borrowMaxWaitMillis The time to wait in milliseconds for an object
* to become available
*
* @return object instance from the keyed pool
*
* @throws NoSuchElementException if a keyed object instance cannot be
* returned because the pool is exhausted.
*
* @throws Exception if a keyed object instance cannot be returned due to an
* error
*/
public T borrowObject(final K key, final long borrowMaxWaitMillis) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
final boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
final long waitTime = System.currentTimeMillis();
final ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
p = objectDeque.getIdleObjects().pollFirst();
if (p == null) {
p = create(key);
if (p != null) {
create = true;
}
}
if (blockWhenExhausted) {
if (p == null) {
if (borrowMaxWaitMillis < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
p = objectDeque.getIdleObjects().pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
}
}
if (p == null) {
throw new NoSuchElementException("Timeout waiting for idle object");
}
} else {
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
}
if (!p.allocate()) {
p = null;
}
if (p != null) {
try {
factory.activateObject(key, p);
} catch (final Exception e) {
try {
destroy(key, p, true);
} catch (final Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
final NoSuchElementException nsee = new NoSuchElementException("Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(key, p);
} catch (final Throwable t) {
PoolUtils.checkRethrow(t);
validationThrowable = t;
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (final Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
final NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
updateStatsBorrow(p, System.currentTimeMillis() - waitTime);
return p.getObject();
}
Aggregations