下面列出了com.google.common.collect.Maps#newHashMap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void readTextWithTranslator() throws Exception {
Map<String, Object> configMap = Maps.newHashMap();
configMap.put(FileSystemInput.FORMAT_CONFIG, FileSystemInput.TEXT_FORMAT);
configMap.put(FileSystemInput.PATH_CONFIG, FileSystemInput.class.getResource(TEXT_DATA).getPath());
configMap.put("translator.type", KVPTranslator.class.getName());
configMap.put("translator.delimiter.kvp", ",");
configMap.put("translator.delimiter.field", "=");
configMap.put("translator.schema.type", "flat");
configMap.put("translator.schema.field.names", Lists.newArrayList("a", "b", "c"));
configMap.put("translator.schema.field.types", Lists.newArrayList("int", "string", "boolean"));
config = ConfigFactory.parseMap(configMap);
FileSystemInput formatInput = new FileSystemInput();
assertNoValidationFailures(formatInput, config);
formatInput.configure(config);
List<Row> results = formatInput.read().collectAsList();
assertEquals(2, results.size());
assertTrue(results.contains(RowFactory.create(1, "hello", true)));
assertTrue(results.contains(RowFactory.create(2, "world", false)));
}
@Override
public Object decode(KafkaHeader header, ByteBuf buffer) throws Exception {
SyncGroupRequest request = new SyncGroupRequest();
Map<String, SyncGroupAssignment> groupAssignment = Collections.emptyMap();
request.setGroupId(Serializer.readString(buffer, Serializer.SHORT_SIZE));
request.setGenerationId(buffer.readInt());
request.setMemberId(Serializer.readString(buffer, Serializer.SHORT_SIZE));
int size = buffer.readInt();
if (size > 0) {
groupAssignment = Maps.newHashMap();
for (int i = 0; i < size; i++) {
String memberId = Serializer.readString(buffer, Serializer.SHORT_SIZE);
SyncGroupAssignment assignment = KafkaSyncGroupAssignmentSerializer.readAssignment(buffer);
groupAssignment.put(memberId, assignment);
}
}
request.setGroupAssignment(groupAssignment);
return request;
}
@Test
public void emit_WhenZipkinTracingIsNotEnabled_ShouldDisableSamplingForTheEntireRequestChain() {
Map<String, String> additionalData = Maps.newHashMap();
Map.Entry<String, String> expectedHeader = new AbstractMap.SimpleEntry<>(ZipkinKeys.SAMPLED, ZipkinKeys.DO_NOT_SAMPLE_VALUE);
victim = new ZipkinSocketContextEmitter(compoundContextEmitter);
when(ctx.traceLoggingEnabled()).thenReturn(false);
when(zipkinRequestUUID.isZipkinTracingEnabled()).thenReturn(false);
victim.emit(ctx, additionalData, null);
assertEquals(1, additionalData.size());
assertTrue(additionalData.containsKey(expectedHeader.getKey()));
assertEquals(additionalData.get(expectedHeader.getKey()), expectedHeader.getValue());
}
@Test
public void testDifferentTasks() throws Exception {
// Create a job with two different tasks
String jobName = TestHelper.getTestMethodName();
Workflow.Builder workflowBuilder = new Workflow.Builder(jobName);
List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(2);
TaskConfig taskConfig1 = new TaskConfig("TaskOne", null);
TaskConfig taskConfig2 = new TaskConfig("TaskTwo", null);
taskConfigs.add(taskConfig1);
taskConfigs.add(taskConfig2);
Map<String, String> jobCommandMap = Maps.newHashMap();
jobCommandMap.put("Timeout", "1000");
JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand")
.addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobCommandMap);
workflowBuilder.addJob(jobName, jobBuilder);
_driver.start(workflowBuilder.build());
// Ensure the job completes
_driver.pollForWorkflowState(jobName, TaskState.COMPLETED);
// Ensure that each class was invoked
Assert.assertTrue(_invokedClasses.contains(TaskOne.class.getName()));
Assert.assertTrue(_invokedClasses.contains(TaskTwo.class.getName()));
}
public void recordTraffic(String topic, int traffic) {
if (topicTraffic == null) {
topicTraffic = Maps.newHashMap();
}
traffic = ObjectUtils.defaultIfNull(topicTraffic.get(topic), 0) + traffic;
topicTraffic.put(topic, traffic);
}
private Collection<WorkflowData> reduce(List<WorkflowData> ops) {
Map<String, WorkflowData> map = Maps.newHashMap();
for (WorkflowData op : ops) {
map.put(op.name(), op);
}
//TODO check the version... or maybe workplaceStore will handle this.
return map.values();
}
/**
* Creates a new challenge for the server node to send to the client node.
*
* @return The challenge as a collection of properties to be added to the message the server node
* sends the client node; never {@code null}.
*/
static Map<String, String> newChallenge() {
return Maps.newHashMap(
ImmutableMap.<String, String>builder()
.put(encodeProperty(ChallengePropertyNames.NONCE, newRandomBytes(LARGE_NONCE_LENGTH)))
.put(encodeProperty(ChallengePropertyNames.SALT, newRandomBytes(HASH_OUTPUT_SIZE)))
.build());
}
private HarvestAgentStatusDTO setupHarvestAgentStatus(String secondJobName) {
HarvestAgentStatusDTO harvestAgentStatusDTO = new HarvestAgentStatusDTO();
HashMap<String, HarvesterStatusDTO> statusMap = Maps.newHashMap();
HarvesterStatusDTO harvesterStatusDTO = new HarvesterStatusDTO();
harvesterStatusDTO.setJobName("notTheSameJob");
statusMap.put("irrelevant", harvesterStatusDTO);
HarvesterStatusDTO harvesterStatusDTO2 = new HarvesterStatusDTO();
harvesterStatusDTO2.setJobName(secondJobName);
statusMap.put("irrelevant2", harvesterStatusDTO2);
harvestAgentStatusDTO.setHarvesterStatus(statusMap);
return harvestAgentStatusDTO;
}
public Map<String,Object> getSubset(ConfigNamespace umbrella, String... umbrellaElements) {
Map<String,Object> result = Maps.newHashMap();
for (ReadConfiguration config : new ReadConfiguration[]{global,local}) {
result.putAll(super.getSubset(config,umbrella,umbrellaElements));
}
return result;
}
@Test
public void shouldUseExistingTimestampHeaderInTimestampedEvent() {
SimpleEvent base = new SimpleEvent();
Map<String, String> headersWithTimestamp = Maps.newHashMap();
headersWithTimestamp.put("timestamp", "-321");
base.setHeaders(headersWithTimestamp );
TimestampedEvent timestampedEvent = new TimestampedEvent(base);
assertEquals(-321L, timestampedEvent.getTimestamp());
assertEquals("-321", timestampedEvent.getHeaders().get("timestamp"));
}
/**
* 只转化当前字段, 方便给json用
* @return
*/
public Map<String, Object> toSimpleObj() {
Map<String, Object> map = Maps.newHashMap();
map.put("id", id);
map.put("hasUsed", hasUsed);
map.put("name", name);
map.put("startDate", startDate);
map.put("endDate", endDate);
map.put("price", price);
map.put("usedType", usedType);
map.put("usedTypeDesc", usedTypeDesc);
map.put("type", type);
map.put("typeDesc", typeDesc);
return map;
}
private static String getJsonOfCoordinate(double latitude, double longitude) {
try {
Map<String, Double> map = Maps.newHashMap();
map.put("lat", latitude);
map.put("lng", longitude);
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return null;
}
}
@Override
public final Map<String, List<M>> getBySubmissionJids(List<String> submissionJids) {
if (submissionJids.isEmpty()) {
return ImmutableMap.of();
}
Map<String, List<M>> result = Maps.newHashMap();
for (List<String> partitionedSubmissionJids : Lists.partition(submissionJids, 1000)) {
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<M> query = cb.createQuery(getEntityClass());
Root<M> root = query.from(getEntityClass());
query.where(root.get(AbstractProgrammingGradingModel_.submissionJid).in(partitionedSubmissionJids));
List<M> models = currentSession().createQuery(query).getResultList();
for (M model : models) {
if (result.containsKey(model.submissionJid)) {
result.get(model.submissionJid).add(model);
} else {
@SuppressWarnings("unchecked")
List<M> list = Lists.newArrayList(model);
result.put(model.submissionJid, list);
}
}
}
return result;
}
@Test
public void testAlternatePhasings()
{
String geneName = "GENE1";
String geneId = "ENSG0001";
String chromosome = "1";
// SV breakend positions won't impact fusion determination since transcripts are created manually
GeneAnnotation gene1 = createGeneAnnotation(0, true, geneName, geneId, 1, chromosome, 150, 1);
// one on the negative strand
String geneName2 = "GENE2";
String geneId2 = "ENSG0003";
String chromosome2 = "1";
GeneAnnotation gene2 = createGeneAnnotation(0, false, geneName2, geneId2, -1, chromosome2, 150, 1);
String transName1 = "ENST0001";
int transId1 = 1;
// non-coding combos
Integer codingStart = new Integer(100);
Integer codingEnd = new Integer(200);
Transcript transUp = new Transcript(gene1, transId1, transName1, 2, 1, 3, 1,
10, getCodingBases(codingStart, codingEnd),10, true, 50, 250, codingStart, codingEnd);
String transName2 = "ENST0002";
int transId2 = 2;
Transcript transDown = new Transcript(gene2, transId2, transName2, 2, 0, 3, 0,
10, getCodingBases(codingStart, codingEnd),10, true, 50, 250, codingStart, codingEnd);
FusionParameters params = new FusionParameters();
params.AllowExonSkipping = true;
params.RequirePhaseMatch = false;
// up non-coding
assertTrue(transUp.isCoding());
assertTrue(transDown.isCoding());
GeneFusion fusion = checkFusionLogic(transUp, transDown, params);
assertTrue( fusion != null);
assertTrue( !fusion.phaseMatched());
Map<Integer,Integer> altPhasings = Maps.newHashMap();
altPhasings.put(0, 1);
transUp.setAlternativePhasing(altPhasings);
fusion = checkFusionLogic(transUp, transDown, params);
assertTrue( fusion != null);
assertTrue( fusion.phaseMatched());
assertEquals(fusion.getExonsSkipped(true), 1);
assertEquals(fusion.getExonsSkipped(false), 0);
transUp.setAlternativePhasing(Maps.newHashMap());
altPhasings.clear();
altPhasings.put(1, 1);
transDown.setAlternativePhasing(altPhasings);
fusion = checkFusionLogic(transUp, transDown, params);
assertTrue( fusion != null);
assertTrue( fusion.phaseMatched());
assertEquals(fusion.getExonsSkipped(true), 0);
assertEquals(fusion.getExonsSkipped(false), 1);
// check 5' gene fusing from the 3'UTR region
transUp = new Transcript(gene1, transId1, transName1, 6, -1, 7, -1,
100, 100,10, true, 50, 250, codingStart, codingEnd);
assertTrue(transUp.postCoding());
assertEquals(transUp.ExonDownstreamPhase, POST_CODING_PHASE);
assertEquals(transUp.ExonUpstreamPhase, POST_CODING_PHASE);
altPhasings.clear();
altPhasings.put(0, 3);
transUp.setAlternativePhasing(altPhasings);
fusion = checkFusionLogic(transUp, transDown, params);
assertTrue( fusion != null);
assertTrue( fusion.phaseMatched());
assertEquals(fusion.getExonsSkipped(true), 3);
assertEquals(fusion.getExonsSkipped(false), 0);
}
public void test5Pages() throws Exception {
//Get a connection manager based on the test properties
ConnectionManagerTester cm = TestHelpers.getTestConnectionManager();
cm.setLogCql(true);
cm.buildCluster(true);
CObjectShardList shardIdLists = new ShardListMock(Arrays.asList(1L,2L,3L,4L,5L));
//Build our keyspace definition object
CKeyspaceDefinition definition = JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class, this.getClass().getClassLoader(), "MultiInsertKeyspace.js");
//Rebuild the keyspace and get the object mapper
cm.buildKeyspace(definition, true);
ObjectMapper om = cm.getObjectMapper(definition);
om.setLogCql(true);
// Set up test data
// we will insert 200 objects
int nDataItems = 200;
List<Map<String, Object>> values2 = generateNObjects(nDataItems);
List<Map<String, Object>> updatedValues2 = Lists.newArrayList();
for (Map<String, Object> baseValue : values2) {
updatedValues2.add(JsonUtil.rhombusMapFromJsonMap(baseValue, definition.getDefinitions().get("object2")));
}
Map<String, List<Map<String, Object>>> multiInsertMap = Maps.newHashMap();
multiInsertMap.put("object2", updatedValues2);
//Insert data
om.insertBatchMixed(multiInsertMap);
// generate a executorIterator
SortedMap<String, Object> indexValues = Maps.newTreeMap();
indexValues.put("account_id", UUID.fromString("00000003-0000-0030-0040-000000030000"));
indexValues.put("user_id", UUID.fromString("00000003-0000-0030-0040-000000030000"));
UUID stop = UUID.fromString(uuidList.get(nDataItems-1));
CDefinition cDefinition = definition.getDefinitions().get("object2");
BaseCQLStatementIterator unBoundedIterator = (BaseCQLStatementIterator) CObjectCQLGenerator.makeCQLforList(KEYSPACE_NAME, shardIdLists, cDefinition, indexValues, CObjectOrdering.DESCENDING, null, stop, 10l, true, false, false);
Session session = cm.getRhombusSession(definition);
CQLExecutor cqlExecutor = new CQLExecutor(session, true, definition.getConsistencyLevel());
CQLExecutorIterator cqlExecutorIterator = new CQLExecutorIterator(cqlExecutor, unBoundedIterator);
cqlExecutorIterator.setPageSize((nDataItems/5));
for (int i=0 ; i< nDataItems; i++ ){
assertTrue(cqlExecutorIterator.hasNext());
assertNotNull(cqlExecutorIterator.next());
}
assertFalse(cqlExecutorIterator.hasNext());
}
public ShrunkenDictionaryBuilder(Dictionary<T> fullDict) {
this.fullDict = fullDict;
this.valueToIdMap = Maps.newHashMap();
}
public MockFileSystem(String... paths) {
files = Maps.newHashMap();
for (String path : paths) {
files.put(path, new MockVirtualFile(path));
}
}
@Override
protected Map<String, Object> initialValue() {
return Maps.newHashMap();
}
/**
* Resets the state after a launch
*/
public void reset() {
failureMap = Maps.newHashMap();
totalHadoopTimeSpent = 0;
jc = null;
}
/**
* Copy constructor.
*
* @param other The constructed object is a replicated copy of this element.
*/
public MustDef(MustDef other) {
reachingDef = Maps.newHashMap(other.reachingDef);
}