下面列出了com.google.common.collect.Multimap#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void flush(List<String> eventKeys, Multimap<String, ByteBuffer> eventsByChannel,
int numOutboundReplicationEvents) {
try (Timer.Context ignore = _eventFlushTimer.time()) {
if (!eventsByChannel.isEmpty()) {
_eventSink.apply(eventsByChannel);
_eventsWrittenLocal.mark(eventsByChannel.size() - numOutboundReplicationEvents);
_eventsWrittenOutboundReplication.mark(numOutboundReplicationEvents);
eventsByChannel.clear();
}
if (!eventKeys.isEmpty()) {
_eventSource.delete(eventKeys);
_eventsRead.mark(eventKeys.size());
eventKeys.clear();
}
}
}
Collection<BindingStrategy> collect(Collection<Class<?>> aggregateClasses,
Collection<Class<?>> valueObjectClasses) {
Collection<BindingStrategy> strategies = new ArrayList<>();
boolean bindGuiceFactory = true;
if (!aggregateClasses.isEmpty() || !valueObjectClasses.isEmpty()) {
strategies.add(new GenericBindingStrategy<>(Factory.class, DefaultFactory.class,
Stream.concat(aggregateClasses.stream(), valueObjectClasses.stream())
.filter(this::isCandidate)
.map(candidate -> new Type[]{candidate})
.collect(Collectors.toList())));
bindGuiceFactory = false;
}
Multimap<Type, Class<?>> producibleClasses = filterProducibleClasses(bindings);
if (!producibleClasses.isEmpty()) {
strategies.add(new DefaultFactoryStrategy<>(Factory.class, DefaultFactory.class, producibleClasses,
bindGuiceFactory));
}
return strategies;
}
public static String getDocumentationOn(final String query) {
final String keyword = StringUtils.removeEnd(StringUtils.removeStart(query.trim(), "#"), ":");
final Multimap<GamlIdiomsProvider<?>, IGamlDescription> results = GamlIdiomsProvider.forName(keyword);
if (results.isEmpty()) { return "No result found"; }
final StringBuilder sb = new StringBuilder();
final int max = results.keySet().stream().mapToInt(each -> each.name.length()).max().getAsInt();
final String separator = StringUtils.repeat("—", max + 6).concat(Strings.LN);
results.asMap().forEach((provider, list) -> {
sb.append("").append(separator).append("|| ");
sb.append(StringUtils.rightPad(provider.name, max));
sb.append(" ||").append(Strings.LN).append(separator);
for (final IGamlDescription d : list) {
sb.append("== ").append(toText(d.getTitle())).append(Strings.LN).append(toText(provider.document(d)))
.append(Strings.LN);
}
});
return sb.toString();
//
}
@Override
public String toText() {
Multimap<String, PublicCertificate> certs = getParent().getCertificatesByType(company);
if (certs.isEmpty()) return null;
StringBuilder text = new StringBuilder();
for (String certType : certs.keySet()) {
if (text.length() > 0) text.append("<br>");
// parse certType
// TODO: Create true CertificateTypes
String[] items = certType.split("_");
String type = items[1] + (items.length > 2 && items[2].contains("P") ? "P" : "");
text.append(type).append(" x ").append(certs.get(certType).size());
}
return "<html>" + text.toString() + "</html>";
}
@Override
public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,
Multimap<String, String> tenantIdGroupNamePairs,
Iterable<String> ipRanges,
Iterable<String> groupIds, SecurityGroup group) {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String id = group.getProviderId();
IpPermission.Builder builder = IpPermission.builder();
builder.ipProtocol(protocol);
builder.fromPort(startPort);
builder.toPort(endPort);
if (!Iterables.isEmpty(ipRanges)) {
for (String cidr : ipRanges) {
builder.cidrBlock(cidr);
}
}
if (!tenantIdGroupNamePairs.isEmpty()) {
for (String userId : tenantIdGroupNamePairs.keySet()) {
for (String groupString : tenantIdGroupNamePairs.get(userId)) {
String[] parts = AWSUtils.parseHandle(groupString);
String groupId = parts[1];
builder.tenantIdGroupNamePair(userId, groupId);
}
}
}
client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build());
return getSecurityGroupById(group.getId());
}
@Override
public <E extends DomainEvent> void publish(E event) {
LOGGER.debug("Firing event {} synchronously", event.getClass()
.getName());
for (Class<? extends DomainEvent> eventClass : eventHandlerClassesByEvent.keys()
.elementSet()) {
if (eventClass.isAssignableFrom(event.getClass())) {
checkCyclicCall(eventClass, event);
Multimap<Class<? extends DomainEvent>, DomainEvent> currentEventClasses = context
.get();
boolean isFirstCall = currentEventClasses.isEmpty();
context.get()
.put(eventClass, event);
try {
notifyHandlers(eventClass, event);
} catch (Exception e) {
throw BusinessException.wrap(e,
BusinessErrorCode.EXCEPTION_OCCURRED_DURING_EVENT_HANDLER_INVOCATION)
.put("event", eventClass.getName());
} finally {
if (isFirstCall) {
context.remove();
}
}
}
}
}
@Unique
private static void checkRequiredTags(RegistryTagManager tagManager) {
Multimap<String, Identifier> missingTags = HashMultimap.create();
missingTags.putAll("blocks", BlockTags.method_29214(tagManager.blocks()));
missingTags.putAll("items", ItemTags.method_29217(tagManager.items()));
missingTags.putAll("fluids", FluidTags.method_29216(tagManager.fluids()));
missingTags.putAll("entity_types", EntityTypeTags.method_29215(tagManager.entityTypes()));
if (!missingTags.isEmpty()) {
LogManager.getLogger("multiconnect").error("Missing required tags: " + missingTags.entries().stream()
.map(entry -> entry.getKey() + ":" + entry.getValue())
.sorted()
.collect(Collectors.joining(",")));
}
}
/**
* Flatten the dimension map
*/
protected static List<String> getDimensionsList(Multimap<String, String> dimensions) {
List<String> dimensionsList = new ArrayList<>();
if (dimensions != null && !dimensions.isEmpty()) {
for (Map.Entry<String, Collection<String>> entry : dimensions.asMap().entrySet()) {
dimensionsList.add(entry.getKey() + " : " + String.join(",", entry.getValue()));
}
}
return dimensionsList;
}
@Override
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,
Multimap<String, String> tenantIdGroupNamePairs,
Iterable<String> ipRanges,
Iterable<String> groupIds, SecurityGroup group) {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String id = group.getProviderId();
IpPermission.Builder builder = IpPermission.builder();
builder.ipProtocol(protocol);
builder.fromPort(startPort);
builder.toPort(endPort);
if (!Iterables.isEmpty(ipRanges)) {
for (String cidr : ipRanges) {
builder.cidrBlock(cidr);
}
}
if (!tenantIdGroupNamePairs.isEmpty()) {
for (String userId : tenantIdGroupNamePairs.keySet()) {
for (String groupString : tenantIdGroupNamePairs.get(userId)) {
String[] parts = AWSUtils.parseHandle(groupString);
String groupId = parts[1];
builder.tenantIdGroupNamePair(userId, groupId);
}
}
}
client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, builder.build());
return getSecurityGroupById(group.getId());
}
Symbol addComparisons(Symbol symbol,
List<GeneratedReference> generatedCols,
List<Reference> expansionCandidates,
Functions functions) {
Multimap<Reference, GeneratedReference> referencedSingleReferences =
extractGeneratedReferences(generatedCols, expansionCandidates);
if (referencedSingleReferences.isEmpty()) {
return symbol;
} else {
Context ctx = new Context(referencedSingleReferences, functions);
return symbol.accept(this, ctx);
}
}
private URI appendQueryParameters(URIBuilder uriBuilder, Multimap<String, String> queryParameters) throws URISyntaxException {
if (queryParameters != null && !queryParameters.isEmpty()) {
queryParameters.entries().stream().forEach(entry -> {
try {
uriBuilder.setParameter(URLEncoder.encode(entry.getKey(), "UTF-8"), entry.getValue());
} catch (UnsupportedEncodingException e) {
}
});
}
return uriBuilder.build();
}
@Override
public void next() throws IOException {
tk = null;
tv = null;
while (itr.hasTop() && tk == null) {
Multimap<String,TermInfo> terms = aggregateDate();
if (terms.isEmpty()) {
if (log.isTraceEnabled())
log.trace("Couldn't aggregate index info; moving onto next date/field/term if data is available.");
continue;
} else {
if (log.isTraceEnabled())
log.trace("Received term info multimap of size [" + terms.size() + "]");
ArrayList<DiscoveredThing> things = newArrayList(filter(
transform(terms.asMap().values(), new TermInfoAggregation(separateCountsByColVis, showReferenceCount, reverseIndex)),
Predicates.notNull()));
if (log.isTraceEnabled())
log.trace("After conversion to discovery objects, there are [" + things.size() + "] term info objects.");
if (things.isEmpty()) {
continue;
} else {
Pair<Key,Value> top = makeTop(things);
tk = top.getFirst();
tv = top.getSecond();
return;
}
}
}
if (log.isTraceEnabled())
log.trace("No data found.");
}
@Override
protected @NonNull Map<String, Object> createQueryParameters(long start, long end, int nb) {
Map<@NonNull String, @NonNull Object> parameters = FetchParametersUtils.selectionTimeQueryToMap(new SelectionTimeQueryFilter(start, end, nb, fSelectedIds));
Multimap<@NonNull Integer, @NonNull String> regexesMap = getRegexes();
if (!regexesMap.isEmpty()) {
parameters.put(DataProviderParameterUtils.REGEX_MAP_FILTERS_KEY, regexesMap.asMap());
}
return parameters;
}
private void failIfSnapshotsAreReferenced(boolean hasSnapshots,
Map<MavenProject, Multimap<ArtifactCoordinates, ArtifactCoordinates>> snapshotsByProjectAndPlugin,
Map<MavenProject, PomPropertyResolver> propertyResolvers) throws MojoFailureException {
if (hasSnapshots) {
this.log.error(
"\tThere are plugins with SNAPSHOT dependencies! The following list contains all SNAPSHOT dependencies grouped by plugin and module:");
for (MavenProject p : snapshotsByProjectAndPlugin.keySet()) {
PomPropertyResolver propertyResolver = propertyResolvers.get(p);
Multimap<ArtifactCoordinates, ArtifactCoordinates> snapshots = snapshotsByProjectAndPlugin.get(p);
if (!snapshots.isEmpty()) {
this.log.error("\t\t[PROJECT] " + ProjectToString.INSTANCE.apply(p));
for (ArtifactCoordinates plugin : snapshots.keySet()) {
this.log.error("\t\t\t[PLUGIN] " + plugin);
for (ArtifactCoordinates dependency : snapshots.get(plugin)) {
String resolvedVersion = propertyResolver.expandPropertyReferences(dependency.getVersion());
String coordinates = dependency.toString();
if (!Objects.equal(resolvedVersion, dependency.getVersion())) {
coordinates = coordinates + " (resolves to " + resolvedVersion + ")";
}
this.log.error("\t\t\t\t[DEPENDENCY] " + coordinates);
}
}
}
}
throw new MojoFailureException("The project cannot be released due to one or more SNAPSHOT plugin-dependencies!");
}
}
public static final void configureIndexMatchingIterator(DiscoveryQueryConfiguration config, ScannerBase bs, Multimap<String,String> literals,
Multimap<String,String> patterns, Multimap<String,LiteralRange<String>> ranges, boolean reverseIndex) {
if ((literals == null || literals.isEmpty()) && (patterns == null || patterns.isEmpty()) && (ranges == null || ranges.isEmpty())) {
return;
}
log.debug("Configuring IndexMatchingIterator with " + literals + " and " + patterns);
IteratorSetting cfg = new IteratorSetting(config.getBaseIteratorPriority() + 23, "termMatcher", IndexMatchingIterator.class);
IndexMatchingIterator.Configuration conf = new IndexMatchingIterator.Configuration();
if (literals != null) {
for (Entry<String,String> literal : literals.entries()) {
if (Constants.ANY_FIELD.equals(literal.getValue())) {
conf.addLiteral(literal.getKey());
} else {
conf.addLiteral(literal.getKey(), literal.getValue());
}
}
}
if (patterns != null) {
for (Entry<String,String> pattern : patterns.entries()) {
if (Constants.ANY_FIELD.equals(pattern.getValue())) {
conf.addPattern(pattern.getKey());
} else {
conf.addPattern(pattern.getKey(), pattern.getValue());
}
}
}
if (ranges != null) {
for (Entry<String,LiteralRange<String>> range : ranges.entries()) {
if (Constants.ANY_FIELD.equals(range.getKey())) {
conf.addRange(range.getValue());
} else {
conf.addRange(range.getValue(), range.getKey());
}
}
}
cfg.addOption(IndexMatchingIterator.CONF, IndexMatchingIterator.gson().toJson(conf));
cfg.addOption(IndexMatchingIterator.REVERSE_INDEX, Boolean.toString(reverseIndex));
bs.addScanIterator(cfg);
}
/**
* This method returns a Map which defines the evolutionary relation between ColumnRefs in the specified
* 'from' TableRef, to the specified 'to' TableRef.
*
* @param from The source TableRef.
* @param to The target TableRef.
* @return The column mapping between the two TableRefs.
*/
public Map<ColumnRef, ColumnRef> getColumnMapping(TableRef from, TableRef to) {
boolean forwards = isForwards(from, to);
Multimap<ColumnRef, ColumnRef> mapping = HashMultimap.create();
from.getColumns().forEach((k, v) -> mapping.put(v, v));
while (true) {
Multimap<ColumnRef, ColumnRef> pending = HashMultimap.create();
for (ColumnRef source : mapping.keySet()) {
Collection<ColumnRef> targets = mapping.get(source);
targets.stream()
.filter(target -> {
TableRef table = target.getTable();
return !table.equals(to);
})
.forEach(target -> pending.put(source, target));
}
if (pending.isEmpty()) {
break;
}
pending.entries().forEach(entry -> {
ColumnRef columnRef = entry.getValue();
mapping.remove(entry.getKey(), columnRef);
Set<ColumnRef> nextColumns = null;
if (forwards) {
nextColumns = columnRef.getBasisFor();
}
else {
nextColumns = columnRef.getBasedOn();
}
if (!nextColumns.isEmpty()) {
mapping.putAll(entry.getKey(), nextColumns);
}
});
}
return mapping.entries().stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
@Override
public boolean isEmpty(SerializerProvider prov, Multimap<?,?> value) {
return value.isEmpty();
}
/**
* Reentrant. If {@code instance} was registered for injection at injector-creation time, this
* method will ensure that all its members have been injected before returning.
*/
public T get(Errors errors) throws ErrorsException {
// skipping acquiring lock if initialization is already finished
if (state == InjectableReferenceState.READY) {
return instance;
}
// acquire lock for current binding to initialize an instance
Multimap<?, ?> lockCycle = lock.lockOrDetectPotentialLocksCycle();
if (!lockCycle.isEmpty()) {
// Potential deadlock detected and creation lock is not taken.
// According to injectAll()'s contract return non-initialized instance.
// This condition should not be possible under the current Guice implementation.
// This clause exists for defensive programming purposes.
// Reasoning:
// get() is called either directly from injectAll(), holds no locks and can not create
// a cycle, or it is called through a singleton scope, which resolves deadlocks by itself.
// Before calling get() object has to be requested for injection.
// Initializer.requestInjection() is called either for constant object bindings, which wrap
// creation into a Singleton scope, or from Binder.requestInjection(), which
// has to use Singleton scope to reuse the same InjectableReference to potentially
// create a lock cycle.
return instance;
}
try {
// lock acquired, current thread owns this instance initialization
switch (state) {
case READY:
return instance;
// When instance depends on itself in the same thread potential dead lock
// is not detected. We have to prevent a stack overflow and we use
// an "injecting" stage to short-circuit a call.
case INJECTING:
return instance;
case VALIDATED:
state = InjectableReferenceState.INJECTING;
break;
case NEW:
throw new IllegalStateException("InjectableReference is not validated yet");
default:
throw new IllegalStateException("Unknown state: " + state);
}
// if in Stage.TOOL, we only want to inject & notify toolable injection points.
// (otherwise we'll inject all of them)
membersInjector.injectAndNotify(instance,
errors.withSource(source),
key,
provisionCallback,
source,
injector.options.stage == Stage.TOOL);
// mark instance as ready to skip a lock on subsequent calls
state = InjectableReferenceState.READY;
return instance;
} finally {
// always release our creation lock, even on failures
lock.unlock();
}
}
/**
* Get the fetch parameters to pass to a fetchRowModel call
*
* @param start
* Start time of query
* @param end
* End time of query
* @param resolution
* Resolution of query
* @param fullSearch
* True to perform a full search
* @param items
* The unique keys of the entries to query.
* @return Map of parameters for fetchRowModel
* @since 5.2
*/
protected @NonNull Map<@NonNull String, @NonNull Object> getFetchRowModelParameters(long start, long end, long resolution, boolean fullSearch, @NonNull Collection<Long> items) {
@NonNull Map<@NonNull String, @NonNull Object> parameters = new HashMap<>();
parameters.put(DataProviderParameterUtils.REQUESTED_TIME_KEY, StateSystemUtils.getTimes(start, end, resolution));
parameters.put(DataProviderParameterUtils.REQUESTED_ITEMS_KEY, items);
Multimap<@NonNull Integer, @NonNull String> regexesMap = getRegexes();
if (!regexesMap.isEmpty()) {
parameters.put(DataProviderParameterUtils.REGEX_MAP_FILTERS_KEY, regexesMap.asMap());
}
if (fullSearch) {
parameters.put(DataProviderParameterUtils.FULL_SEARCH_KEY, Boolean.TRUE);
}
return parameters;
}
/**
* Create map of parameters that will be used by updateData method. If a
* viewer need a more specialized map than just the time requested it's its
* responsibility to override this method and provide the desired instance.
*
* @param start
* The starting value
* @param end
* The ending value
* @param nb
* The number of entries
* @return Map of parameters
* @since 5.0
*/
protected @NonNull Map<String, Object> createQueryParameters(long start, long end, int nb) {
Map<@NonNull String, @NonNull Object> parameters = FetchParametersUtils.timeQueryToMap(new TimeQueryFilter(start, end, nb));
Multimap<@NonNull Integer, @NonNull String> regexesMap = getRegexes();
if (!regexesMap.isEmpty()) {
parameters.put(DataProviderParameterUtils.REGEX_MAP_FILTERS_KEY, regexesMap.asMap());
}
return parameters;
}