com.google.common.collect.Maps Java Examples

The following examples show how to use com.google.common.collect.Maps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SshTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: MacroParametersUtilsTest.java    From livingdoc-confluence with GNU General Public License v3.0 6 votes vote down vote up
@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]);
}
 
Example #3
Source File: FormStatusReader.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: YamlOrchestrationMasterSlaveIntegrateTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: InstanceMetadataUpdaterTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: DataStep.java    From envelope with Apache License 2.0 6 votes vote down vote up
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));
  }
}
 
Example #7
Source File: CppWhitespaceTokenizer.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: ExecutableManager.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: SpillableGroupByIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #10
Source File: AppAboutController.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 关于我们
 */
@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);
}
 
Example #11
Source File: TestFileChannelFormatRegression.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #12
Source File: DeterministicObjectMapperTest.java    From StubbornJava with MIT License 6 votes vote down vote up
@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);
}
 
Example #13
Source File: ShopAreaController.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 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));
}
 
Example #14
Source File: DependencyManager.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: CppWhitespaceTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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;
}
 
Example #16
Source File: CommonUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: EnvironmentChecksTest.java    From caja with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #18
Source File: JawboneHeartRateDataPointMapperUnitTests.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: DelegatingWalkableGraph.java    From bazel with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #20
Source File: JobDiff.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #21
Source File: IndexMsgController.java    From EserKnife with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #22
Source File: AstyanaxBlockedDataReaderDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Iterator<Map.Entry<DeltaClusteringKey, Change>> decodeChanges(final Iterator<StitchedColumn> iter) {
    return Iterators.transform(iter, new Function<StitchedColumn, Map.Entry<DeltaClusteringKey, Change>>() {
        @Override
        public Map.Entry<DeltaClusteringKey, Change> apply(StitchedColumn column) {
            Change change = _changeEncoder.decodeChange(column.getName(), _daoUtils.skipPrefix(column.getByteBufferValue()));
            return Maps.immutableEntry(new DeltaClusteringKey(column.getName(), column.getNumBlocks()), change);
        }
    });
}
 
Example #23
Source File: TestLog4jFormatter.java    From suro with Apache License 2.0 5 votes vote down vote up
@Test
public void testJson() throws IOException {
    ClientConfig config = new ClientConfig();
    JsonLog4jFormatter formatter = new JsonLog4jFormatter(config);

    Map<String, Object> logEvent = Maps.newHashMap();
    logEvent.put("field1", "value1");
    logEvent.put("field2", 100);

    LoggingEvent event = mock(LoggingEvent.class);
    when(event.getLevel()).thenReturn(Level.INFO);
    when(event.getLoggerName()).thenReturn("TestLogger");
    when(event.getMessage()).thenReturn(logEvent);
    when(event.getThrowableStrRep()).thenReturn(new String[]{"StackTrace0", "StackTrace1"});

    Map<String, Object> formattedEvent = new DefaultObjectMapper().readValue(
            formatter.format(event),
            new TypeReference<Map<String, Object>>(){});

    assertEquals(formattedEvent.get("field1"), "value1");
    assertEquals(formattedEvent.get("field2"), 100);
    assertEquals(formattedEvent.get("logLevel"), "INFO");
    assertEquals(formattedEvent.get("class"), "TestLogger");
    assertEquals(formattedEvent.get("Exception").toString(), "[StackTrace0, StackTrace1]");

    // can't compare datetime because of millisecond
    // just check the time with minute
    DateTime now = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern(config.getLog4jDateTimeFormat());
    String nowStr = fmt.print(now);
    assertEquals(nowStr.split(":")[0]+nowStr.split(":")[1],
            ((String)formattedEvent.get("datetime")).split(":")[0] + ((String)formattedEvent.get("datetime")).split(":")[1]);
}
 
Example #24
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private TypeDeclaration findTypeDeclaration(@NonNull String signature) {
    if (mTypeUnits == null) {
        mTypeUnits = Maps.newHashMapWithExpectedSize(mCompiled.size());
        for (CompilationUnitDeclaration unit : mCompiled.values()) {
            if (unit.types != null) {
                for (TypeDeclaration typeDeclaration : unit.types) {
                    addTypeDeclaration(typeDeclaration);
                }
            }
        }
    }

    return mTypeUnits.get(signature);
}
 
Example #25
Source File: TestRunner.java    From envelope with Apache License 2.0 5 votes vote down vote up
@Test
(expected = AnalysisException.class)
public void testNoUDFs() throws Throwable {
  Contexts.closeSparkSession();
  Config config = ConfigUtils.configFromResource("/udf/udf_none.conf");

  new Runner().initializeUDFs(config);
  Deriver deriver = ComponentFactory.create(
      Deriver.class, config.getConfig("steps.runudf.deriver"), true);
  deriver.derive(Maps.<String, Dataset<Row>>newHashMap());
}
 
Example #26
Source File: BlogArticleServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public void createArticlIndex() {
    File fileDectory = new File(LuceneSearch.dir);
    if(!fileDectory.exists()){
        fileDectory.mkdir();
    }else {
        File[] f = fileDectory.listFiles();
        if(f.length>0){
            for (File file : f){
                file.delete();
            }
        }
    }
    Map<String,Object> map = Maps.newHashMap();
    map.put("isBaseChannel",true);
    List<BlogArticle> list = selectDetailArticle(map);
    for (BlogArticle blogArticle : list){
        Document doc = new Document();
        doc.add(new LongPoint("id",blogArticle.getId()));
        doc.add(new TextField("title",blogArticle.getTitle(), Field.Store.YES));
        doc.add(new TextField("marks",blogArticle.getMarks()==null?"":blogArticle.getMarks(),Field.Store.YES));
        doc.add(new TextField("text",blogArticle.getText()==null?"":blogArticle.getText(),Field.Store.YES));
        doc.add(new StoredField("href",blogArticle.getBlogChannel().getHref()));
        doc.add(new StoredField("show_pic",blogArticle.getShowPic()==null?"":blogArticle.getShowPic()));
        doc.add(new StoredField("id",blogArticle.getId()));
        try {
            LuceneSearch.write(doc);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #27
Source File: TeTopologyManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public TeTopologies teTopologies() {
    Map<TeTopologyKey, TeTopology> map;
    if (MapUtils.isNotEmpty(store.teTopologies().teTopologies())) {
        map = Maps.newHashMap(store.teTopologies().teTopologies());
    } else {
        map = Maps.newHashMap();
    }
    if (mergedTopology != null) {
        map.put(mergedTopologyKey, mergedTopology);
    }
    return new DefaultTeTopologies(store.teTopologies().name(), map);
}
 
Example #28
Source File: KafkaSourcePositionHandlerTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializePosition() throws Exception {
    Map<Integer, Long> partitionOffsetMap = Maps.newHashMap();
    partitionOffsetMap.put(0, 1000L);
    partitionOffsetMap.put(1, 1001L);
    partitionOffsetMap.put(2, 1002L);
    KafkaPosition kafkaPosition = new KafkaPosition(partitionOffsetMap);
    String posStr = positionHandler.serializePosition(kafkaPosition);
    System.out.println(posStr);
    KafkaPosition deserializePosition = (KafkaPosition) positionHandler.parsePosition(posStr);
    deserializePosition.getPartitionOffsets();

    assertEquals(deserializePosition.getPartitionOffsets(), partitionOffsetMap);
}
 
Example #29
Source File: SerializationTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test
public void hostContainerMapTest() {
    Host host = new Host("1.1.1.1", 1234, "ep");
    Host host2 = new Host("1.1.1.2", 1234, "ep");
    ContainerSet set = new ContainerSet(Sets.newSet(1, 2, 3, 4));
    ContainerSet set2 = new ContainerSet(Sets.newSet(1, 2, 3, 4));
    Map<Host, ContainerSet> map = new HashMap<>();
    map.put(host, set);
    map.put(host2, set2);
    HostContainerMap hostContainerMap = new HostContainerMap(map);
    byte[] serialized = hostContainerMap.toBytes();
    HostContainerMap deserialized = HostContainerMap.fromBytes(serialized);
    assertTrue(Maps.difference(hostContainerMap.getHostContainerMap(), deserialized.getHostContainerMap()).areEqual());
}
 
Example #30
Source File: NettyHttpRequest.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public Builder addHeader(String name, Object value) {
   if (headers == null) {
      headers = new ArrayList<>();
   }
   Map.Entry<String, Object> headerEntry = Maps.immutableEntry(name, value);
   headers.add(headerEntry);
   return this;
}