Java Code Examples for com.google.common.collect.ImmutableSet

The following are top voted examples for showing how to use com.google.common.collect.ImmutableSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: athena   File: HostResourceTest.java   View source code 7 votes vote down vote up
/**
 * 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));
}
 
Example 2
Project: tac-kbp-eal   File: AnswerKey.java   View source code 6 votes vote down vote up
/**
 * 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, 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, assessedResponsesSet,
        Sets.difference(unassessedResponseSet, assessedResponses),
        corefAnnotation);
  }

}
 
Example 3
Project: googles-monorepo-demo   File: SubscriberRegistry.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 4
Project: Elasticsearch   File: Multibinder.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: de.flapdoodle.solid   File: Blobs.java   View source code 6 votes vote down vote up
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();
	}
 
Example 6
Project: QDrill   File: TestLocalExchange.java   View source code 6 votes vote down vote up
/** 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());
  }
}
 
Example 7
Project: athena   File: AbstractCorsaPipeline.java   View source code 6 votes vote down vote up
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();
}
 
Example 8
Project: n4js   File: TokenTypeRewriter.java   View source code 6 votes vote down vote up
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);
					}
				}
			}
		}
	}
}
 
Example 9
Project: BUILD_file_generator   File: UserDefinedResolverTest.java   View source code 6 votes vote down vote up
/**
 * 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");
  }
}
 
Example 10
Project: GitHub   File: EncodingInfo.java   View source code 6 votes vote down vote up
@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);
}
 
Example 11
Project: servicebuilder   File: UserTokenFilter.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 12
Project: tac-kbp-eal   File: ScoringDataTransformations.java   View source code 6 votes vote down vote up
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() {

    }
  };
}
 
Example 13
Project: AdvancedDataProfilingSeminar   File: BellBrockhausenTest.java   View source code 6 votes vote down vote up
@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"), Range.closed(1, 4), INTEGER);
    Attribute attributeC = new Attribute(new ColumnIdentifier(TABLE_NAME, "d"), Range.closed("b", "c"), TEXT);
    Attribute attributeD = new Attribute(new ColumnIdentifier(TABLE_NAME, "c"), 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));
}
 
Example 14
Project: QDrill   File: DrillRuleSets.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 15
Project: dremio-oss   File: IndexKey.java   View source code 6 votes vote down vote up
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])));
  }
}
 
Example 16
Project: java-monitoring-client-library   File: AbstractMetric.java   View source code 5 votes vote down vote up
AbstractMetric(
    String name,
    String description,
    String valueDisplayName,
    Kind kind,
    ImmutableSet<LabelDescriptor> labels,
    Class<V> valueClass) {
  this.metricSchema = MetricSchema.create(name, description, valueDisplayName, kind, labels);
  this.valueClass = valueClass;
}
 
Example 17
Project: guava-mock   File: PrimitivesTest.java   View source code 5 votes vote down vote up
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) {
  }
}
 
Example 18
Project: googles-monorepo-demo   File: AbstractGraphTest.java   View source code 5 votes vote down vote up
@Test
public void addNode_existingNode() {
  addNode(N1);
  ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes());
  assertThat(addNode(N1)).isFalse();
  assertThat(graph.nodes()).containsExactlyElementsIn(nodes);
}
 
Example 19
Project: athena   File: SfcwebUiTopovMessageHandler.java   View source code 5 votes vote down vote up
@Override
protected Collection<RequestHandler> createRequestHandlers() {
    return ImmutableSet.of(
            new DisplayStartHandler(),
            new DisplayStopHandler(),
            new ConfigSfpMsg()
    );
}
 
Example 20
Project: ArchUnit   File: JavaClassTest.java   View source code 5 votes vote down vote up
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();
}
 
Example 21
Project: googles-monorepo-demo   File: ClassPath.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 22
Project: alfresco-test-assertions   File: WorkflowAssertTest.java   View source code 5 votes vote down vote up
@Test
public void test_workflow_conditions() {
    WorkflowAssert.assertThat(workflowInstance)
                    .isInitiator(AuthenticationUtil.getAdminUserName())
                    .hasDescription(DESCRIPTION)
                    .hasNumberOfPackageItems(2)
                    .hasPackageItemAttached(attachment1)
                    .hasPackageItemsAttached(ImmutableSet.of(attachment1, attachment2));
}
 
Example 23
Project: java-monitoring-client-library   File: MutableDistributionTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 24
Project: carml   File: PredicateObjectMapperTest.java   View source code 5 votes vote down vote up
@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, ownGraphIri, subjectGraphIri);
	Set<IRI> ownContext = ImmutableSet.of(ownGraphIri, subjectGraphIri, 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, evaluator, subjectIRI, expectedContext);

}
 
Example 25
Project: Elasticsearch   File: ParentChildIndexFieldData.java   View source code 5 votes vote down vote up
@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);
}
 
Example 26
Project: NullAway   File: LibraryModelsHandler.java   View source code 5 votes vote down vote up
@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();
}
 
Example 27
Project: athena   File: FlowsResourceTest.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: guava-mock   File: PredicatesTest.java   View source code 5 votes vote down vote up
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();
}
 
Example 29
Project: ditb   File: ReplicationLogCleaner.java   View source code 5 votes vote down vote up
/**
 * 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));
  }
}
 
Example 30
Project: ProjectAres   File: PlayerClass.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: athena   File: PceManagerTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 32
Project: reflect   File: Utils.java   View source code 5 votes vote down vote up
public static ImmutableSet<Method> toMethods(Iterable<Class<?>> classes) {
  return FluentIterable.from(classes)
      .transformAndConcat(
          new Function<Class<?>, ImmutableSet<Method>>() {
            @Override
            public ImmutableSet<Method> apply(Class<?> c) {
              return Reflect.methods(c);
            }
          })
      .toSet();
}
 
Example 33
Project: ProjectAres   File: Methods.java   View source code 5 votes vote down vote up
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();
}
 
Example 34
Project: json2java4idea   File: Configuration.java   View source code 5 votes vote down vote up
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;
}
 
Example 35
Project: Reer   File: FileToArchiveEntrySetTransformer.java   View source code 5 votes vote down vote up
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();
}
 
Example 36
Project: tac-kbp-eal   File: OnlyMostSpecificTemporal.java   View source code 5 votes vote down vote up
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();
}
 
Example 37
Project: pyplyn   File: ConfigurationUpdateManager.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 38
Project: hashsdn-controller   File: ShardedDOMDataWriteTransaction.java   View source code 5 votes vote down vote up
@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;
}
 
Example 39
Project: athena   File: HostHandler.java   View source code 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example 40
Project: tac-kbp-eal   File: KBPEATestUtils.java   View source code 5 votes vote down vote up
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);
}