java类com.google.common.collect.ImmutableSet的实例源码

HostResourceTest.java 文件源码 项目:athena 阅读 43 收藏 0 点赞 0 评论 0
/**
 * 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));
}
AnswerKey.java 文件源码 项目:tac-kbp-eal 阅读 45 收藏 0 点赞 0 评论 0
/**
 * 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);
  }

}
SubscriberRegistry.java 文件源码 项目:googles-monorepo-demo 阅读 40 收藏 0 点赞 0 评论 0
/**
 * 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());
}
Multibinder.java 文件源码 项目:Elasticsearch 阅读 40 收藏 0 点赞 0 评论 0
/**
 * 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;
}
Blobs.java 文件源码 项目:de.flapdoodle.solid 阅读 44 收藏 0 点赞 0 评论 0
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();
    }
TestLocalExchange.java 文件源码 项目:QDrill 阅读 37 收藏 0 点赞 0 评论 0
/** 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());
  }
}
AbstractCorsaPipeline.java 文件源码 项目:athena 阅读 40 收藏 0 点赞 0 评论 0
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();
}
TokenTypeRewriter.java 文件源码 项目:n4js 阅读 36 收藏 0 点赞 0 评论 0
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);
                    }
                }
            }
        }
    }
}
UserDefinedResolverTest.java 文件源码 项目:BUILD_file_generator 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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");
  }
}
EncodingInfo.java 文件源码 项目:GitHub 阅读 31 收藏 0 点赞 0 评论 0
@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);
}
UserTokenFilter.java 文件源码 项目:servicebuilder 阅读 44 收藏 0 点赞 0 评论 0
@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);
    }
}
ScoringDataTransformations.java 文件源码 项目:tac-kbp-eal 阅读 29 收藏 0 点赞 0 评论 0
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() {

    }
  };
}
BellBrockhausenTest.java 文件源码 项目:AdvancedDataProfilingSeminar 阅读 42 收藏 0 点赞 0 评论 0
@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));
}
DrillRuleSets.java 文件源码 项目:QDrill 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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());
}
IndexKey.java 文件源码 项目:dremio-oss 阅读 34 收藏 0 点赞 0 评论 0
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])));
  }
}
AbstractMetric.java 文件源码 项目:java-monitoring-client-library 阅读 36 收藏 0 点赞 0 评论 0
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;
}
PrimitivesTest.java 文件源码 项目:guava-mock 阅读 32 收藏 0 点赞 0 评论 0
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) {
  }
}
AbstractGraphTest.java 文件源码 项目:googles-monorepo-demo 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void addNode_existingNode() {
  addNode(N1);
  ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes());
  assertThat(addNode(N1)).isFalse();
  assertThat(graph.nodes()).containsExactlyElementsIn(nodes);
}
SfcwebUiTopovMessageHandler.java 文件源码 项目:athena 阅读 34 收藏 0 点赞 0 评论 0
@Override
protected Collection<RequestHandler> createRequestHandlers() {
    return ImmutableSet.of(
            new DisplayStartHandler(),
            new DisplayStopHandler(),
            new ConfigSfpMsg()
    );
}
JavaClassTest.java 文件源码 项目:ArchUnit 阅读 41 收藏 0 点赞 0 评论 0
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();
}
ClassPath.java 文件源码 项目:googles-monorepo-demo 阅读 51 收藏 0 点赞 0 评论 0
/**
 * 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();
}
WorkflowAssertTest.java 文件源码 项目:alfresco-test-assertions 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void test_workflow_conditions() {
    WorkflowAssert.assertThat(workflowInstance)
                    .isInitiator(AuthenticationUtil.getAdminUserName())
                    .hasDescription(DESCRIPTION)
                    .hasNumberOfPackageItems(2)
                    .hasPackageItemAttached(attachment1)
                    .hasPackageItemsAttached(ImmutableSet.of(attachment1, attachment2));
}
MutableDistributionTest.java 文件源码 项目:java-monitoring-client-library 阅读 33 收藏 0 点赞 0 评论 0
@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());
}
PredicateObjectMapperTest.java 文件源码 项目:carml 阅读 32 收藏 0 点赞 0 评论 0
@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);

}
ParentChildIndexFieldData.java 文件源码 项目:Elasticsearch 阅读 39 收藏 0 点赞 0 评论 0
@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);
}
LibraryModelsHandler.java 文件源码 项目:NullAway 阅读 29 收藏 0 点赞 0 评论 0
@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();
}
FlowsResourceTest.java 文件源码 项目:athena 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 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);
}
PredicatesTest.java 文件源码 项目:guava-mock 阅读 40 收藏 0 点赞 0 评论 0
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();
}
ReplicationLogCleaner.java 文件源码 项目:ditb 阅读 24 收藏 0 点赞 0 评论 0
/**
 * 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));
  }
}
PlayerClass.java 文件源码 项目:ProjectAres 阅读 41 收藏 0 点赞 0 评论 0
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;
}


问题


面经


文章

微信
公众号

扫码关注公众号