类com.google.common.collect.Lists源码实例Demo

下面列出了怎么用com.google.common.collect.Lists的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: onos   文件: CienaWaveserverDeviceDescription.java
public static PortDescription parseWaveServerCienaOchPorts(long portNumber,
                                                           HierarchicalConfiguration config,
                                                           SparseAnnotations annotations) {
    final List<String> tunableType = Lists.newArrayList("performance-optimized", "accelerated");
    final String flexGrid = "flex-grid";
    final String state = "properties.transmitter.state";
    final String tunable = "properties.modem.tx-tuning-mode";
    final String spacing = "properties.line-system.wavelength-spacing";
    final String frequency = "properties.transmitter.frequency.value";

    boolean isEnabled = config.getString(state).equals(ENABLED);
    boolean isTunable = tunableType.contains(config.getString(tunable));

    GridType gridType = config.getString(spacing).equals(flexGrid) ? GridType.FLEX : null;
    ChannelSpacing chSpacing = gridType == GridType.FLEX ? ChannelSpacing.CHL_6P25GHZ : null;

    //Working in Ghz //(Nominal central frequency - 193.1)/channelSpacing = spacingMultiplier
    final int baseFrequency = 193100;
    long spacingFrequency = chSpacing == null ? baseFrequency : chSpacing.frequency().asHz();
    int spacingMult = ((int) (toGbps(((int) config.getDouble(frequency) -
            baseFrequency)) / toGbpsFromHz(spacingFrequency))); //FIXME is there a better way ?

    return ochPortDescription(PortNumber.portNumber(portNumber), isEnabled, OduSignalType.ODU4, isTunable,
                              new OchSignal(gridType, chSpacing, spacingMult, 1), annotations);
}
 
@Test
public void testViewInform3() throws CouldntLoadDataException {
  final boolean starState2 = true;
  view.getConfiguration().setStaredInternal(starState2);
  assertEquals(starState2, view.getConfiguration().isStared());

  final ViewNotificationContainer container =
      new ViewNotificationContainer(view.getConfiguration().getId(),
          Optional.fromNullable(view),
          Optional.<Integer>absent(),
          Optional.<INaviModule>absent(),
          Optional.<INaviProject>absent(),
          "UPDATE");

  final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
  parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);

  assertEquals(false, view.getConfiguration().isStared());
}
 
@Test
public void scheduleLocationsMultipleAddsAlternate() throws Exception {
  HousekeepingCleanupLocationManager manager = new HousekeepingCleanupLocationManager(EVENT_ID, housekeepingListener,
      replicaCatalogListener, DATABASE, TABLE);
  String pathEventId = "pathEventId";
  Path path1 = new Path("location1");
  Path path2 = new Path("location2");

  manager.addCleanupLocation(pathEventId, path1);
  manager.scheduleLocations();
  verify(housekeepingListener).cleanUpLocation(EVENT_ID, pathEventId, path1, DATABASE, TABLE);
  List<URI> uris = Lists.newArrayList(path1.toUri());
  verify(replicaCatalogListener).deprecatedReplicaLocations(uris);

  manager.addCleanupLocation(pathEventId, path2);
  manager.scheduleLocations();
  verify(housekeepingListener).cleanUpLocation(EVENT_ID, pathEventId, path2, DATABASE, TABLE);
  List<URI> urisSecondCleanup = Lists.newArrayList(path2.toUri());
  verify(replicaCatalogListener).deprecatedReplicaLocations(urisSecondCleanup);
}
 
/**
 * 根据userState将userId分组
 * @param userStateReqs 修改用户状态的请求
 * @return 分组后结果(key:用户状态、value:该状态下对应的userid列表)
 */
private Map<Integer, List<String>> groupUserIdByUserState(BatchReq<UserStateReq> userStateReqs) {
    // 创建结果集
    Map<Integer, List<String>> userStateMap = Maps.newHashMap();

    // 遍历UserStateEnum
    if (UserStateEnum.values().length > 0) {
        for (UserStateEnum userStateEnum : UserStateEnum.values()) {
            // 获取当前用户状态下的所有userid
            List<String> userIdList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(userStateReqs.getReqList())) {
                for (UserStateReq userStateReq : userStateReqs.getReqList()) {
                    if (userStateReq.getUserState() == userStateEnum.getCode()) {
                        userIdList.add(userStateReq.getUserId());
                    }
                }
                userStateMap.put(userStateEnum.getCode(), userIdList);
            }
        }
    }

    return userStateMap;
}
 
源代码5 项目: joyqueue   文件: ProduceRequestHandler.java
protected void splitByPartitionGroup(TopicConfig topicConfig, TopicName topic, Producer producer, byte[] clientAddress, Traffic traffic,
                            ProduceRequest.PartitionRequest partitionRequest, Map<Integer, ProducePartitionGroupRequest> partitionGroupRequestMap) {
    PartitionGroup partitionGroup = topicConfig.fetchPartitionGroupByPartition((short) partitionRequest.getPartition());
    ProducePartitionGroupRequest producePartitionGroupRequest = partitionGroupRequestMap.get(partitionGroup.getGroup());

    if (producePartitionGroupRequest == null) {
        producePartitionGroupRequest = new ProducePartitionGroupRequest(Lists.newLinkedList(), Lists.newLinkedList(),
                Lists.newLinkedList(), Maps.newHashMap(), Maps.newHashMap());
        partitionGroupRequestMap.put(partitionGroup.getGroup(), producePartitionGroupRequest);
    }

    List<BrokerMessage> brokerMessages = Lists.newLinkedList();
    for (KafkaBrokerMessage message : partitionRequest.getMessages()) {
        BrokerMessage brokerMessage = KafkaMessageConverter.toBrokerMessage(producer.getTopic(), partitionRequest.getPartition(), producer.getApp(), clientAddress, message);
        brokerMessages.add(brokerMessage);
    }

    traffic.record(topic.getFullName(), partitionRequest.getTraffic(), partitionRequest.getSize());
    producePartitionGroupRequest.getPartitions().add(partitionRequest.getPartition());
    producePartitionGroupRequest.getMessages().addAll(brokerMessages);
    producePartitionGroupRequest.getMessageMap().put(partitionRequest.getPartition(), brokerMessages);
    producePartitionGroupRequest.getKafkaMessages().addAll(partitionRequest.getMessages());
    producePartitionGroupRequest.getKafkaMessageMap().put(partitionRequest.getPartition(), partitionRequest.getMessages());
}
 
源代码6 项目: onos   文件: FujitsuT100DeviceDescription.java
/**
 * Parses a configuration and returns a set of ports for the fujitsu T100.
 *
 * @param cfg a hierarchical configuration
 * @return a list of port descriptions
 */
private static List<PortDescription> parseFujitsuT100Ports(HierarchicalConfiguration cfg) {
    AtomicInteger counter = new AtomicInteger(1);
    List<PortDescription> portDescriptions = Lists.newArrayList();
    List<HierarchicalConfiguration> subtrees =
            cfg.configurationsAt("data.interfaces.interface");
    for (HierarchicalConfiguration portConfig : subtrees) {
        if (!portConfig.getString("name").contains("LCN") &&
                !portConfig.getString("name").contains("LMP") &&
                "ianaift:ethernetCsmacd".equals(portConfig.getString("type"))) {
            portDescriptions.add(parseT100OduPort(portConfig, counter.getAndIncrement()));
        } else if ("ianaift:otnOtu".equals(portConfig.getString("type"))) {
            portDescriptions.add(parseT100OchPort(portConfig, counter.getAndIncrement()));
        }
    }
    return portDescriptions;
}
 
源代码7 项目: kite   文件: TestSchemaCommandMerge.java
@Test
public void testSchemaMerge() throws Exception {
  command.datasets = Lists.newArrayList(
      schemaFile.toString(),
      "resource:schema/user.avsc");
  int rc = command.run();
  Assert.assertEquals("Should return success code", 0, rc);

  Schema merged = SchemaBuilder.record("user").fields()
      .optionalLong("id") // required in one, missing in the other
      .requiredString("username")
      .requiredString("email")
      .endRecord();

  verify(console).info(argThat(TestUtil.matchesSchema(merged)));
  verifyNoMoreInteractions(console);
}
 
源代码8 项目: accumulo-recipes   文件: AccumuloEntityStoreIT.java
@Test
public void test_createAndDeleteEntities() throws Exception {

    for (int i = 0; i < 10; i++) {
        Entity entity = EntityBuilder.create("type", "type_"+i)
                .attr(new Attribute("key1", "val1", meta))
                .attr(new Attribute("key2", "val2", meta))
                .build();

        store.save(singleton(entity));
    }
    store.flush();

    List<EntityIdentifier> typesAndIds = Arrays.asList(new EntityIdentifier("type", "type_0"),
            new EntityIdentifier("type", "type_1"), new EntityIdentifier("type", "type_2"));
    Iterable<Entity> actualEntities = store.get(typesAndIds, null, new Auths("A"));
    assertEquals(3,Iterables.size(actualEntities));

    store.delete(Lists.newArrayList(store.get(typesAndIds,new Auths("A"))));
    store.flush();

    Iterable<Entity> actualEntitiesAfterDelete = store.get(typesAndIds, null, new Auths("A"));
    assertEquals(0,Iterables.size(actualEntitiesAfterDelete));

}
 
源代码9 项目: tracing-framework   文件: MethodTracepoint.java
@Override
public List<TracepointSpec> getTracepointSpecsForAdvice(AdviceSpec advice) {
    TracepointSpec.Builder tsb = TracepointSpec.newBuilder();
    MethodTracepointSpec.Builder b = tsb.getMethodTracepointBuilder();
    b.setClassName(className);
    b.setMethodName(methodName);
    b.addAllParamClass(Lists.newArrayList(args));
    b.setWhere(interceptAt);
    if (interceptAt == Where.LINENUM) {
        b.setLineNumber(interceptAtLineNumber);
    }
    for (String observedVar : advice.getObserve().getVarList()) {
        b.addAdviceArg(exports.get(observedVar.split("\\.")[1]).getSpec());
    }
    return Lists.<TracepointSpec>newArrayList(tsb.build());
}
 
@Test
public void testSearchBusinessObjectDefinitionColumns()
{
    createDatabaseEntitiesForBusinessObjectDefinitionColumnSearchTesting();

    // Search the business object definition columns using all field parameters.
    BusinessObjectDefinitionColumnSearchResponse businessObjectDefinitionColumnSearchResponse = businessObjectDefinitionColumnService
        .searchBusinessObjectDefinitionColumns(new BusinessObjectDefinitionColumnSearchRequest(Lists.newArrayList(
            new BusinessObjectDefinitionColumnSearchFilter(Lists.newArrayList(new BusinessObjectDefinitionColumnSearchKey(BDEF_NAMESPACE, BDEF_NAME))))),
            Sets.newHashSet(SCHEMA_COLUMN_NAME_FIELD, DESCRIPTION_FIELD));

    // Validate the response object.
    assertEquals(new BusinessObjectDefinitionColumnSearchResponse(Lists.newArrayList(
        new BusinessObjectDefinitionColumn(NO_ID, new BusinessObjectDefinitionColumnKey(BDEF_NAMESPACE, BDEF_NAME, BDEF_COLUMN_NAME), COLUMN_NAME,
            BDEF_COLUMN_DESCRIPTION, NO_BUSINESS_OBJECT_DEFINITION_COLUMN_CHANGE_EVENTS),
        new BusinessObjectDefinitionColumn(NO_ID, new BusinessObjectDefinitionColumnKey(BDEF_NAMESPACE, BDEF_NAME, BDEF_COLUMN_NAME_2), COLUMN_NAME_2,
            BDEF_COLUMN_DESCRIPTION_2, NO_BUSINESS_OBJECT_DEFINITION_COLUMN_CHANGE_EVENTS))), businessObjectDefinitionColumnSearchResponse);
}
 
源代码11 项目: brooklyn-server   文件: PortForwardManagerImpl.java
@Override
public boolean forgetPortMappings(String publicIpId) {
    List<PortMapping> result = Lists.newArrayList();
    synchronized (mutex) {
        for (Iterator<PortMapping> iter = mappings.values().iterator(); iter.hasNext();) {
            PortMapping m = iter.next();
            if (publicIpId.equals(m.publicIpId)) {
                iter.remove();
                result.add(m);
                emitAssociationDeletedEvent(associationMetadataFromPortMapping(m));
            }
        }
    }
    if (log.isDebugEnabled()) log.debug("cleared all port mappings for "+publicIpId+" - "+result);
    if (!result.isEmpty()) {
        onChanged();
    }
    return !result.isEmpty();
}
 
源代码12 项目: curator   文件: DistributedDoubleBarrier.java
private List<String> filterAndSortChildren(List<String> children)
{
    Iterable<String> filtered = Iterables.filter
    (
        children,
        new Predicate<String>()
        {
            @Override
            public boolean apply(String name)
            {
                return !name.equals(READY_NODE);
            }
        }
    );

    ArrayList<String> filteredList = Lists.newArrayList(filtered);
    Collections.sort(filteredList);
    return filteredList;
}
 
@Test
public void testCheckTableSchemaTypeValid() throws MetaException {
  TableDescription description = getHashRangeTable();

  Table table = new Table();
  Map<String, String> parameters = Maps.newHashMap();
  parameters.put(DynamoDBConstants.DYNAMODB_COLUMN_MAPPING, "col1:dynamo_col1$," +
      "col2:dynamo_col2#,hashKey:hashKey");
  table.setParameters(parameters);
  StorageDescriptor sd = new StorageDescriptor();
  List<FieldSchema> cols = Lists.newArrayList();
  cols.add(new FieldSchema("col1", "string", ""));
  cols.add(new FieldSchema("col2", "bigint", ""));
  cols.add(new FieldSchema("hashKey", "string", ""));
  sd.setCols(cols);
  table.setSd(sd);
  // This check is expected to pass for the given input
  storageHandler.checkTableSchemaType(description, table);
}
 
源代码14 项目: hadoop-ozone   文件: OzoneManagerRequestHandler.java
private ListVolumeResponse listVolumes(ListVolumeRequest request)
    throws IOException {
  ListVolumeResponse.Builder resp = ListVolumeResponse.newBuilder();
  List<OmVolumeArgs> result = Lists.newArrayList();

  if (request.getScope()
      == ListVolumeRequest.Scope.VOLUMES_BY_USER) {
    result = impl.listVolumeByUser(request.getUserName(),
        request.getPrefix(), request.getPrevKey(), request.getMaxKeys());
  } else if (request.getScope()
      == ListVolumeRequest.Scope.VOLUMES_BY_CLUSTER) {
    result =
        impl.listAllVolumes(request.getPrefix(), request.getPrevKey(),
            request.getMaxKeys());
  }

  result.forEach(item -> resp.addVolumeInfo(item.getProtobuf()));

  return resp.build();
}
 
源代码15 项目: brooklyn-server   文件: ConfigConstraints.java
@SuppressWarnings("unchecked")
protected Iterable<ConfigKey<?>> validateAll() {
    List<ConfigKey<?>> violating = Lists.newLinkedList();
    Iterable<ConfigKey<?>> configKeys = getBrooklynObjectTypeConfigKeys();
    LOG.trace("Checking config keys on {}: {}", getBrooklynObject(), configKeys);
    for (ConfigKey<?> configKey : configKeys) {
        BrooklynObjectInternal.ConfigurationSupportInternal configInternal = getConfigurationSupportInternal();
        // getNonBlocking method coerces the value to the config key's type.
        Maybe<?> maybeValue = configInternal.getNonBlocking(configKey);
        if (maybeValue.isPresent()) {
            // Cast is safe because the author of the constraint on the config key had to
            // keep its type to Predicte<? super T>, where T is ConfigKey<T>.
            ConfigKey<Object> ck = (ConfigKey<Object>) configKey;
            if (!isValueValid(ck, maybeValue.get())) {
                violating.add(configKey);
            }
        } else {
            // absent means did not resolve in time or not coercible;
            // code will return `Maybe.of(null)` if it is unset,
            // and coercion errors are handled when the value is _set_ or _needed_
            // (this allows us to deal with edge cases where we can't *immediately* coerce)
        }
    }
    return violating;
}
 
@Test
@Parameters({ "1.0, 2.0" })
public void shouldCreateDoubleFieldSegmentation(double lowerBound, double upperBound) throws Exception {
  //given
  ReindexCommand command = mock(ReindexCommand.class);
  String fieldName = "fieldName";
  when(command.getSegmentationField()).thenReturn(fieldName);
  when(command.getSegmentationThresholds()).thenReturn(Lists.newArrayList(lowerBound, upperBound));
  //when
  QuerySegmentation querySegmentation = QuerySegmentationFactory.create(command);
  //then
  assertThat(querySegmentation)
      .isInstanceOf(DoubleFieldSegmentation.class)
      .hasFileName(fieldName)
      .hasSegmentsCount(1);
  RangeSegmentAssert.assertThat((RangeSegment) (querySegmentation.getThreshold(0).get()))
      .hasLowerOpenBound(lowerBound)
      .hasUpperBound(upperBound);
}
 
源代码17 项目: hadoop   文件: QuorumJournalManager.java
private static List<InetSocketAddress> getLoggerAddresses(URI uri)
    throws IOException {
  String authority = uri.getAuthority();
  Preconditions.checkArgument(authority != null && !authority.isEmpty(),
      "URI has no authority: " + uri);
  
  String[] parts = StringUtils.split(authority, ';');
  for (int i = 0; i < parts.length; i++) {
    parts[i] = parts[i].trim();
  }

  if (parts.length % 2 == 0) {
    LOG.warn("Quorum journal URI '" + uri + "' has an even number " +
        "of Journal Nodes specified. This is not recommended!");
  }
  
  List<InetSocketAddress> addrs = Lists.newArrayList();
  for (String addr : parts) {
    addrs.add(NetUtils.createSocketAddr(
        addr, DFSConfigKeys.DFS_JOURNALNODE_RPC_PORT_DEFAULT));
  }
  return addrs;
}
 
源代码18 项目: clutz   文件: TypeScriptGeneratorTest.java
@Parameters(name = "Test {index}: {0}")
public static Iterable<SingleTestConfig> testCases() throws IOException {
  List<SingleTestConfig> configs = Lists.newArrayList();
  List<File> testInputFiles =
      getTestInputFiles(DeclarationGeneratorTest.JS_NO_EXTERNS_OR_ZIP, singleTestPath);
  File inputFileRoot = getTestDirPath(singleTestPath).toFile().getCanonicalFile();
  for (File file : testInputFiles) {
    TestInput input =
        new TestInput(
            inputFileRoot.getAbsolutePath(), TestUtil.getRelativePathTo(file, inputFileRoot));

    configs.add(new SingleTestConfig(ExperimentTracker.withoutExperiments(), input));

    /*
     * To specify that another experiment should be used, add the Experiment enum
     * value for that experiment in the withExperiments() method.
     */
    // To enable testing an experiment, replace SOME_EXPERIMENT with the experiment
    // enum value below and uncomment the next lines.
    // configs.add(
    //     new SingleTestConfig(
    //         ExperimentTracker.withExperiments(Experiment.SOME_EXPERIMENT), input));
  }
  return configs;
}
 
@Override
public List<BundleSubmission> getBundleSubmissionsByFilters(String orderBy, String orderDir, String authorJid, String problemJid, String containerJid) {
    ImmutableMap.Builder<SingularAttribute<? super SM, ? extends Object>, String> filterColumnsBuilder = ImmutableMap.builder();
    if (authorJid != null) {
        filterColumnsBuilder.put(AbstractBundleSubmissionModel_.createdBy, authorJid);
    }
    if (problemJid != null) {
        filterColumnsBuilder.put(AbstractBundleSubmissionModel_.problemJid, problemJid);
    }
    if (containerJid != null) {
        filterColumnsBuilder.put(AbstractBundleSubmissionModel_.containerJid, containerJid);
    }

    Map<SingularAttribute<? super SM, ? extends Object>, String> filterColumns = filterColumnsBuilder.build();

    List<SM> submissionModels = bundleSubmissionDao.findSortedByFiltersEq(orderBy, orderDir, "", filterColumns, 0, -1);

    return Lists.transform(submissionModels, m -> BundleSubmissionServiceUtils.createSubmissionFromModel(m));
}
 
源代码20 项目: dubbox   文件: ActivityRuleService.java
@Override
public List<ActivityRuleEntity> getActivityRule(ActivityRuleEntity activityRuleEntity) throws DTSAdminException {
    ActivityRuleDO activityRuleDO = ActivityRuleHelper.toActivityRuleDO(activityRuleEntity);
    ActivityRuleDOExample example = new ActivityRuleDOExample();
    Criteria criteria = example.createCriteria();
    criteria.andIsDeletedIsNotNull();
    if (StringUtils.isNotEmpty(activityRuleDO.getBizType())) {
        criteria.andBizTypeLike(activityRuleDO.getBizType());
    }
    if (StringUtils.isNotEmpty(activityRuleDO.getApp())) {
        criteria.andAppLike(activityRuleDO.getApp());
    }
    if (StringUtils.isNotEmpty(activityRuleDO.getAppCname())) {
        criteria.andAppCnameLike(activityRuleDO.getAppCname());
    }
    example.setOrderByClause("app,biz_type");
    List<ActivityRuleDO> lists = activityRuleDOMapper.selectByExample(example);
    if (CollectionUtils.isEmpty(lists)) {
        return Lists.newArrayList();
    }
    List<ActivityRuleEntity> entities = Lists.newArrayList();
    for (ActivityRuleDO an : lists) {
        entities.add(ActivityRuleHelper.toActivityRuleEntity(an));
    }
    return entities;
}
 
源代码21 项目: cloudbreak   文件: AzurePlatformParameters.java
@Override
public List<StackParamValidation> additionalStackParameters() {
    List<StackParamValidation> additionalStackParameterValidations = Lists.newArrayList();
    additionalStackParameterValidations.add(new StackParamValidation(PlatformParametersConsts.TTL_MILLIS, false, String.class, Optional.of("^[0-9]*$")));
    additionalStackParameterValidations.add(new StackParamValidation("diskPerStorage", false, String.class, Optional.empty()));
    additionalStackParameterValidations.add(new StackParamValidation("encryptStorage", false, Boolean.class, Optional.empty()));
    additionalStackParameterValidations.add(new StackParamValidation("persistentStorage", false, String.class,
            Optional.of("^[a-z0-9]{0,24}$")));
    additionalStackParameterValidations.add(new StackParamValidation("attachedStorageOption", false, ArmAttachedStorageOption.class,
            Optional.empty()));
    additionalStackParameterValidations.add(new StackParamValidation(RESOURCE_GROUP_NAME_PARAMETER, false, String.class,
            Optional.empty()));
    return additionalStackParameterValidations;
}
 
源代码22 项目: judgels   文件: IcpcScoreboardProcessorTests.java
@Test
void no_pending() {
    ScoreboardProcessResult result = scoreboardProcessor.process(
            contest,
            state,
            Optional.empty(),
            styleModuleConfig,
            contestants,
            baseSubmissions,
            ImmutableList.of(),
            freezeTime);

    assertThat(Lists.transform(result.getEntries(), e -> (IcpcScoreboardEntry) e)).containsExactly(
            new IcpcScoreboardEntry.Builder()
                    .rank(1)
                    .contestantJid("c2")
                    .totalAccepted(2)
                    .totalPenalties(5)
                    .lastAcceptedPenalty(150000)
                    .addAttemptsList(1, 1)
                    .addPenaltyList(3, 2)
                    .addProblemStateList(
                            IcpcScoreboardProblemState.ACCEPTED,
                            IcpcScoreboardProblemState.FIRST_ACCEPTED
                    )
                    .build(),
            new IcpcScoreboardEntry.Builder()
                    .rank(2)
                    .contestantJid("c1")
                    .totalAccepted(1)
                    .totalPenalties(1)
                    .lastAcceptedPenalty(40000)
                    .addAttemptsList(1, 0)
                    .addPenaltyList(1, 0)
                    .addProblemStateList(
                            IcpcScoreboardProblemState.FIRST_ACCEPTED,
                            IcpcScoreboardProblemState.NOT_ACCEPTED
                    )
                    .build());
}
 
源代码23 项目: dremio-oss   文件: FunctionHolderExpression.java
public FunctionHolderExpression(String nameUsed, List<LogicalExpression> args) {
  if (args == null) {
    args = Lists.newArrayList();
  }

  if (!(args instanceof ImmutableList)) {
    args = ImmutableList.copyOf(args);
  }
  this.args = (ImmutableList<LogicalExpression>) args;
  this.nameUsed = nameUsed;
}
 
源代码24 项目: newts   文件: CassandraCachePrimerITCase.java
@Test
public void canRestoreTheCacheContextFromCassandra() {
    CassandraSession session = newtsInstance.getCassandraSession();

    CassandraIndexingOptions options = new CassandraIndexingOptions.Builder()
            .withHierarchicalIndexing(true)
            .build();

    MetricRegistry registry = new MetricRegistry();
    GuavaResourceMetadataCache cache = new GuavaResourceMetadataCache(2048, registry);
    CassandraIndexer indexer = new CassandraIndexer(session, 0, cache, registry, options,
            new EscapableResourceIdSplitter(), new ContextConfigurations());

    Map<String, String> base = map("meat", "people", "bread", "beer");
    List<Sample> samples = Lists.newArrayList();
    samples.add(sampleFor(new Resource("a:b:c", Optional.of(base)), "m0"));
    samples.add(sampleFor(new Resource("a:b", Optional.of(base)), "m1"));
    samples.add(sampleFor(new Resource("x:b:z", Optional.of(base)), "m2"));
    indexer.update(samples);

    // Verify that the cache has some entries
    Map<String, ResourceMetadata> cacheContents = cache.getCache().asMap();
    assertThat(cacheContents.keySet(), hasSize(greaterThanOrEqualTo(3)));

    // Now prime a new cache using the data available in Cassandra
    GuavaResourceMetadataCache newCache = new GuavaResourceMetadataCache(2048, registry);
    CassandraCachePrimer cachePrimer = new CassandraCachePrimer(session);
    cachePrimer.prime(newCache);

    // We should have been able to replicate the same state
    Map<String, ResourceMetadata> primedCache = newCache.getCache().asMap();
    assertThat(cacheContents, equalTo(primedCache));
}
 
源代码25 项目: joyqueue   文件: ProduceMessageRequestCodec.java
@Override
public ProduceMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    short dataSize = buffer.readShort();
    Map<String, ProduceMessageData> data = Maps.newHashMapWithExpectedSize(dataSize);
    for (int i = 0; i < dataSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        String txId = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int timeout = buffer.readInt();
        QosLevel qosLevel = QosLevel.valueOf(buffer.readByte());

        ProduceMessageData produceMessageData = new ProduceMessageData();
        produceMessageData.setTxId(txId);
        produceMessageData.setTimeout(timeout);
        produceMessageData.setQosLevel(qosLevel);

        short messageSize = buffer.readShort();
        List<BrokerMessage> messages = Lists.newArrayListWithCapacity(messageSize);
        for (int j = 0; j < messageSize; j++) {
            BrokerMessage brokerMessage = Serializer.readBrokerMessage(buffer);
            brokerMessage.setTopic(topic);
            brokerMessage.setTxId(txId);
            messages.add(brokerMessage);
        }

        produceMessageData.setMessages(messages);
        data.put(topic, produceMessageData);
    }

    ProduceMessageRequest produceMessageRequest = new ProduceMessageRequest();
    produceMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    produceMessageRequest.setData(data);
    return produceMessageRequest;
}
 
源代码26 项目: onboard   文件: HelpTipServiceImpl.java
private Map<String, List<HelpTip>> seperateHelpTipByTitle(List<HelpTip> helpTips) {
    Map<String, List<HelpTip>> helpTipsGroupByTitleMap = new HashMap<String, List<HelpTip>>();
    for (HelpTip helpTip : helpTips) {
        String title = helpTip.getTitle();
        if (!helpTipsGroupByTitleMap.containsKey(title)) {
            List<HelpTip> list = Lists.newArrayList();
            list.add(helpTip);
            helpTipsGroupByTitleMap.put(title, list);
        } else {
            helpTipsGroupByTitleMap.get(title).add(helpTip);
        }
    }

    return helpTipsGroupByTitleMap;
}
 
public BuiltInFunctionTupleFilter(String name, FilterOperatorEnum filterOperatorEnum) {
    super(Lists.<TupleFilter> newArrayList(),
            filterOperatorEnum == null ? FilterOperatorEnum.FUNCTION : filterOperatorEnum);
    this.methodParams = Lists.newArrayList();

    if (name != null) {
        this.name = name.toUpperCase(Locale.ROOT);
        initMethod();
    }
}
 
源代码28 项目: onos   文件: MulticastRouteManagerTest.java
@Before
public void setUp() throws Exception {
    manager = new MulticastRouteManager();
    mcastStore = new DistributedMcastStore();
    TestUtils.setField(mcastStore, "storageService", new TestStorageService());
    injectEventDispatcher(manager, new TestEventDispatcher());
    events = Lists.newArrayList();
    manager.store = mcastStore;
    mcastStore.activate();
    manager.activate();
    manager.addListener(listener);
}
 
源代码29 项目: dhis2-core   文件: AnalyticsIndexTest.java
@Test
public void testGetIndexName()
{
    AnalyticsIndex indexA = new AnalyticsIndex( "analytics_2017_temp", Lists.newArrayList( quote( "quarterly" ) ), null );
    AnalyticsIndex indexB = new AnalyticsIndex( "analytics_2018_temp", Lists.newArrayList( quote( "ax" ), quote( "co" ) ), null );
    AnalyticsIndex indexC = new AnalyticsIndex( "analytics_2019_temp", Lists.newArrayList( quote( "YtbsuPPo010" ) ), null );

    assertTrue( indexA.getIndexName( AnalyticsTableType.DATA_VALUE ).startsWith( QUOTE + "in_quarterly_ax_2017_" ) );
    assertTrue( indexB.getIndexName( AnalyticsTableType.DATA_VALUE ).startsWith( QUOTE + "in_ax_co_ax_2018_" ) );
    assertTrue( indexC.getIndexName( AnalyticsTableType.DATA_VALUE ).startsWith( QUOTE + "in_YtbsuPPo010_ax_2019_" ) );
}
 
源代码30 项目: hmftools   文件: PotentialMNVRegion.java
@NotNull
static PotentialMNVRegion addVariant(@NotNull final PotentialMNVRegion region, @NotNull final VariantContext variant,
        final int gapSize) {
    if (region.equals(PotentialMNVRegion.empty())) {
        return fromVariant(variant);
    } else {
        final List<PotentialMNV> mnvs = addVariantToPotentialMnvs(region.mnvs(), variant, gapSize);
        final List<VariantContext> variants = Lists.newArrayList(region.variants());
        variants.add(variant);
        final int mnvEnd = Math.max(region.end(), variant.getStart() + variant.getReference().getBaseString().length());
        return ImmutablePotentialMNVRegion.of(region.chromosome(), region.start(), mnvEnd, variants, mnvs);
    }
}
 
 同包方法