项目:athena
文件:HostResourceTest.java
/**
* Tests fetch of one host by mac and vlan.
*/
@Test
public void testSingleHostByMacAndVlanFetch() {
final ProviderId pid = new ProviderId("of","foo");
final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01");
final Set<IpAddress> ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::"));
final Host host1 =
new DefaultHost(pid,HostId.hostId(mac1),valueOf(1),vlanId((short) 1),new HostLocation(deviceid.deviceid("1"),portNumber(11),1),ips1);
hosts.add(host1);
expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1")))
.andReturn(host1)
.anyTimes();
replay(mockHostService);
WebTarget wt = target();
String response = wt.path("hosts/00:00:11:00:00:01/1").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertthat(result,matchesHost(host1));
}
项目:tac-kbp-eal
文件:AnswerKey.java
/**
* Creates an {@code AnswerKey} where the same response may appear both as assessed and
* unassessed. This removes any such tuples from the unassessed set before calling {@link
* #from(com.bbn.bue.common.symbols.Symbol,Iterable,CorefAnnotation)}. This is simply
* provided for convenience.
*/
public static AnswerKey fromPossiblyOverlapping(Symbol docID,Iterable<AssessedResponse> assessed,Iterable<Response> unassessedResponses,CorefAnnotation corefAnnotation) {
final ImmutableSet<AssessedResponse> assessedResponsesSet = ImmutableSet.copyOf(assessed);
final ImmutableSet<Response> unassessedResponseSet = ImmutableSet.copyOf(unassessedResponses);
final Set<Response> assessedResponses = FluentIterable.from(assessedResponsesSet)
.transform(AssessedResponseFunctions.response()).toSet();
if (Sets.intersection(assessedResponses,unassessedResponseSet).isEmpty()) {
return from(docID,assessedResponsesSet,unassessedResponseSet,corefAnnotation);
} else {
return from(docID,Sets.difference(unassessedResponseSet,assessedResponses),corefAnnotation);
}
}
/**
* Gets an iterator representing an immutable snapshot of all subscribers to the given event at
* the time this method is called.
*/
Iterator<Subscriber> getSubscribers(Object event) {
ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass());
List<Iterator<Subscriber>> subscriberIterators =
Lists.newArrayListWithCapacity(eventTypes.size());
for (Class<?> eventType : eventTypes) {
copyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);
if (eventSubscribers != null) {
// eager no-copy snapshot
subscriberIterators.add(eventSubscribers.iterator());
}
}
return Iterators.concat(subscriberIterators.iterator());
}
项目:Elasticsearch
文件:Multibinder.java
/**
* Invoked by Guice at Injector-creation time to prepare providers for each
* element in this set. At this time the set's size is kNown,but its
* contents are only evaluated when get() is invoked.
*/
@Inject
public void initialize(Injector injector) {
providers = new ArrayList<>();
List<Dependency<?>> dependencies = new ArrayList<>();
for (Binding<?> entry : injector.findBindingsByType(elementType)) {
if (keyMatches(entry.getKey())) {
@SuppressWarnings("unchecked") // protected by findBindingsByType()
Binding<T> binding = (Binding<T>) entry;
providers.add(binding.getProvider());
dependencies.add(Dependency.get(binding.getKey()));
}
}
this.dependencies = ImmutableSet.copyOf(dependencies);
this.binder = null;
}
public static ImmutableSet<?> propertyOf(Blob blob,Function<String,Collection<String>> pathPropertyMapping,PropertyCollectionResolver propertyResolver,String propertyName) {
Collection<String> aliasList = pathPropertyMapping.apply(propertyName);
for (String alias : aliasList) {
// if (alias.equals("filename")) {
// return ImmutableSet.of(blob.filename());
// }
// if (alias.equals("path")) {
// return ImmutableSet.of(Joiner.on('/').join(blob.path()));
// }
ImmutableSet<?> resolved = propertyResolver.resolve(blob.Meta(),Splitter.on('.').split(alias));
if (!resolved.isEmpty()) {
return resolved;
}
}
return ImmutableSet.of();
}
项目:QDrill
文件:TestLocalExchange.java
/** Helper method to verify the number of PartitionSenders in a given fragment endpoint assignments */
private static void verifyAssignment(List<Integer> fragmentList,ArrayListMultimap<Integer,DrillbitEndpoint> partitionSenderMap) {
// We expect at least one entry the list
assertTrue(fragmentList.size() > 0);
for(Integer majorFragmentId : fragmentList) {
// we expect the fragment that has DeMux/HashToRandom as sending exchange to have parallelization with not more
// than the number of nodes in the cluster and each node in the cluster can have at most one assignment
List<DrillbitEndpoint> assignments = partitionSenderMap.get(majorFragmentId);
assertNotNull(assignments);
assertTrue(assignments.size() > 0);
assertTrue(String.format("Number of partition senders in major fragment [%d] is more than expected",majorFragmentId),CLUSTER_SIZE >= assignments.size());
// Make sure there are no duplicates in assigned endpoints (i.e at most one partition sender per endpoint)
assertTrue("Some endpoints have more than one fragment that has ParitionSender",ImmutableSet.copyOf(assignments).size() == assignments.size());
}
}
项目:athena
文件:AbstractCorsaPipeline.java
private Collection<FlowRule> processspecific(ForwardingObjective fwd) {
log.debug("Processing specific forwarding objective");
TrafficSelector selector = fwd.selector();
EthTypeCriterion ethType =
(EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
if (ethType != null) {
short et = ethType.ethType().toShort();
if (et == Ethernet.TYPE_IPV4) {
return processspecificRoute(fwd);
} else if (et == Ethernet.TYPE_VLAN) {
/* The ForwardingObjective must specify VLAN ethtype in order to use the Transit Circuit */
return processspecificSwitch(fwd);
}
}
fail(fwd,ObjectiveError.UNSUPPORTED);
return ImmutableSet.of();
}
项目:n4js
文件:TokenTypeRewriter.java
private static void rewriteIdentifiers(N4JSGrammaraccess ga,ImmutableMap.Builder<AbstractElement,Integer> builder) {
ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of(
ga.getBindingIdentifierRule(),ga.getIdentifierNameRule(),ga.getIDENTIFIERRule());
for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
if (obj instanceof Assignment) {
Assignment assignment = (Assignment) obj;
AbstractElement terminal = assignment.getTerminal();
int type = InternalN4JSParser.RULE_IDENTIFIER;
if (terminal instanceof CrossReference) {
terminal = ((CrossReference) terminal).getTerminal();
type = IDENTIFIER_REF_TOKEN;
}
if (terminal instanceof RuleCall) {
AbstractRule calledRule = ((RuleCall) terminal).getRule();
if (identifierRules.contains(calledRule)) {
builder.put(assignment,type);
}
}
}
}
}
}
项目:BUILD_file_generator
文件:UserDefinedResolverTest.java
/**
* Tests behavior when a class is mapped to multiple rules. A runtime exception should be thrown.
*/
@Test
public void classMappedToMultipleRules() {
ImmutableList<String> lines =
ImmutableList.of(
"com.test.stuff,//java/com/test/stuff:target","com.test.stuff,//java/com/test/other:target");
try {
(new UserDefinedResolver(lines)).resolve((ImmutableSet.of("com.test.stuff")));
fail("Expected an exception,but nothing was thrown");
} catch (IllegalArgumentException e) {
assertthat(e)
.hasMessageThat()
.isEqualTo(
"com.test.stuff mapped to multiple targets: //java/com/test/other:target,"
+ "//java/com/test/stuff:target");
}
}
项目:GitHub
文件:EncodingInfo.java
@Derived
@Auxiliary
ImmutableSet<String> crossReferencedMethods() {
Set<String> referenced = new HashSet<>();
for (EncodedElement e : element()) {
for (Term t : e.code()) {
if (t.isBinding()) {
Code.Binding b = (Code.Binding) t;
if (b.isMethod()) {
referenced.add(b.identifier());
}
}
}
}
return ImmutableSet.copyOf(referenced);
}
项目:servicebuilder
文件:UserTokenFilter.java
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String usertokenId = requestContext.getHeaderString(Constants.USERTOKENID_HEADER);
if (Strings.isNullOrEmpty(usertokenId)) {
return;
}
UserToken userToken;
try {
userToken = tokenServiceClient.getUserTokenById(usertokenId);
} catch (TokenServiceClientException e) {
throw new NotAuthorizedException("UsertokenId: '" + usertokenId + "' not valid",e);
}
UibBrukerPrincipal brukerPrincipal = UibBrukerPrincipal.ofUserToken(userToken);
ImmutableSet<String> tilganger = extractRolesAllowed(userToken,brukerPrincipal.uibBruker);
requestContext.setSecurityContext(new AutentiseringsContext(brukerPrincipal,tilganger));
if (authenticatedHandler != null) {
authenticatedHandler.handle(requestContext);
}
}
项目:tac-kbp-eal
文件:ScoringDataTransformations.java
public static ScoringDataTransformation applyPredicatetoSystemOutput(
final Predicate<Response> responsePredicate) {
return new ScoringDataTransformation() {
@Override
public ScoringData transform(final ScoringData scoringData) {
checkArgument(scoringData.argumentOutput().isPresent(),"System output must be present");
final ImmutableSet.Builder<Response> toDelete = ImmutableSet.builder();
for (final Response r : scoringData.argumentOutput().get().responses()) {
if (!responsePredicate.apply(r)) {
toDelete.add(r);
}
}
return ScoringData.builder().from(scoringData).argumentOutput(
ResponseMapping.delete(toDelete.build())
.apply(scoringData.argumentOutput().get())).build();
}
@Override
public void logStats() {
}
};
}
@Test
public void testTableWithMixedTypes(DataAccessObject dataAccessObject) throws AlgorithmExecutionException {
// GIVEN
Attribute attributeA = new Attribute(new ColumnIdentifier(TABLE_NAME,"a"),Range.closed(1,3),INTEGER);
Attribute attributeB = new Attribute(new ColumnIdentifier(TABLE_NAME,"b"),4),INTEGER);
Attribute attributeC = new Attribute(new ColumnIdentifier(TABLE_NAME,"d"),Range.closed("b","c"),TEXT);
Attribute attributeD = new Attribute(new ColumnIdentifier(TABLE_NAME,Range.closed("a","z"),TEXT);
ImmutableList<Attribute> attributes = ImmutableList.of(attributeA,attributeB,attributeC,attributeD);
TableInfo tableInfo = new TableInfo(TABLE_NAME,attributes);
InclusionDependency indAB = toInd(attributeA.getColumnIdentifier(),attributeB.getColumnIdentifier());
InclusionDependency indCD = toInd(attributeC.getColumnIdentifier(),attributeD.getColumnIdentifier());
ImmutableSet<InclusionDependency> validinds = ImmutableSet.of(indAB,indCD);
when(dataAccessObject.isValidUIND(any(InclusionDependency.class)))
.thenAnswer(invocation -> validinds.contains(invocation.<InclusionDependency>getArgument(0)));
// WHEN
when(dataAccessObject.getTableInfo(TABLE_NAME)).thenReturn(tableInfo);
bellbrockhausen.execute();
// THEN
assertthat(resultReceiver.getReceivedResults()).containsExactlyInAnyOrder(toArray(validinds));
}
项目:QDrill
文件:DrillRuleSets.java
/**
* Get a list of logical rules that can be turned on or off by session/system options.
*
* If a rule is intended to always be included with the logical set,it should be added
* to the immutable list created in the getDrillBasicrules() method below.
*
* @param optimizerRulesContext - used to get the list of planner settings,other rules may
* also in the future need to get other query state from this,* such as the available list of UDFs (as is used by the
* DrillMergeProjectRule created in getDrillBasicrules())
* @return - a list of rules that have been filtered to leave out
* rules that have been turned off by system or session settings
*/
public static RuleSet getDrillUserConfigurableLogicalRules(OptimizerRulesContext optimizerRulesContext) {
final PlannerSettings ps = optimizerRulesContext.getPlannerSettings();
// This list is used to store rules that can be turned on an off
// by user facing planning options
final Builder<RelOptRule> userConfigurableRules = ImmutableSet.<RelOptRule>builder();
if (ps.isConstantFoldingEnabled()) {
// Todo - DRILL-2218
userConfigurableRules.add(ReduceExpressionsRule.PROJECT_INSTANCE);
userConfigurableRules.add(DrillReduceExpressionsRule.FILTER_INSTANCE_DRILL);
userConfigurableRules.add(DrillReduceExpressionsRule.CALC_INSTANCE_DRILL);
}
return new DrillRuleSet(userConfigurableRules.build());
}
项目:dremio-oss
文件:IndexKey.java
void addTodoc(Document doc,String... values){
Preconditions.checkArgument(valueType == String.class);
if (isSorted()) {
Preconditions.checkArgument(values.length < 2,"sorted fields cannot have multiple values");
}
// add distinct elements to doc
final Iterable<String> nonNull = FluentIterable.from(Arrays.asList(values))
.filter(new Predicate<String>() {
@Override
public boolean apply(@Nullable final String input) {
return input != null;
}
});
for (final String value : ImmutableSet.copyOf(nonNull)) {
final String truncatedValue = StringUtils.abbreviate(value,MAX_STRING_LENGTH);
doc.add(new StringField(indexFieldName,truncatedValue,stored ? Store.YES : Store.NO));
}
if (isSorted() && values.length == 1) {
Preconditions.checkArgument(sortedValueType == SearchFieldSorting.FieldType.STRING);
doc.add(new SortedDocValuesField(indexFieldName,new BytesRef(values[0])));
}
}
项目:java-monitoring-client-library
文件:AbstractMetric.java
项目:guava-mock
文件:PrimitivesTest.java
public void testAllWrapperTypes() {
Set<Class<?>> wrappers = Primitives.allWrapperTypes();
assertEquals(
ImmutableSet.<Object>of(
Boolean.class,Byte.class,Character.class,Double.class,Float.class,Integer.class,Long.class,Short.class,Void.class),wrappers);
try {
wrappers.remove(Boolean.class);
fail();
} catch (UnsupportedOperationException expected) {
}
}
@Test
public void addNode_existingNode() {
addNode(N1);
ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes());
assertthat(addNode(N1)).isFalse();
assertthat(graph.nodes()).containsExactlyElementsIn(nodes);
}
项目:athena
文件:SfcwebUiTopovMessageHandler.java
SELF evaluationToType(Class<?> secondType) {
Class<?>[] types = ImmutableSet.<Class<?>>builder()
.addAll(additionalTypes).add(firstType).add(secondType)
.build().toArray(new Class<?>[0]);
JavaClass javaClass = importClassesWithContext(types).get(secondType);
for (DescribedPredicate<JavaClass> predicate : assignable) {
assignableAssertion.add(assertthat(predicate.apply(javaClass))
.as(message + secondType.getSimpleName()));
}
return self();
}
/**
* Returns all top level classes whose package name is {@code packageName} or starts with
* {@code packageName} followed by a '.'.
*/
public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) {
checkNotNull(packageName);
String packagePrefix = packageName + '.';
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
for (ClassInfo classInfo : getTopLevelClasses()) {
if (classInfo.getName().startsWith(packagePrefix)) {
builder.add(classInfo);
}
}
return builder.build();
}
项目:alfresco-test-assertions
文件:WorkflowAssertTest.java
@Test
public void test_workflow_conditions() {
WorkflowAssert.assertthat(workflowInstance)
.isInitiator(AuthenticationUtil.getAdminUserName())
.hasDescription(DESCRIPTION)
.hasNumberOfPackageItems(2)
.hasPackageItemAttached(attachment1)
.hasPackageItemsAttached(ImmutableSet.of(attachment1,attachment2));
}
@Test
public void testAdd_oneFiniteInterval_overflowValue_returnsOverflowInterval() throws Exception {
Mutabledistribution distribution =
new Mutabledistribution(CustomFitter.create(ImmutableSet.of(1.0,5.0)));
distribution.add(10.0);
assertthat(distribution.intervalCounts())
.isEqualTo(
ImmutableRangeMap.<Double,Long>builder()
.put(Range.lessthan(1.0),0L)
.put(Range.closedOpen(1.0,5.0),0L)
.put(Range.atLeast(5.0),1L)
.build());
}
@Test
public void map_withPassedAndOwnGraphs_removesDuplicatesFromConcatenatedContext() throws Exception {
SimpleValueFactory f = SimpleValueFactory.getInstance();
IRI subjectIRI = f.createIRI("http://foo.bar/subjectIRI");
PredicateMapper childMapper = mock(PredicateMapper.class);
Model model = new ModelBuilder().build();
EvaluateExpression evaluator = null;
IRI subjectGraphIri = f.createIRI("http://subject.context/graph");
IRI ownGraphIri = f.createIRI("http://own.context/graph");
Set<IRI> subjectContext = ImmutableSet.of(subjectGraphIri,ownGraphIri,subjectGraphIri);
Set<IRI> ownContext = ImmutableSet.of(ownGraphIri,subjectGraphIri,ownGraphIri);
IRI[] expectedContext = new IRI[] { subjectGraphIri,ownGraphIri };
Set<TermGenerator<IRI>> ownGraphGenerators = ownContext.stream()
.map(graphIri -> {
@SuppressWarnings("unchecked")
TermGenerator<IRI> generator = (TermGenerator<IRI>) mock(TermGenerator.class);
when(generator.apply(evaluator)).thenReturn(Optional.of(graphIri)).getMock();
return generator;
})
.collect(ImmutableCollectors.toImmutableSet());
PredicateObjectMapper testSubject = new PredicateObjectMapper(ownGraphGenerators,ImmutableSet.of(childMapper));
testSubject.map(model,evaluator,subjectIRI,subjectContext);
verify(childMapper).map(model,expectedContext);
}
@Override
public IndexParentChildFieldData localGlobalDirect(DirectoryReader indexReader) throws Exception {
final long startTime = System.nanoTime();
final Set<String> parentTypes;
if (Version.indexCreated(indexSettings()).before(Version.V_2_0_0_beta1)) {
synchronized (lock) {
parentTypes = ImmutableSet.copyOf(this.parentTypes);
}
} else {
parentTypes = this.parentTypes;
}
long ramBytesUsed = 0;
final Map<String,OrdinalMapAndAtomicFieldData> perType = new HashMap<>();
for (String type : parentTypes) {
final AtomicParentChildFieldData[] fieldData = new AtomicParentChildFieldData[indexReader.leaves().size()];
for (LeafReaderContext context : indexReader.leaves()) {
fieldData[context.ord] = load(context);
}
final OrdinalMap ordMap = buildOrdinalMap(fieldData,type);
ramBytesUsed += ordMap.ramBytesUsed();
perType.put(type,new OrdinalMapAndAtomicFieldData(ordMap,fieldData));
}
final AtomicParentChildFieldData[] fielddata = new AtomicParentChildFieldData[indexReader.leaves().size()];
for (int i = 0; i < fielddata.length; ++i) {
fielddata[i] = new GlobalAtomicFieldData(parentTypes,perType,i);
}
breakerService.getBreaker(CircuitBreaker.FIELDDATA).addWithoutBreaking(ramBytesUsed);
if (logger.isDebugEnabled()) {
logger.debug(
"Global-ordinals[_parent] took {}",new TimeValue(System.nanoTime() - startTime,TimeUnit.NANOSECONDS)
);
}
return new GlobalFieldData(indexReader,fielddata,ramBytesUsed,perType);
}
项目:NullAway
文件:LibraryModelsHandler.java
@Override
public ImmutableSet<Integer> onUnannotatedInvocationGetNonNullPositions(
NullAway analysis,VisitorState state,Symbol.MethodSymbol methodSymbol,List<? extends ExpressionTree> actualParams,ImmutableSet<Integer> nonNullPositions) {
return Sets.union(
nonNullPositions,libraryModels.nonNullParameters().get(LibraryModels.MethodRef.fromSymbol(methodSymbol)))
.immutablecopy();
}
项目:athena
文件:FlowsResourceTest.java
/**
* Sets up the global values for all the tests.
*/
@Before
public void setUptest() {
// Mock device service
expect(mockDeviceService.getDevice(deviceid1))
.andReturn(device1);
expect(mockDeviceService.getDevice(deviceid2))
.andReturn(device2);
expect(mockDeviceService.getDevices())
.andReturn(ImmutableSet.of(device1,device2));
// Mock Core Service
expect(mockCoreService.getAppId(anyShort()))
.andReturn(NetTestTools.APP_ID).anyTimes();
expect(mockCoreService.getAppId(anyString()))
.andReturn(NetTestTools.APP_ID).anyTimes();
expect(mockCoreService.registerapplication(FlowRuleCodec.REST_APP_ID))
.andReturn(APP_ID).anyTimes();
replay(mockCoreService);
// Register the services needed for the test
final CodecManager codecService = new CodecManager();
codecService.activate();
ServiceDirectory testDirectory =
new TestServiceDirectory()
.add(FlowRuleService.class,mockFlowService)
.add(DeviceService.class,mockDeviceService)
.add(CodecService.class,codecService)
.add(CoreService.class,mockCoreService)
.add(applicationservice.class,mockapplicationservice);
BaseResource.setServiceDirectory(testDirectory);
}
项目:guava-mock
文件:PredicatesTest.java
public void testIn_equality() {
Collection<Integer> nums = ImmutableSet.of(1,5);
Collection<Integer> sameOrder = ImmutableSet.of(1,5);
Collection<Integer> differentOrder = ImmutableSet.of(5,1);
Collection<Integer> differentNums = ImmutableSet.of(1,3,5);
new EqualsTester()
.addEqualityGroup(Predicates.in(nums),Predicates.in(nums),Predicates.in(sameOrder),Predicates.in(differentOrder))
.addEqualityGroup(Predicates.in(differentNums))
.testEquals();
}
项目:ditb
文件:ReplicationLogCleaner.java
/**
* Load all wals in all replication queues from ZK. This method guarantees to return a
* snapshot which contains all WALs in the zookeeper at the start of this call even there
* is concurrent queue failover. However,some newly created WALs during the call may
* not be included.
*/
private Set<String> loadWALsFromQueues() throws KeeperException {
for (int retry = 0; ; retry++) {
int v0 = replicationQueues.getQueuesZNodeCversion();
List<String> RSS = replicationQueues.getlistofReplicators();
if (RSS == null) {
LOG.debug("Didn't find any region server that replicates,won't prevent any deletions.");
return ImmutableSet.of();
}
Set<String> wals = Sets.newHashSet();
for (String rs : RSS) {
List<String> listofPeers = replicationQueues.getAllQueues(rs);
// if rs just died,this will be null
if (listofPeers == null) {
continue;
}
for (String id : listofPeers) {
List<String> peersWals = replicationQueues.getLogsInQueue(rs,id);
if (peersWals != null) {
wals.addAll(peersWals);
}
}
}
int v1 = replicationQueues.getQueuesZNodeCversion();
if (v0 == v1) {
return wals;
}
LOG.info(String.format("Replication queue node cversion changed from %d to %d,retry = %d",v0,v1,retry));
}
}
项目:ProjectAres
文件:PlayerClass.java
public PlayerClass(String name,String category,@Nullable String description,@Nullable String longDescription,boolean sticky,Set<Kit> kits,MaterialData icon,boolean restrict) {
this.name = checkNotNull(name,"name");
this.category = checkNotNull(category,"family name");
this.description = description;
this.longDescription = longDescription;
this.sticky = sticky;
this.kits = ImmutableSet.copyOf(checkNotNull(kits,"kits"));
this.icon = checkNotNull(icon,"icon");
this.restrict = restrict;
}
项目:athena
文件:PceManagerTest.java
@Override
public Collection<Tunnel> queryTunnel(TunnelEndPoint src,TunnelEndPoint dst) {
Collection<Tunnel> result = new HashSet<Tunnel>();
Tunnel tunnel = null;
for (TunnelId tunnelId : tunnelIdaskeyStore.keySet()) {
tunnel = tunnelIdaskeyStore.get(tunnelId);
if ((null != tunnel) && (src.equals(tunnel.src())) && (dst.equals(tunnel.dst()))) {
result.add(tunnel);
}
}
return result.size() == 0 ? Collections.emptySet() : ImmutableSet.copyOf(result);
}
项目:reflect
文件:Utils.java
项目:ProjectAres
文件:Methods.java
public static Set<Method> ancestors(Method method) {
if(Members.isPrivate(method)) return Collections.emptySet();
final ImmutableSet.Builder<Method> builder = ImmutableSet.builder();
for(Class<?> ancestor : Types.ancestors(method.getDeclaringClass())) {
final Method sup = overrideIn(ancestor,method);
if(sup != null) builder.add(sup);
}
return builder.build();
}
private Configuration(@Nonnull Builder builder) {
style = builder.style;
classNamePolicy = builder.classNamePolicy;
fieldNamePolicy = builder.fieldNamePolicy;
methodNamePolicy = builder.methodNamePolicy;
parameterNamePolicy = builder.parameterNamePolicy;
annotationPolicies = ImmutableSet.copyOf(builder.annotationPolicies);
jsonParser = builder.jsonParser;
javaBuilder = builder.javaBuilder;
}
public Set<ArchiveEntry> transform(File archiveFile) {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(archiveFile);
} catch (FileNotFoundException e) {
throw new UncheckedioException(e);
}
ImmutableSet.Builder<ArchiveEntry> allEntries = ImmutableSet.builder();
walk(fileInputStream,allEntries,ImmutableList.<String>of());
return allEntries.build();
}
项目:tac-kbp-eal
文件:OnlyMostSpecificTemporal.java
private static ImmutableSet<TypeRoleFillerRealis> computeBannedResponseSignatures(
final AnswerKey key) {
final ImmutableSet.Builder<TypeRoleFillerRealis> bannedResponseSignatures =
ImmutableSet.builder();
for (final AssessedResponse response : key.annotatedResponses()) {
if (response.assessment().entityCorrectFiller().isPresent()
&& response.assessment().entityCorrectFiller().get().isAcceptable()
&& response.response().istemporal()) {
try {
final KBPTIMEXExpression time = KBPTIMEXExpression.parseTIMEX(
response.response().canonicalArgument().string());
final TypeRoleFillerRealis responseSignature = responseSignature(response.response());
for (final KBPTIMEXExpression lessspecificTimex : time.lessspecificCompatibleTimes()) {
bannedResponseSignatures.add(responseSignature.withArgumentCanonicalString(
KBPString.from(lessspecificTimex.toString(),DUMMY_OFFSETS)));
}
} catch (KBPTIMEXExpression.KBPTIMEXException timexException) {
log.warn(
"While applying only-most-specific-temporal rule,encountered an illegal temporal "
+ "expression " + response.response().canonicalArgument().string()
+ " which was evaluated as "
+ "correct. Such responses should have incorrect CAS assessments.");
}
}
}
return bannedResponseSignatures.build();
}
/**
* Ensures only tasks that should be running are running
*/
private void updateTasksAfterClusterEvent() {
logger.info("Synchronizing tasks on local node...");
// compute the difference between currently executing tasks and locally managed configurations
Set<Configuration> localConfigurations = get();
Set<Configuration> localTasks = taskManager.allTasks();
ImmutableSet.copyOf(Sets.difference(localTasks,localConfigurations))
// and delete all the tasks that should not run on the local node
.forEach(new DeleteTaskConsumer((always) -> true));
// upsert all local configurations,to ensure all that should be running are running
localConfigurations.forEach(new UpsertTaskConsumer((always) -> true));
}
项目:hashsdn-controller
文件:ShardedDOMDataWriteTransaction.java
@Override
public synchronized boolean cancel() {
if (closed) {
return false;
}
LOG.debug("Cancelling transaction {}",identifier);
for (DOMStoreWriteTransaction tx : ImmutableSet.copyOf(idToTransaction.values())) {
tx.close();
}
closed = true;
producer.cancelTransaction(this);
return true;
}
项目:athena
文件:HostHandler.java
/**
* Add per host route to subnet list and populate the flow rule if the host
* does not belong to the configured subnet.
*
* @param location location of the host being added
* @param ip IP address of the host being added
*/
private void addPerHostRoute(ConnectPoint location,Ip4Address ip) {
Ip4Prefix portsubnet = srManager.deviceConfiguration.getPortsubnet(
location.deviceid(),location.port());
if (portsubnet != null && !portsubnet.contains(ip)) {
Ip4Prefix ip4Prefix = ip.toIpPrefix().getIp4Prefix();
srManager.deviceConfiguration.addsubnet(location,ip4Prefix);
srManager.defaultRoutingHandler.populatesubnet(location,ImmutableSet.of(ip4Prefix));
}
}
项目:tac-kbp-eal
文件:KBPEATestUtils.java
public static AnswerKey minimalAnswerKeyFor(CorefAnnotation coref) {
final DummyResponseGenerator responseGenerator = new DummyResponseGenerator();
final ImmutableSet.Builder<Response> responses = ImmutableSet.builder();
for (final KBPString s : coref.allCASes()) {
responses.add(responseGenerator.responseFor(dummyTRFR(coref.docId(),s)));
}
final ImmutableSet<AssessedResponse> assessedResponses = FluentIterable
.from(responses.build())
.transform(dummyAnnotationFunction)
.toSet();
return AnswerKey.from(coref.docId(),assessedResponses,ImmutableSet.<Response>of(),coref);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。