Java源码示例:java.util.Collection
示例1
static Query genericFunctionFilter(Function function, Context context) {
if (function.valueType() != DataTypes.BOOLEAN) {
raiseUnsupported(function);
}
// rewrite references to source lookup instead of using the docValues column store if:
// - no docValues are available for the related column, currently only on objects defined as `ignored`
// - docValues value differs from source, currently happening on GeoPoint types as lucene's internal format
// results in precision changes (e.g. longitude 11.0 will be 10.999999966)
function = (Function) DocReferences.toSourceLookup(function,
r -> r.columnPolicy() == ColumnPolicy.IGNORED
|| r.valueType() == DataTypes.GEO_POINT);
final InputFactory.Context<? extends LuceneCollectorExpression<?>> ctx = context.docInputFactory.getCtx(context.txnCtx);
@SuppressWarnings("unchecked")
final Input<Boolean> condition = (Input<Boolean>) ctx.add(function);
final Collection<? extends LuceneCollectorExpression<?>> expressions = ctx.expressions();
final CollectorContext collectorContext = new CollectorContext();
for (LuceneCollectorExpression<?> expression : expressions) {
expression.startCollect(collectorContext);
}
return new GenericFunctionQuery(function, expressions, condition);
}
示例2
protected ScannerBase metricScanner(AccumuloFeatureConfig xform, Date start, Date end, String group, Iterable<String> types, String name, TimeUnit timeUnit, Auths auths) {
checkNotNull(xform);
try {
group = defaultString(group);
timeUnit = (timeUnit == null ? TimeUnit.MINUTES : timeUnit);
BatchScanner scanner = connector.createBatchScanner(tableName + REVERSE_SUFFIX, auths.getAuths(), config.getMaxQueryThreads());
Collection<Range> typeRanges = new ArrayList();
for (String type : types)
typeRanges.add(buildRange(type, start, end, timeUnit));
scanner.setRanges(typeRanges);
scanner.fetchColumn(new Text(combine(timeUnit.toString(), xform.featureName())), new Text(combine(group, name)));
return scanner;
} catch (TableNotFoundException e) {
throw new RuntimeException(e);
}
}
示例3
@Override
public Collection<ParameterEnum<?>> getParameters() {
final Collection<ParameterEnum<?>> params = super.getParameters();
params.addAll(
Arrays.asList(
new ParameterEnum<?>[] {
Partition.PARTITIONER_CLASS,
Partition.MAX_DISTANCE,
Partition.MAX_MEMBER_SELECTION,
Global.BATCH_ID,
Hull.DATA_TYPE_ID,
Hull.PROJECTION_CLASS,
Clustering.MINIMUM_SIZE,
Partition.GEOMETRIC_DISTANCE_UNIT,
Partition.DISTANCE_THRESHOLDS}));
return params;
}
示例4
@Override
public String[] unparse(LoadContext context, EquipmentModifier mod)
{
Changes<ChangeArmorType> changes = context.getObjectContext().getListChanges(mod, ListKey.ARMORTYPE);
Collection<ChangeArmorType> added = changes.getAdded();
if (added == null || added.isEmpty())
{
// Zero indicates no Token
return null;
}
TreeSet<String> set = new TreeSet<>();
for (ChangeArmorType cat : added)
{
set.add(cat.getLSTformat());
}
return set.toArray(new String[0]);
}
示例5
/**
* Matches the expectations in the added issues matchers against the given issues.
*
* @param issues
* the issues to match the expectations against
* @param messages
* if this parameter is not <code>null</code>, this method will add an explanatory message for each
* mismatch
* @return <code>true</code> if and only if every expectation was matched against an issue
*/
public boolean matchesAllExpectations(Collection<Issue> issues, List<String> messages) {
Collection<Issue> issueCopy = new LinkedList<>(issues);
Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);
performMatching(issueCopy, matcherCopy, messages);
if (inverted) {
if (matcherCopy.isEmpty()) {
explainExpectations(issueMatchers, messages, inverted);
return false;
}
} else {
if (!matcherCopy.isEmpty()) {
explainExpectations(matcherCopy, messages, inverted);
return false;
}
}
return false;
}
示例6
public static String getResultsFormatted(Map<String, Object> map) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
builder
.append("- ")
.append(entry.getKey())
.append(" (")
.append(entry.getValue().getClass().getName())
.append(")");
if (entry.getValue() instanceof Collection) {
builder.append(" [").append(((Collection) entry.getValue()).size()).append(" elements]");
} else {
builder.append(": ").append(entry.getValue().toString());
}
builder.append(System.lineSeparator());
}
return builder.toString();
}
示例7
@Override
public Collection<Message> getMessages(Uuid conversation, Time start, Time end) {
final Collection<Message> messages = new ArrayList<>();
try (final Connection connection = source.connect()) {
Serializers.INTEGER.write(connection.out(), NetworkCode.GET_MESSAGES_BY_TIME_REQUEST);
Time.SERIALIZER.write(connection.out(), start);
Time.SERIALIZER.write(connection.out(), end);
if (Serializers.INTEGER.read(connection.in()) == NetworkCode.GET_MESSAGES_BY_TIME_RESPONSE) {
messages.addAll(Serializers.collection(Message.SERIALIZER).read(connection.in()));
} else {
LOG.error("Response from server failed.");
}
} catch (Exception ex) {
System.out.println("ERROR: Exception during call on server. Check log for details.");
LOG.error(ex, "Exception during call on server.");
}
return messages;
}
示例8
public Collection<HistogramSnapshot> createRpcResponseSnapshot() {
final List<HistogramSnapshot> histogramSnapshotList = new ArrayList<HistogramSnapshot>(16);
for (RpcMetric metric : rpcCache.values()) {
histogramSnapshotList.addAll(metric.createSnapshotList());
}
return histogramSnapshotList;
}
示例9
/**
* Only those who have any of the given roles can access the protected instance.
*
* @param roles The roles to check for.
* @return A newly created AccessPredicate that only returns true, if the name of the {@link GrantedAuthority}s
* matches any of the given role names.
*/
static AccessPredicate hasAnyRole(final Collection<String> roles) {
requireNonNull(roles, "roles");
roles.forEach(role -> requireNonNull(role, "role"));
final Set<String> immutableRoles = ImmutableSet.copyOf(roles);
return authentication -> {
for (final GrantedAuthority authority : authentication.getAuthorities()) {
if (immutableRoles.contains(authority.getAuthority())) {
return true;
}
}
return false;
};
}
示例10
public Action createContextAwareInstance(Lookup actionContext) {
Collection<? extends BreakpointAnnotation> ann = actionContext.lookupAll(BreakpointAnnotation.class);
if (ann.size() > 0) {
onBreakpoint = true;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
onBreakpoint = false;
}
});
return getAction();
} else {
return this;
}
}
示例11
@Override
public Collection<WriterSegmentProcessor> createWriterSegmentProcessors(UpdateableSegmentMetadata metadata) {
Exceptions.checkNotClosed(this.closed.get(), this);
if (!metadata.getAttributes().containsKey(TableAttributes.INDEX_OFFSET)) {
// Not a Table Segment; nothing to do.
return Collections.emptyList();
}
return Collections.singletonList(new WriterTableProcessor(new TableWriterConnectorImpl(metadata), this.executor));
}
示例12
public PartitionMessageWithDirectReply(
Collection<InternalDistributedMember> recipients, int regionId,
DirectReplyProcessor processor, final TXStateInterface tx) {
super(recipients, regionId, processor, tx);
this.processor = processor;
this.posDup = false;
}
示例13
public static Collection<DeclaredType> collectInterfaces(TypeElement type) {
@SuppressWarnings({"unchecked"})
Collection<DeclaredType> interfaces = (Collection<DeclaredType>) type.getInterfaces();
for (TypeMirror interfaceType : type.getInterfaces()) {
interfaces.addAll(collectInterfaces(getDeclaration(interfaceType)));
}
return interfaces;
}
示例14
/**
* Computes the necessary equality constraints for conditional expressions.
*
* @param constraints the type constraints (element type: <code>ITypeConstraint2</code>)
* @param level the compliance level
*/
private void computeConditionalTypeConstraints(final Collection<ITypeConstraint2> constraints, final int level) {
ITypeConstraint2 constraint= null;
for (final Iterator<ITypeConstraint2> iterator= constraints.iterator(); iterator.hasNext();) {
constraint= iterator.next();
if (constraint instanceof ConditionalTypeConstraint) {
final ConditionalTypeConstraint conditional= (ConditionalTypeConstraint) constraint;
fModel.createEqualityConstraint(constraint.getLeft(), constraint.getRight());
fModel.createEqualityConstraint(conditional.getExpression(), constraint.getLeft());
fModel.createEqualityConstraint(conditional.getExpression(), constraint.getRight());
}
}
}
示例15
private Collection<GenericTestCase> createTestCases() throws InitializationError {
return new RDFUnitTestSuiteGenerator.Builder()
.addSchemaURI("custom", getSchema().uri(), getSchemaReader())
.enableAutotests()
.build()
.getTestSuite()
.getTestCases();
}
示例16
public X509CA ( final CertificateFactory cf, final String certificateUrl, final Collection<String> crlUrls )
{
this.certificateFactory = cf;
this.certificateUrl = certificateUrl;
this.crlUrls = crlUrls != null ? new ArrayList<String> ( crlUrls ) : null;
this.certificates = new X509Certificate[0];
this.crls = new X509CRL[0];
}
示例17
@Override
protected void checkForDeletionBlockers(Collection<String> blockers) {
super.checkForDeletionBlockers(blockers);
if (!(getSchoolClassesSet().isEmpty() && getGuidesSet().isEmpty() && getStudentCandidaciesSet().isEmpty() && getShiftDistributionEntriesSet()
.isEmpty())) {
blockers.add(BundleUtil.getString(Bundle.APPLICATION, "execution.degree.cannot.be.deleted"));
}
}
示例18
@Override
public synchronized Collection<Glyph> getActiveGlyphs ()
{
if (activeGlyphs == null) {
activeGlyphs = Glyphs.sortedSet(activeMap.values());
activeGlyphs.addAll(virtualGlyphs);
}
return Collections.unmodifiableCollection(activeGlyphs);
}
示例19
@Override
public Collection<String> getHeaders(String name) {
Enumeration<String> values = headers.values(name);
List<String> result = new ArrayList<>();
while (values.hasMoreElements()) {
result.add(values.nextElement());
}
return result;
}
示例20
public void testBindCollectionInFromClause() throws Exception {
Query query = CacheUtils.getQueryService().newQuery("SELECT DISTINCT * FROM $1 ");
Object params[] = new Object[1];
Region region = CacheUtils.getRegion("/Portfolios");
params[0] = region.values();
Object result = query.execute(params);
if(result instanceof Collection){
int resultSize = ((Collection)result).size();
if( resultSize != region.values().size())
fail("Results not as expected");
}else
fail("Invalid result");
}
示例21
static
public <K, V extends Number> Map.Entry<K, Value<V>> getWinner(Type type, Collection<Map.Entry<K, Value<V>>> entries){
Ordering<Map.Entry<K, Value<V>>> ordering = Classification.<K, V>createOrdering(type);
try {
return ordering.max(entries);
} catch(NoSuchElementException nsee){
return null;
}
}
示例22
private static void decodeByteSegment(BitSource bits, StringBuilder result, int count,
CharacterSetECI currentCharacterSetECI, Collection<byte[]> byteSegments, Map<DecodeHintType, ?> hints)
throws FormatException {
// Don't crash trying to read more bits than we have available.
if (8 * count > bits.available()) {
throw FormatException.getFormatInstance();
}
byte[] readBytes = new byte[count];
for (int i = 0; i < count; i++) {
readBytes[i] = (byte) bits.readBits(8);
}
String encoding;
if (currentCharacterSetECI == null) {
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessEncoding(readBytes, hints);
} else {
encoding = currentCharacterSetECI.name();
}
try {
result.append(new String(readBytes, encoding));
} catch (UnsupportedEncodingException ignored) {
throw FormatException.getFormatInstance();
}
byteSegments.add(readBytes);
}
示例23
private Optional<String> canAnyPassThroughCanal(
final CanalAttachment canalAttachment,
final Collection<Unit> units,
final GamePlayer player) {
if (units.stream().anyMatch(Matches.unitIsOfTypes(canalAttachment.getExcludedUnits()))) {
return Optional.empty();
}
return checkCanalStepAndOwnership(canalAttachment, player);
}
示例24
@Override
public short aggregate(short[] values, short nodata)
{
boolean data0 = values[0] != nodata;
boolean data1 = values[1] != nodata;
boolean data2 = values[2] != nodata;
boolean data3 = values[3] != nodata;
Collection<Integer> averages = new ArrayList<>();
if (data0 && data1)
{
averages.add((values[0] + values[1]) / 2);
}
if (data0 && data2)
{
averages.add((values[0] + values[2]) / 2);
}
if (data0 && data3)
{
averages.add((values[0] + values[3]) / 2);
}
if (data1 && data2)
{
averages.add((values[1] + values[2]) / 2);
}
if (data1 && data3)
{
averages.add((values[1] + values[3]) / 2);
}
if (data2 && data3)
{
averages.add((values[2] + values[3]) / 2);
}
return (averages.isEmpty()) ? nodata : Collections.min(averages).shortValue();
}
示例25
@SuppressWarnings("checkstyle:IllegalCatch")
public AbstractTransactCommand getClone() {
try {
return getClass().getConstructor(HwvtepOperationalState.class, Collection.class)
.newInstance(hwvtepOperationalState, changes);
} catch (Throwable e) {
LOG.error("Failed to clone the cmd ", e);
}
return this;
}
示例26
public Collection<String> getResourcesAsStrings() {
if (resources == null) {
findResources();
}
return CollectionUtils.collect(resources, new Transformer<URL, String>() {
@Override
public String transform(URL url) {
try {
return URLDecoder.decode(url.toString(), "utf-8");
} catch (UnsupportedEncodingException uee) {
throw new OntopiaRuntimeException(uee);
}
}
});
}
示例27
/**
* Zip up all of the simple linear chains present in this graph.
*
* Merges together all pairs of vertices in the graph v1 -> v2 into a single vertex v' containing v1 + v2 sequence
*
* Only works on vertices where v1's only outgoing edge is to v2 and v2's only incoming edge is from v1.
*
* If such a pair of vertices is found, they are merged and the graph is update. Otherwise nothing is changed.
*
* @return true if any such pair of vertices could be found, false otherwise
*/
public boolean zipLinearChains() {
// create the list of start sites [doesn't modify graph yet]
final Collection<SeqVertex> zipStarts = new LinkedList<>();
for ( final SeqVertex source : vertexSet() ) {
if ( isLinearChainStart(source) ) {
zipStarts.add(source);
}
}
if ( zipStarts.isEmpty() ) // nothing to do, as nothing could start a chain
{
return false;
}
// At this point, zipStarts contains all of the vertices in this graph that might start some linear
// chain of vertices. We walk through each start, building up the linear chain of vertices and then
// zipping them up with mergeLinearChain, if possible
boolean mergedOne = false;
for ( final SeqVertex zipStart : zipStarts ) {
final LinkedList<SeqVertex> linearChain = traceLinearChain(zipStart);
// merge the linearized chain, recording if we actually did some useful work
mergedOne |= mergeLinearChain(linearChain);
}
return mergedOne;
}
示例28
@Override
public Set<TimelineEntityGroupId> getTimelineEntityGroupId(String entityType,
NameValuePair primaryFilter,
Collection<NameValuePair> secondaryFilters) {
if (!knownEntityTypes.contains(entityType)
|| primaryFilter == null
|| !knownEntityTypes.contains(primaryFilter.getName())
|| summaryEntityTypes.contains(entityType)) {
return null;
}
return convertToTimelineEntityGroupIds(primaryFilter.getName(), primaryFilter.getValue().toString());
}
示例29
@Test
public void deliverShouldWork() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
HOST_ADDRESS_1,
HOST_ADDRESS_2).iterator();
when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class)))
.thenReturn(ExecutionResult.success());
ExecutionResult executionResult = testee.deliver(mail);
verify(mailDelivrerToHost, times(1)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.SUCCESS);
}
示例30
@Override
public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) {
LinkedHashSet<Symbol> toKeep = new LinkedHashSet<>(outputsToKeep);
SymbolVisitors.intersection(query, source.outputs(), toKeep::add);
LogicalPlan newSource = source.pruneOutputsExcept(tableStats, toKeep);
if (newSource == source) {
return this;
}
return new Filter(newSource, query);
}