下面列出了java.util.Map#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static <K> Map<K, Object> toMap(Class<K> keyType, Object... data) { // SCIPIO: Fixed: public static <K, Object>...
if (data == null) {
return null;
}
if (data.length % 2 == 1) {
throw new IllegalArgumentException("You must pass an even sized array to the toMap method");
}
Map<K, Object> map = new LinkedHashMap<>();
for (int i = 0; i < data.length;) {
Object key = data[i];
if (key != null && !(keyType.isInstance(key))) {
throw new IllegalArgumentException("Key(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")");
}
i++;
Object value = data[i];
map.put(keyType.cast(key), value);
}
return map;
}
protected List<Map<String, Object>> getIndexFields(String index)
throws IOException, SolrServerException {
List<Map<String, Object>> indexFields = new ArrayList<>();
// Get all the fields in use, including dynamic fields
LukeRequest lukeRequest = new LukeRequest();
LukeResponse lukeResponse = lukeRequest.process(client, index);
for (Entry<String, LukeResponse.FieldInfo> field : lukeResponse.getFieldInfo().entrySet()) {
Map<String, Object> fieldData = new HashMap<>();
fieldData.put("name", field.getValue().getName());
fieldData.put("type", field.getValue().getType());
indexFields.add(fieldData);
}
// Get all the schema fields
SchemaRepresentation schemaRepresentation = new SchemaRequest().process(client, index)
.getSchemaRepresentation();
indexFields.addAll(schemaRepresentation.getFields());
return indexFields;
}
private Map<String, String> extractResultMap(QuerySolution qs, List<String> vars) {
Map<String, String> resultMap = new HashMap<>();
for (String var : vars) {
RDFNode node = qs.get(var);
if (node != null) {
if (node instanceof Literal) {
resultMap.put(var, ((Literal)node).getLexicalForm());
} else {
resultMap.put(var, node.toString());
}
}
}
return resultMap;
}
@Override
public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
final Map<String, Object> m = new HashMap<>();
m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal()));
final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals();
final List<Map<String, Object>> intermediates = new ArrayList<>();
for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) {
final Map<String, Object> intermediate = new HashMap<>();
intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString());
intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName());
intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1()));
intermediates.add(intermediate);
}
m.put(GraphSONTokens.INTERMEDIATE, intermediates);
if (strategyTraversals.isEmpty())
m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal()));
else
m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1()));
jsonGenerator.writeObject(m);
}
public void scanData() throws Exception {
if (!isInit) {
init();
}
Map<String, Datum> startKey = new HashMap<String, Datum>();
startKey.put("noteId", DatumUtil.toDatum((long) 1));
Map<String, Datum> stopKey = new HashMap<String, Datum>();
stopKey.put("noteId", DatumUtil.toDatum((long) 5));
List<String> attributes = new ArrayList<String>();
attributes.add("title");
ScanRequest scanRequest = new ScanRequest()
.setTableName(tableName)
.setStartKey(startKey)
.setStopKey(stopKey)
.setLimit(100)
.setAttributes(attributes);
ScanResult scanResult = tableClient.scan(scanRequest);
List<Map<String, Datum>> kvsList = scanResult.getRecords();
for (Map<String, Datum> kvs : kvsList) {
for (Map.Entry<String, Datum> e : kvs.entrySet()) {
LOG.info(e.getKey() + "\t" + DatumUtil.fromDatum(e.getValue()));
}
}
}
/**
* get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
*
* @param apkFile apk file
* @return null if not found
*/
public static Map<String, String> getMap(final File apkFile) {
try {
final String rawString = getRaw(apkFile);
if (rawString == null) {
return null;
}
final JSONObject jsonObject = new JSONObject(rawString);
final Iterator keys = jsonObject.keys();
final Map<String, String> result = new HashMap<String, String>();
while (keys.hasNext()) {
final String key = keys.next().toString();
result.put(key, jsonObject.getString(key));
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@BeforeEach
public void setup() throws Exception {
solrComponent.addCollection(SENSOR_NAME, "./src/test/resources/config/test/conf");
solrComponent.addCollection("error", "./src/main/config/schema/error");
Map<String, Object> globalConfig = createGlobalConfig();
globalConfig.put(HBaseDao.HBASE_TABLE, TABLE_NAME);
globalConfig.put(HBaseDao.HBASE_CF, CF);
CuratorFramework client = ConfigurationsUtils.getClient(solrComponent.getZookeeperUrl());
client.start();
ZKConfigurationsCache cache = new ZKConfigurationsCache(client);
cache.start();
AccessConfig accessConfig = new AccessConfig();
accessConfig.setGlobalConfigSupplier(() -> globalConfig);
accessConfig.setIndexSupplier(s -> s);
accessConfig.setIndexSupplier(IndexingCacheUtil.getIndexLookupFunction(cache, "solr"));
SolrDao dao = new SolrDao();
dao.init(accessConfig);
setDao(dao);
}
/**
* 封装网站设置的数据数据,返回Map形式方便调用者进行遍历
*
* @param webSite
* @return
*/
private Map<String, Object> getDefaultWebSiteSettingMap(Map<String, String> webSite) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("rows", 10);
map.put("template", Constants.DEFAULT_TEMPLATE_PATH);
map.put(Constants.AUTO_UPGRADE_VERSION_KEY, Constants.DEFAULT_AUTO_UPGRADE_VERSION_TYPE.getCycle());
map.put("title", webSite.get("title"));
map.put("second_title", webSite.get("second_title"));
map.put("language", I18nUtil.getCurrentLocale());
map.put(Constants.ZRLOG_SQL_VERSION_KEY, ZrLogUtil.getSqlVersion(basePath + "/update-sql"));
return map;
}
@Test
public void executeControlActionTest_2() {
ControlActionMetadata metadata = new ControlActionMetadata("io.cloudslang.worker.execution.reflection.ReflectionAdapterTestHelper", "myMethod_2");
Map<String, Object> map = new HashMap<>();
map.put("parameter_1", 5);
map.put("parameter_2", 3);
Integer result = (Integer)adapter.executeControlAction(metadata, createAccessorFromMap(map));
assertEquals(8, (int)result);
}
/**
* Gets the map of child attribute names to the parent attribute values.
*
* @param relationshipName the name of the relationship for which to get the map.
* @return the map of child attribute names to the parent attribute values.
*/
public Map<String, Object> getForeignKeyAttributeMap(String relationshipName) {
MetadataChild relationship = findAndValidateRelationship(relationshipName);
List<DataObjectAttributeRelationship> attributeRelationships = relationship.getAttributeRelationships();
if (!attributeRelationships.isEmpty()) {
Map<String, Object> attributeMap = new LinkedHashMap<String, Object>();
for (DataObjectAttributeRelationship attributeRelationship : attributeRelationships) {
// obtain the property value on the current parent object
String parentAttributeName = attributeRelationship.getParentAttributeName();
Object parentAttributeValue = null;
try {
parentAttributeValue = getPropertyValue(parentAttributeName);
} catch (BeansException be) {
// exception thrown may be a db property which may not be defined on class (JPA foreign keys)
// use null value for parentAttributeValue
}
// not all of our relationships are populated, so we cannot obtain a valid foreign key
if (parentAttributeValue == null) {
return null;
}
// store the mapping with the child attribute name to fetch on the referenced child object
String childAttributeName = attributeRelationship.getChildAttributeName();
if (childAttributeName != null) {
attributeMap.put(childAttributeName, parentAttributeValue);
}
}
return attributeMap;
}
return null;
}
@Test
public void setValues_never() throws Exception {
//setup
Map<String, String> values = new HashMap<>();
BaseMatcher.ConversationStepOccurrence expectedOccurrence = BaseMatcher.ConversationStepOccurrence.never;
values.put(KEY_OCCURRENCE, expectedOccurrence.toString());
//test
matcher.setConfigs(values);
//assert
Assert.assertEquals(expectedOccurrence, matcher.getOccurrence());
}
protected static Map<String, String> parseQueryParameters(String query) {
Map<String, String> m = new HashMap<>();
if (query != null) {
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = idx > 0 ? pair.substring(0, idx) : pair;
String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : null;
if (key != null && value != null) {
m.put(key, value);
}
}
}
return m;
}
@Override
public Map<String, JsonbParser.DecoratedType> find(final Class<?> clazz) {
final Map<String, JsonbParser.DecoratedType> readers = new HashMap<>();
for (final Map.Entry<String, Field> f : fields(clazz, true).entrySet()) {
final String key = f.getKey();
if (isIgnored(key) || (johnzonAny != null && Meta.getAnnotation(f.getValue(), johnzonAny) != null)) {
continue;
}
final Field field = f.getValue();
readers.put(key, new FieldDecoratedType(field, field.getGenericType()));
}
return readers;
}
@Test
public void testConvertRegister() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
register.put(key, null);
Map<String, Map<String, String>> newRegister = UrlUtils.convertRegister(register);
assertEquals(register, newRegister);
}
@Test
public void testExtractTaskResultVariablesFromTaskResult() throws Exception {
ScriptExecutableContainer scriptContainer = new ScriptExecutableContainer(new TaskScript(new SimpleScript("print('hello'); result='hello'",
"javascript")));
TaskLauncherInitializer taskLauncherInitializer = getTaskLauncherInitializerWithWorkflowVariables();
TaskContext taskContext = new TaskContext(scriptContainer,
taskLauncherInitializer,
null,
new NodeDataSpacesURIs(null, null, null, null, null, null),
null,
new NodeInfo(null, null, null, null));
Map<String, byte[]> taskResultVariables = new HashMap<>();
// The task result variables are expected to be converted to byte streams.
taskResultVariables.put(taskResultPropagatedVariables1Key,
AllObjects2BytesConverterHandler.convertObject2Byte(taskResultPropagatedVariables1Key,
taskResultPropagatedVariables1Value));
TaskResultImpl taskResult = new TaskResultImpl(taskContext.getTaskId(), new Exception("Exception"));
taskResult.setPropagatedVariables(taskResultVariables);
Map<String, Serializable> contextVariables = new TaskContextVariableExtractor().getAllVariablesWithTaskResult(taskContext,
taskResult);
assertThat((String) contextVariables.get(taskResultPropagatedVariables1Key),
is(taskResultPropagatedVariables1Value));
}
@Test(dataProvider = "resolve_yd")
public void test_resolve_yd_lenient(int y, int d, MinguoDate expected, boolean smart, boolean strict) {
Map<TemporalField, Long> fieldValues = new HashMap<>();
fieldValues.put(ChronoField.YEAR, (long) y);
fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d);
MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT);
assertEquals(date, expected);
assertEquals(fieldValues.size(), 0);
}
private Map<Class<?>, List<URI>> copy(Map<Class<?>, List<URI>> map) {
Map<Class<?>, List<URI>> result = new HashMap<Class<?>, List<URI>>();
for (Map.Entry<Class<?>, List<URI>> e : map.entrySet()) {
if (e.getValue() == null) {
result.put(e.getKey(), null);
} else {
result.put(e.getKey(), new LinkedList<URI>(e.getValue()));
}
}
return result;
}
@Override
public Map<String, SymbolDefinition> getTypeDefinitions() {
Map<String, SymbolDefinition> result = super.getVariableDefinitions();
if (typeParameters != null) {
for (TypeParameter tp : typeParameters) {
result.put(tp.getSymbolName(), tp);
}
}
return result;
}
@SuppressWarnings("unchecked")
private Object convert(org.apache.avro.Schema schema, Object object) {
switch (schema.getType()) {
case RECORD:
return convert(schema, (Row) object);
case ARRAY:
List<Object> convertedList = Lists.newArrayList();
List<?> list = (List<?>) object;
for (Object element : list) {
convertedList.add(convert(schema.getElementType(), element));
}
return convertedList;
case MAP:
Map<String, Object> convertedMap = Maps.newLinkedHashMap();
Map<String, ?> map = (Map<String, ?>) object;
for (Map.Entry<String, ?> entry : map.entrySet()) {
convertedMap.put(entry.getKey(), convert(schema.getValueType(), entry.getValue()));
}
return convertedMap;
case UNION:
if (object == null) {
return null;
}
List<org.apache.avro.Schema> types = schema.getTypes();
if (types.get(0).getType() != NULL) {
return convert(types.get(0), object);
} else {
return convert(types.get(1), object);
}
case FIXED:
Fixed convertedFixed = new Fixed(schema);
convertedFixed.bytes((byte[]) object);
return convertedFixed;
case BYTES:
return ByteBuffer.wrap((byte[]) object);
case BOOLEAN:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case STRING:
return object;
case NULL:
return null;
default:
throw new UnsupportedOperationException("Not a supported type: " + schema);
}
}
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final DatabaseReader dbReader = databaseReaderRef.get();
final String ipAttributeName = context.getProperty(IP_ADDRESS_ATTRIBUTE).evaluateAttributeExpressions(flowFile).getValue();
final String ipAttributeValue = flowFile.getAttribute(ipAttributeName);
if (StringUtils.isEmpty(ipAttributeName)) { //TODO need to add additional validation - should look like an IPv4 or IPv6 addr for instance
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Unable to find ip address for {}", new Object[]{flowFile});
return;
}
InetAddress inetAddress = null;
CityResponse response = null;
try {
inetAddress = InetAddress.getByName(ipAttributeValue);
} catch (final IOException ioe) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Could not resolve {} to ip address for {}", new Object[]{ipAttributeValue, flowFile}, ioe);
return;
}
final StopWatch stopWatch = new StopWatch(true);
try {
response = dbReader.city(inetAddress);
stopWatch.stop();
} catch (final IOException | GeoIp2Exception ex) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Failure while trying to find enrichment data for {} due to {}", new Object[]{flowFile, ex}, ex);
return;
}
if (response == null) {
session.transfer(flowFile, REL_NOT_FOUND);
return;
}
final Map<String, String> attrs = new HashMap<>();
attrs.put(new StringBuilder(ipAttributeName).append(".geo.lookup.micros").toString(), String.valueOf(stopWatch.getDuration(TimeUnit.MICROSECONDS)));
attrs.put(new StringBuilder(ipAttributeName).append(".geo.city").toString(), response.getCity().getName());
final Double latitude = response.getLocation().getLatitude();
if (latitude != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.latitude").toString(), latitude.toString());
}
final Double longitude = response.getLocation().getLongitude();
if (longitude != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.longitude").toString(), longitude.toString());
}
int i = 0;
for (final Subdivision subd : response.getSubdivisions()) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.subdivision.").append(i).toString(), subd.getName());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.subdivision.isocode.").append(i).toString(), subd.getIsoCode());
i++;
}
attrs.put(new StringBuilder(ipAttributeName).append(".geo.country").toString(), response.getCountry().getName());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.country.isocode").toString(), response.getCountry().getIsoCode());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.postalcode").toString(), response.getPostal().getCode());
flowFile = session.putAllAttributes(flowFile, attrs);
session.transfer(flowFile, REL_FOUND);
}