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

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

源代码1 项目: envelope   文件: DataStep.java
private void notifyDataStepDataGenerated() {
  if (EventManager.isHandled(CoreEventTypes.DATA_STEP_DATA_GENERATED)) {
    long startTime = System.nanoTime();

    if (!isCached()) {
      cache();
    }

    long count = data.count();
    long timeTakenNs = System.nanoTime() - startTime;
    String prettyTimeTaken = EventUtils.prettifyNs(timeTakenNs);

    Map<String, Object> metadata = Maps.newHashMap();
    metadata.put(CoreEventMetadataKeys.DATA_STEP_DATA_GENERATED_STEP_NAME, getName());
    metadata.put(CoreEventMetadataKeys.DATA_STEP_DATA_GENERATED_ROW_COUNT, count);
    metadata.put(CoreEventMetadataKeys.DATA_STEP_DATA_GENERATED_TIME_TAKEN_NS, timeTakenNs);

    String message = "Data step " + getName() + " generated " + count + " rows in " + prettyTimeTaken;

    EventManager.notify(new Event(CoreEventTypes.DATA_STEP_DATA_GENERATED, message, metadata));
  }
}
 
源代码2 项目: cloudbreak   文件: InstanceMetadataUpdaterTest.java
@Before
public void setUp() throws CloudbreakException, JsonProcessingException, CloudbreakOrchestratorFailedException {
    MockitoAnnotations.initMocks(this);
    when(gatewayConfigService.getGatewayConfig(any(Stack.class), any(InstanceMetaData.class), anyBoolean())).thenReturn(gatewayConfig);

    InstanceMetadataUpdater.Package packageByName = new InstanceMetadataUpdater.Package();
    packageByName.setName("packageByName");
    packageByName.setPkg(Lists.newArrayList(generatePackageName("packageByName", "(.*)-(.*)")));
    InstanceMetadataUpdater.Package packageByCmd = new InstanceMetadataUpdater.Package();
    packageByCmd.setName("packageByCmd");
    packageByCmd.setPkg(Lists.newArrayList(generatePackageName("packageByCmd", null)));

    underTest.setPackages(Lists.newArrayList(packageByCmd, packageByName));

    Map<String, Map<String, String>> hostPackageMap = Maps.newHashMap();
    hostPackageMap.put("instanceId", packageMap());
    hostPackageMap.put("hostByCmd", packageMap());
    when(hostOrchestrator.getPackageVersionsFromAllHosts(any(GatewayConfig.class), any())).thenReturn(hostPackageMap);
}
 
@Test
public void assertWithDataSource() throws Exception {
    File yamlFile = new File(YamlOrchestrationMasterSlaveIntegrateTest.class.getResource(filePath).toURI());
    DataSource dataSource;
    if (hasDataSource) {
        dataSource = YamlOrchestrationShardingSphereDataSourceFactory.createDataSource(yamlFile);
    } else {
        dataSource = YamlOrchestrationShardingSphereDataSourceFactory.createDataSource(
                Maps.asMap(Sets.newHashSet("db_master", "db_slave_0", "db_slave_1"), AbstractYamlDataSourceTest::createDataSource), yamlFile);
    }
    try (Connection connection = dataSource.getConnection();
         Statement statement = connection.createStatement()) {
        statement.executeQuery("SELECT * FROM t_order");
        statement.executeQuery("SELECT * FROM t_order_item");
        statement.executeQuery("SELECT * FROM t_config");
    }
    ((OrchestrationShardingSphereDataSource) dataSource).close();
}
 
@Test
public void testMultipleValuesCanBeSeparatedByComaTo() {
    Map<String, String> parameters = Maps.newHashMap();

    String paramName = "zeParam";
    String paramValue1 = "un";
    String paramValue2 = "deux";
    String paramValue3 = "trois";

    parameters.put(paramName, paramValue1 + "," + paramValue2 + "," + paramValue3);

    String[] values = MacroParametersUtils.extractParameterMultiple(paramName, parameters);
    assertEquals(3, values.length);
    assertEquals(paramValue1, values[0]);
    assertEquals(paramValue2, values[1]);
    assertEquals(paramValue3, values[2]);
}
 
源代码5 项目: hmftools   文件: FormStatusReader.java
@NotNull
public static FormStatusModel buildModelFromCsv(@NotNull final String pathToCsv) throws IOException {
    Map<FormStatusKey, FormStatus> formStatuses = Maps.newHashMap();
    List<String> lines = FileReader.build().readLines(new File(pathToCsv).toPath());
    // No need to read the header line
    lines.remove(0);
    for (String line : lines) {
        String[] parts = splitCsvLine(line, FIELD_SEPARATOR, FIELD_COUNT);
        if (parts.length == FIELD_COUNT) {
            FormStatusKey formKey = new ImmutableFormStatusKey(removeQuotes(parts[PATIENT_ID_COLUMN].replaceAll("-", "")),
                    removeParentheses(removeQuotes(parts[FORM_NAME_COLUMN])),
                    removeQuotes(parts[FORM_SEQ_NUM_COLUMN]),
                    removeParentheses(removeQuotes(parts[STUDY_EVENT_NAME_COLUMN])),
                    removeQuotes(parts[STUDY_EVENT_SEQ_NUM_COLUMN]));
            FormStatus formStatus = new ImmutableFormStatus(interpretState(removeQuotes(parts[DATA_STATUS_COLUMN])),
                    interpretLocked(removeQuotes(parts[LOCKED_COLUMN])));
            formStatuses.put(formKey, formStatus);
        } else if (parts.length > 0) {
            LOGGER.warn("Could not properly parse line in form status csv: {}", line);
        }
    }
    return new ImmutableFormStatusModel(formStatuses);
}
 
源代码6 项目: api-mining   文件: CppWhitespaceTokenizer.java
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);

	final Scanner scanner = new Scanner();
	scanner.setSource(code);
	final WhitespaceToTokenConverter wsConverter = new WhitespaceToTokenConverter();
	do {
		final int token = scanner.getNextToken();
		if (token == Token.tWHITESPACE) {
			final String wsToken = wsConverter
					.toWhiteSpaceSymbol(new String(scanner
							.getCurrentTokenSource()));
			tokens.put(scanner.getCurrentPosition(), wsToken);
		} else {
			final String nxtToken = new String(
					scanner.getCurrentTokenSource());
			tokens.put(scanner.getCurrentPosition(),
					getTokenType(token, nxtToken));
		}
	} while (!scanner.atEnd());
	return tokens;
}
 
源代码7 项目: kylin-on-parquet-v2   文件: ExecutableManager.java
public void resumeJob(String jobId) {
    AbstractExecutable job = getJob(jobId);
    if (job == null) {
        return;
    }
    Map<String, String> info = null;
    if (job instanceof DefaultChainedExecutable) {
        List<AbstractExecutable> tasks = ((DefaultChainedExecutable) job).getTasks();
        for (AbstractExecutable task : tasks) {
            if (task.getStatus() == ExecutableState.ERROR || task.getStatus() == ExecutableState.STOPPED) {
                updateJobOutput(task.getId(), ExecutableState.READY, null, "no output");
                break;
            }
        }
        final long endTime = job.getEndTime();
        if (endTime != 0) {
            long interruptTime = System.currentTimeMillis() - endTime + job.getInterruptTime();
            info = Maps.newHashMap(getJobOutput(jobId).getInfo());
            info.put(AbstractExecutable.INTERRUPT_TIME, Long.toString(interruptTime));
            info.remove(AbstractExecutable.END_TIME);
        }
    }
    updateJobOutput(jobId, ExecutableState.READY, info, null);
}
 
源代码8 项目: phoenix   文件: SpillableGroupByIT.java
@BeforeClass
public static synchronized void doSetup() throws Exception {
    Map<String, String> props = Maps.newHashMapWithExpectedSize(11);
    // Set a very small cache size to force plenty of spilling
    props.put(QueryServices.GROUPBY_MAX_CACHE_SIZE_ATTRIB,
            Integer.toString(1));
    props.put(QueryServices.GROUPBY_SPILLABLE_ATTRIB, String.valueOf(true));
    props.put(QueryServices.GROUPBY_SPILL_FILES_ATTRIB,
            Integer.toString(1));
    // Large enough to not run out of memory, but small enough to spill
    props.put(QueryServices.MAX_MEMORY_SIZE_ATTRIB, Integer.toString(40000));
    
    // Set guidepost width, but disable stats
    props.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(20));
    props.put(QueryServices.STATS_COLLECTION_ENABLED, Boolean.toString(false));
    props.put(QueryServices.EXPLAIN_CHUNK_COUNT_ATTRIB, Boolean.TRUE.toString());
    props.put(QueryServices.EXPLAIN_ROW_COUNT_ATTRIB, Boolean.TRUE.toString());
    // Must update config before starting server
    setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
}
 
源代码9 项目: Shop-for-JavaWeb   文件: ShopAreaController.java
/**
 * List by parentId, return json format string
 *
 * @throws IOException
 */
@RequestMapping("/ajax-list/{parentId}")
public void ajaxList(@PathVariable String parentId, HttpServletResponse response) throws IOException {
	List<Area> areaList = areaService.findByParentId(parentId);

	// @todo
	List<Map<String, Object>> list = Lists.newArrayList();
	for (Area area : areaList) {
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", area.getId());
		map.put("parentId", area.getParentId());
		map.put("name", area.getName());
		list.add(map);
	}

	boolean res = true;
	String msg = "区域列表";

	JsonUtils.setResponse(response);
	response.getWriter().print(JsonUtils.toString(res, msg, list));
}
 
源代码10 项目: javaide   文件: DependencyManager.java
private static List<LibraryDependencyImpl> convertLibraryInfoIntoDependency(
        @NonNull List<LibInfo> libInfos,
        @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap) {
    List<LibraryDependencyImpl> list = Lists.newArrayListWithCapacity(libInfos.size());

    // since the LibInfos is a graph and the previous "foundLibraries" map ensure we reuse
    // instance where applicable, we'll create a map to keep track of what we have already
    // converted.
    Map<LibInfo, LibraryDependencyImpl> convertedMap = Maps.newIdentityHashMap();

    for (LibInfo libInfo : libInfos) {
        list.add(convertLibInfo(libInfo, reverseMap, convertedMap));
    }

    return list;
}
 
源代码11 项目: caja   文件: EnvironmentChecksTest.java
public final void testEnvironmentData() throws Exception {
  Scriptable s = (Scriptable) RhinoTestBed.runJs(
      new RhinoExecutor.Input(  // TODO: make an ASCII-art Rhino.
          "var navigator = { userAgent: 'Rhino Rhino Rhino' };", "rhino-env"),
      new RhinoExecutor.Input(getClass(), "environment-checks.js"),
      new RhinoExecutor.Input("env", getName())
      );
  Map<String, Object> env = Maps.newHashMap();
  for (Object key : ScriptableObject.getPropertyIds(s)) {
    String code = "" + key;
    env.put(EnvironmentData.normJs(code, mq), s.get(code, s));
  }
  for (EnvironmentDatum datum : EnvironmentDatum.values()) {
    assertTrue(datum.name(), env.containsKey(datum.getCode()));
    System.err.println(datum + " = " + env.get(datum.getCode()));
  }
  assertEquals(
      "Rhino Rhino Rhino",
      env.get(EnvironmentDatum.NAV_USER_AGENT.getCode()));
}
 
源代码12 项目: bazel   文件: DelegatingWalkableGraph.java
@Override
public Map<SkyKey, Pair<SkyValue, Iterable<SkyKey>>> getValueAndRdeps(Iterable<SkyKey> keys)
    throws InterruptedException {
  Map<SkyKey, ? extends NodeEntry> entries =
      getBatch(null, Reason.WALKABLE_GRAPH_VALUE_AND_RDEPS, keys);
  Map<SkyKey, Pair<SkyValue, Iterable<SkyKey>>> result =
      Maps.newHashMapWithExpectedSize(entries.size());
  for (Map.Entry<SkyKey, ? extends NodeEntry> entry : entries.entrySet()) {
    // See comment in #getReverseDeps.
    if (entry.getValue().isDone()) {
      result.put(
          entry.getKey(),
          Pair.of(
              getValueFromNodeEntry(entry.getValue()),
              entry.getValue().getReverseDepsForDoneEntry()));
    }
  }
  return result;
}
 
源代码13 项目: EserKnife   文件: IndexMsgController.java
@RequestMapping(value = "/getDemoData")
@ResponseBody
public Object getColInfoByTabname() {

    Map<String, Object> map = Maps.newHashMap();
    List<Map<String,String>> demoDatas = Lists.newArrayList();
    Map<String,String> col1 = Maps.newHashMap();
    col1.put("demo_type","string");
    col1.put("demo_flag","1");
    col1.put("demo_remark","stirng 类型");
    demoDatas.add(col1);

    Map<String,String> col2 = Maps.newHashMap();
    col2.put("demo_type","long");
    col2.put("demo_flag","1");
    col2.put("demo_remark","long 类型");
    demoDatas.add(col2);

    Map<String,String> col3 = Maps.newHashMap();
    col3.put("demo_type","date");
    col3.put("demo_flag","1");
    col3.put("demo_remark","date 类型");
    demoDatas.add(col3);
    map.put("result", demoDatas);
    return map;
}
 
源代码14 项目: brooklyn-server   文件: SshTasks.java
private static Map<String, Object> getSshFlags(Location location) {
    Set<ConfigKey<?>> sshConfig = MutableSet.of();
    
    StringConfigMap mgmtConfig = null;
    sshConfig.addAll(location.config().findKeysPresent(ConfigPredicates.nameStartsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)));
    if (location instanceof AbstractLocation) {
        ManagementContext mgmt = ((AbstractLocation)location).getManagementContext();
        if (mgmt!=null) {
            mgmtConfig = mgmt.getConfig();
            sshConfig.addAll(mgmtConfig.findKeysPresent(ConfigPredicates.nameStartsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)));
        }
    }
    
    
    Map<String, Object> result = Maps.newLinkedHashMap();
    for (ConfigKey<?> key : sshConfig) {
        Maybe<Object> v = ((LocationInternal)location).config().getRaw(key);
        if (v.isAbsent() && mgmtConfig!=null) v = Maybe.of( (Object) mgmtConfig.getConfig(key) );
        result.put(ConfigUtils.unprefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, key).getName(), v.get());
    }
    return result;
}
 
@Test
public void asDataPointsShouldReturnCorrectDataPoints() {

    List<DataPoint<HeartRate>> dataPoints = mapper.asDataPoints(singletonList(responseNode));

    HeartRate expectedHeartRate = new HeartRate.Builder(55)
            .setTemporalRelationshipToPhysicalActivity(AT_REST)
            .setEffectiveTimeFrame(OffsetDateTime.parse("2013-11-20T08:05:00-08:00"))
            .build();

    assertThat(dataPoints.get(0).getBody(), equalTo(expectedHeartRate));

    // TODO kill maps
    Map<String, Object> testProperties = Maps.newHashMap();
    testProperties.put(HEADER_EXTERNAL_ID_KEY, "40F7_htRRnT8Vo7nRBZO1X");
    testProperties.put(HEADER_SOURCE_UPDATE_KEY, "2013-11-21T15:59:59Z");
    testProperties.put(HEADER_SCHEMA_ID_KEY, HeartRate.SCHEMA_ID);
    testProperties.put(HEADER_SENSED_KEY, DataPointModality.SENSED);
    testDataPointHeader(dataPoints.get(0).getHeader(), testProperties);
}
 
源代码16 项目: codemining-core   文件: CppWhitespaceTokenizer.java
@Override
public SortedMap<Integer, FullToken> fullTokenListWithPos(final char[] code) {
	final SortedMap<Integer, FullToken> tokens = Maps.newTreeMap();
	tokens.put(-1, new FullToken(SENTENCE_START, SENTENCE_START));
	tokens.put(Integer.MAX_VALUE, new FullToken(SENTENCE_END, SENTENCE_END));

	final Scanner scanner = new Scanner();
	scanner.setSource(code);
	final WhitespaceToTokenConverter wsConverter = new WhitespaceToTokenConverter();
	do {
		final int token = scanner.getNextToken();
		if (token == Token.tWHITESPACE) {
			final String wsToken = wsConverter
					.toWhiteSpaceSymbol(new String(scanner
							.getCurrentTokenSource()));
			tokens.put(scanner.getCurrentPosition(), new FullToken(wsToken,
					Integer.toString(token)));
		} else {
			final String nxtToken = new String(
					scanner.getCurrentTokenSource());
			tokens.put(scanner.getCurrentPosition(), new FullToken(
					getTokenType(token, nxtToken), Integer.toString(token)));
		}
	} while (!scanner.atEnd());
	return tokens;
}
 
@Test
public void testDeterministicNesting() throws JsonProcessingException
{
    @SuppressWarnings("unused")
    Object obj = new Object() {
        public String get1() { return "1"; }
        public String getC() { return "C"; }
        public String getA() { return "A"; }
    };

    Set<Integer> ints = Sets.newLinkedHashSet(Lists.newArrayList(1, 4, 2, 3, 5, 7, 8, 9, 6, 0, 50, 100, 99));

    Map<String, Object> data = Maps.newLinkedHashMap();
    data.put("obj", obj);
    data.put("c", "C");
    data.put("ints", ints);

    String actual = mapper.writer().writeValueAsString(data);
    String expected = "{" +
                        "\"c\":\"C\"," +
                        "\"ints\":[0,1,2,3,4,5,6,7,8,9,50,99,100]," +
                        "\"obj\":{\"1\":\"1\",\"a\":\"A\",\"c\":\"C\"}" +
                      "}";
    assertEquals(expected, actual);
}
 
源代码18 项目: pacbot   文件: CommonUtils.java
/**
 * Builds the query.
 *
 * @param filter the filter
 * @return elastic search query details
 */
static Map<String, Object> buildQuery(final Map<String, String> filter) {
	Map<String, Object> queryFilters = Maps.newHashMap();
	Map<String, Object> boolFilters = Maps.newHashMap();
	List<Map<String, Object>> should = Lists.newArrayList();
	for (Map.Entry<String, String> entry : filter.entrySet()) {
		Map<String, Object> term = Maps.newHashMap();
		Map<String, Object> termDetails = Maps.newHashMap();
		termDetails.put(entry.getKey(), entry.getValue());
		term.put("term", termDetails);
		should.add(term);
	}
	boolFilters.put("should", should);
	queryFilters.put("bool", boolFilters);
	return queryFilters;
}
 
源代码19 项目: mt-flume   文件: TestFileChannelFormatRegression.java
public void doTestFileFormatV2PreFLUME1432(boolean useLogReplayV1)
        throws Exception {
  TestUtils.copyDecompressed("fileformat-v2-pre-FLUME-1432-checkpoint.gz",
          new File(checkpointDir, "checkpoint"));
  for (int i = 0; i < dataDirs.length; i++) {
    int fileIndex = i + 1;
    TestUtils.copyDecompressed("fileformat-v2-pre-FLUME-1432-log-" + fileIndex
        + ".gz", new File(dataDirs[i], "log-" + fileIndex));
  }
  Map<String, String> overrides = Maps.newHashMap();
  overrides.put(FileChannelConfiguration.CAPACITY, String.valueOf(10000));
  overrides.put(FileChannelConfiguration.USE_LOG_REPLAY_V1,
          String.valueOf(useLogReplayV1));
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Set<String> events = takeEvents(channel, 1);
  Assert.assertEquals(50, events.size());
}
 
源代码20 项目: Shop-for-JavaWeb   文件: AppAboutController.java
/**
 * 关于我们
 */
@RequestMapping("/us")
public String list(HttpServletResponse response) {
       boolean result;
       String message;
       Map<String, Object> data = Maps.newHashMap();
       Map<String, Object> us = Maps.newHashMap();

       String desc = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;月光茶人为客户提供休闲温馨的环境,以最真诚的态度服务于我们的客户,提供香浓的咖啡、健康的奶茶和美味的小吃。为了让客户享受更便捷的服务和优惠价格,我们开发了月光茶人APP,欢迎使用。";
       String copyright = "Copyright © 2015";
       String company = "深圳市宝安区福永月光茶人饮品店";
       String address = "深圳市宝安区福永东福围东街103-5";
       String tel = "联系电话:0755-29350032";
       us.put("desc", desc);
       us.put("copyright", copyright);
       us.put("company", company);
       us.put("address", address);
       us.put("tel", tel);

       result = true;
       message = "";
       data.put("us", us);
       return renderString(response, result, message, data);
}
 
源代码21 项目: attic-aurora   文件: JobDiff.java
private static JobDiff computeUnscoped(
    Map<Integer, ITaskConfig> currentState,
    IJobKey job,
    Map<Integer, ITaskConfig> proposedState) {

  requireNonNull(job);
  requireNonNull(proposedState);

  MapDifference<Integer, ITaskConfig> diff = Maps.difference(currentState, proposedState);

  Map<Integer, ITaskConfig> removedInstances = ImmutableMap.<Integer, ITaskConfig>builder()
      .putAll(diff.entriesOnlyOnLeft())
      .putAll(Maps.transformValues(diff.entriesDiffering(), JobDiff.leftValue()))
      .build();

  Set<Integer> addedInstances = ImmutableSet.<Integer>builder()
      .addAll(diff.entriesOnlyOnRight().keySet())
      .addAll(diff.entriesDiffering().keySet())
      .build();

  return new JobDiff(
      removedInstances,
      addedInstances,
      ImmutableMap.copyOf(diff.entriesInCommon()));
}
 
源代码22 项目: occurrence   文件: CallbackServiceTest.java
@Before
public void setup() {
  downloadEmailUtils = mock(DownloadEmailUtils.class);
  occurrenceDownloadService = mock(OccurrenceDownloadService.class);
  downloadLimitsService= mock(DownloadLimitsService.class);
  when(downloadLimitsService.exceedsSimultaneousDownloadLimit(any(String.class))).thenReturn(null);
  when(downloadLimitsService.exceedsDownloadComplexity(any(DownloadRequest.class))).thenReturn(null);
  when(occurrenceDownloadService.get(anyString())).thenReturn(mockDownload());
  oozieClient = mock(OozieClient.class);
  service =
    new DownloadRequestServiceImpl(oozieClient, Maps.<String, String>newHashMap(), "http://localhost:8080/",
      "", occurrenceDownloadService, downloadEmailUtils,downloadLimitsService);
}
 
源代码23 项目: helios   文件: VersionResponseFilterTest.java
private HttpURLConnection doVersionRequest(String version) throws IOException {
  final Map<String, List<String>> headers = Maps.newHashMap();
  headers.put("Content-Type", asList("application/json"));
  headers.put("Charset", asList("utf-8"));
  if (version != null) {
    headers.put(HELIOS_VERSION_HEADER, asList(version));
  }
  final URI uri = URI.create(masterEndpoint() + "/version");
  final HttpURLConnection connection = connect(uri, headers);
  return connection;
}
 
源代码24 项目: joyqueue   文件: ConsumerClient.java
protected FetchTopicMessageRequest buildFetchTopicMessageCommand(List<String> topics, String app, int count, long ackTimeout, long longPollTimeout) {
    Map<String, FetchTopicMessageData> topicMap = Maps.newHashMap();
    for (String topic : topics) {
        topicMap.put(topic, new FetchTopicMessageData(count));
    }

    FetchTopicMessageRequest fetchTopicMessageRequest = new FetchTopicMessageRequest();
    fetchTopicMessageRequest.setTopics(topicMap);
    fetchTopicMessageRequest.setApp(app);
    fetchTopicMessageRequest.setAckTimeout((int) ackTimeout);
    fetchTopicMessageRequest.setLongPollTimeout((int) longPollTimeout);
    return fetchTopicMessageRequest;
}
 
源代码25 项目: pacbot   文件: TargetTypesServiceImpl.java
private Map<String, Integer> buildSelectedTargetTypesIndex(List<AssetGroupTargetTypes> selectedTargetTypes) {
	Map<String, Integer> selectedTargetTypeIndex = Maps.newHashMap();
	for (int index = 0; index < selectedTargetTypes.size(); index++) {
		selectedTargetTypeIndex.put(selectedTargetTypes.get(index).getTargetType().toLowerCase(), index);
	}
	return selectedTargetTypeIndex;
}
 
源代码26 项目: albedo   文件: Json.java
public static Map<String, Object> toMap(JSONObject jsonObject) {
	Map<String, Object> data = Maps.newHashMap();
	// 将json字符串转换成jsonObject
	Iterator<String> it = jsonObject.keySet().iterator();
	// 遍历jsonObject数据,添加到Map对象
	while (it.hasNext()) {
		String key = String.valueOf(it.next());
		Object value = jsonObject.get(key);
		data.put(key, value);
	}
	return data;
}
 
源代码27 项目: we-cmdb   文件: BeanMapUtils.java
public static <T> Map<String, Object> convertBeanToMap(T bean) {
    Map<String, Object> map = Maps.newHashMap();
    if (bean != null) {
        BeanMap beanMap = BeanMap.create(bean);
        for (Object key : beanMap.keySet()) {
            if (beanMap.get(key) != null) {
                map.put(key.toString(), beanMap.get(key));
            }
        }
    }
    return map;
}
 
源代码28 项目: brooklyn-server   文件: JCloudsPropertiesBuilder.java
public JCloudsPropertiesBuilder setCustomJcloudsProperties() {
    Map<String, Object> extra = Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        String provider = getProviderFromConfig(conf);
        LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider, Sanitizer.sanitize(extra));
    }
    properties.putAll(Maps.filterValues(extra, Predicates.notNull()));
    return this;
}
 
源代码29 项目: onos   文件: MetricsDatabaseTest.java
/**
 * Tests device metrics map update and query.
 */
@Test
public void testDeviceMetricsMap() {
    ControlResource.Type type = ControlResource.Type.CONTROL_MESSAGE;
    DeviceId devId1 = DeviceId.deviceId("of:0000000000000101");
    DeviceId devId2 = DeviceId.deviceId("of:0000000000000102");

    devMetricsMap = Maps.newHashMap();

    Set<DeviceId> devices = ImmutableSet.of(devId1, devId2);
    devices.forEach(dev -> {
        if (!devMetricsMap.containsKey(dev)) {
            devMetricsMap.put(dev, genMDbBuilder(type, ControlResource.CONTROL_MESSAGE_METRICS)
                    .withResourceName(dev.toString())
                    .build());
        }
    });

    Map<String, Double> metrics1 = new HashMap<>();
    ControlResource.CONTROL_MESSAGE_METRICS.forEach(msgType ->
            metrics1.putIfAbsent(msgType.toString(), 10D));

    Map<String, Double> metrics2 = new HashMap<>();
    ControlResource.CONTROL_MESSAGE_METRICS.forEach(msgType ->
            metrics2.putIfAbsent(msgType.toString(), 20D));


    devMetricsMap.get(devId1).updateMetrics(metrics1);
    devMetricsMap.get(devId2).updateMetrics(metrics2);

    ControlResource.CONTROL_MESSAGE_METRICS.forEach(msgType ->
            assertThat(10D, is(devMetricsMap.get(devId1).recentMetric(msgType.toString())))
    );

    ControlResource.CONTROL_MESSAGE_METRICS.forEach(msgType ->
            assertThat(20D, is(devMetricsMap.get(devId2).recentMetric(msgType.toString())))
    );
}
 
源代码30 项目: yql-plus   文件: ProgramParser.java
void defineDataSource(Location loc, String name, boolean hasAliasDefinition) {
    if (isCursor(name)) {
        throw new ProgramCompileException(loc, "Alias '%s' is already used.", name);
    }
    if (cursors.isEmpty()) {
        cursors = Maps.newHashMap();
    }
    cursors.put(name, Boolean.valueOf(hasAliasDefinition));
}
 
 同包方法