use of java.util.Collections in project elasticsearch by elastic.
the class TermsQueryBuilder method convert.
/**
* Convert the list in a way that optimizes storage in the case that all
* elements are either integers or {@link String}s/{@link BytesRef}s. This
* is useful to help garbage collections for use-cases that involve sending
* very large terms queries to Elasticsearch. If the list does not only
* contain integers or {@link String}s, then a list is returned where all
* {@link String}s have been replaced with {@link BytesRef}s.
*/
static List<?> convert(List<?> list) {
if (list.isEmpty()) {
return Collections.emptyList();
}
final boolean allNumbers = list.stream().allMatch(o -> o != null && INTEGER_TYPES.contains(o.getClass()));
if (allNumbers) {
final long[] elements = list.stream().mapToLong(o -> ((Number) o).longValue()).toArray();
return new AbstractList<Object>() {
@Override
public Object get(int index) {
return elements[index];
}
@Override
public int size() {
return elements.length;
}
};
}
final boolean allStrings = list.stream().allMatch(o -> o != null && STRING_TYPES.contains(o.getClass()));
if (allStrings) {
final BytesRefBuilder builder = new BytesRefBuilder();
try (BytesStreamOutput bytesOut = new BytesStreamOutput()) {
final int[] endOffsets = new int[list.size()];
int i = 0;
for (Object o : list) {
BytesRef b;
if (o instanceof BytesRef) {
b = (BytesRef) o;
} else {
builder.copyChars(o.toString());
b = builder.get();
}
bytesOut.writeBytes(b.bytes, b.offset, b.length);
if (i == 0) {
endOffsets[0] = b.length;
} else {
endOffsets[i] = Math.addExact(endOffsets[i - 1], b.length);
}
++i;
}
final BytesReference bytes = bytesOut.bytes();
return new AbstractList<Object>() {
public Object get(int i) {
final int startOffset = i == 0 ? 0 : endOffsets[i - 1];
final int endOffset = endOffsets[i];
return bytes.slice(startOffset, endOffset - startOffset).toBytesRef();
}
public int size() {
return endOffsets.length;
}
};
}
}
return list.stream().map(o -> o instanceof String ? new BytesRef(o.toString()) : o).collect(Collectors.toList());
}
use of java.util.Collections in project spring-framework by spring-projects.
the class TomcatRequestUpgradeStrategy method upgrade.
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
HttpServletRequest servletRequest = getHttpServletRequest(request);
HttpServletResponse servletResponse = getHttpServletResponse(response);
Endpoint endpoint = new StandardWebSocketHandlerAdapter(handler, session -> {
HandshakeInfo info = getHandshakeInfo(exchange, subProtocol);
DataBufferFactory factory = response.bufferFactory();
return new StandardWebSocketSession(session, info, factory);
});
String requestURI = servletRequest.getRequestURI();
DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint);
config.setSubprotocols(subProtocol.map(Collections::singletonList).orElse(Collections.emptyList()));
try {
WsServerContainer container = getContainer(servletRequest);
container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap());
} catch (ServletException | IOException ex) {
return Mono.error(ex);
}
return Mono.empty();
}
use of java.util.Collections in project torodb by torodb.
the class RecoveryService method cloneDatabases.
private void cloneDatabases(@Nonnull MongoClient remoteClient) throws CloningException, MongoException, UserException {
enableDataImportMode();
try {
Stream<String> dbNames;
try (MongoConnection remoteConnection = remoteClient.openConnection()) {
RemoteCommandResponse<ListDatabasesReply> remoteResponse = remoteConnection.execute(ListDatabasesCommand.INSTANCE, "admin", true, Empty.getInstance());
if (!remoteResponse.isOk()) {
throw remoteResponse.asMongoException();
}
dbNames = remoteResponse.getCommandReply().get().getDatabases().stream().map(db -> db.getName());
}
dbNames.filter(this::isReplicable).forEach(databaseName -> {
MyWritePermissionSupplier writePermissionSupplier = new MyWritePermissionSupplier(databaseName);
CloneOptions options = new CloneOptions(true, true, true, false, databaseName, Collections.<String>emptySet(), writePermissionSupplier, (colName) -> replFilters.getCollectionPredicate().test(databaseName, colName), (collection, indexName, unique, keys) -> replFilters.getIndexPredicate().test(databaseName, collection, indexName, unique, keys));
try {
cloner.cloneDatabase(databaseName, remoteClient, server, options);
} catch (MongoException ex) {
throw new CloningException(ex);
}
});
} finally {
disableDataImportMode();
}
}
use of java.util.Collections in project wildfly by wildfly.
the class ChannelCommandDispatcher method submitOnCluster.
@Override
public <R> Map<Node, Future<R>> submitOnCluster(Command<R, ? super C> command, Node... excludedNodes) throws CommandDispatcherException {
Map<Node, Future<R>> results = new ConcurrentHashMap<>();
FutureListener<RspList<R>> listener = future -> {
try {
future.get().keySet().stream().map(address -> this.factory.createNode(address)).forEach(node -> results.remove(node));
} catch (CancellationException e) {
} catch (ExecutionException e) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Message message = this.createMessage(command);
RequestOptions options = this.createRequestOptions(excludedNodes);
try {
Future<? extends Map<Address, Rsp<R>>> futureResponses = this.dispatcher.castMessageWithFuture(null, message, options, listener);
Set<Node> excluded = (excludedNodes != null) ? new HashSet<>(Arrays.asList(excludedNodes)) : Collections.<Node>emptySet();
for (Address address : this.dispatcher.getChannel().getView().getMembers()) {
Node node = this.factory.createNode(address);
if (!excluded.contains(node)) {
Future<R> future = new Future<R>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return futureResponses.cancel(mayInterruptIfRunning);
}
@Override
public R get() throws InterruptedException, ExecutionException {
Map<Address, Rsp<R>> responses = futureResponses.get();
Rsp<R> response = responses.get(address);
if (response == null) {
throw new CancellationException();
}
return createCommandResponse(response).get();
}
@Override
public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
Map<Address, Rsp<R>> responses = futureResponses.get(timeout, unit);
Rsp<R> response = responses.get(address);
if (response == null) {
throw new CancellationException();
}
return createCommandResponse(response).get();
}
@Override
public boolean isCancelled() {
return futureResponses.isCancelled();
}
@Override
public boolean isDone() {
return futureResponses.isDone();
}
};
results.put(node, future);
}
}
return results;
} catch (Exception e) {
throw new CommandDispatcherException(e);
}
}
use of java.util.Collections in project L42 by ElvisResearchGroup.
the class Translator method useFrom.
//this should take a class, strip out nested and 'from' it so that it is as at top level
static ClassB useFrom(ClassB ct, Path p) {
ArrayList<Member> ms = new ArrayList<Member>();
for (Member m : ct.getMs()) {
m.match(nc -> null, mi -> {
throw Assertions.codeNotReachable();
}, mt -> ms.add(From.from(mt, p)));
}
//for(PathMwt pmwt:ct.getStage().getInherited()){
for (PathMwt pmwt : Collections.<PathMwt>emptyList()) {
if (Functions.getIfInDom(ms, pmwt.getMwt().getMs()).isPresent()) {
continue;
}
ms.add(From.from(pmwt.getMwt(), p));
}
List<Path> sup = tools.Map.of(ti -> (Path) From.fromP(ti.getPath(), p), ct.getSupertypes());
//tools.Map.of(pi->(Path)From.fromP(pi,p),ct.getStage().getInheritedPaths());
List<Path> supAll = sup;
ClassB res = ct.withMs(ms).withSupertypes(tools.Map.of(pi -> pi.toImmNT(), sup));
return res;
}
Aggregations