下面列出了java.util.LinkedHashMap#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void assertEntryEquals(
CloseableIterator<IndexEntry> closeableIterator, Map expected) {
LinkedHashMap actual = new LinkedHashMap();
while(closeableIterator.hasNext()) {
IndexEntry entry = closeableIterator.next();
Object ikey = entry.getKey().getDeserializedForReading();
Object rkey = entry.getRegionKey().getDeserializedForReading();
Object value = entry.getValue().getDeserializedForReading();
actual.put(new Pair(ikey, rkey), value);
}
assertEquals(expected, actual);
}
/**
* 添加自己的过滤器,自定义url规则
* Shiro自带拦截器配置规则
* rest:比如/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等
* port:比如/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数
* perms:比如/admins/user/**=perms[user:add:*],perms参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,比如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法
* roles:比如/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,比如/admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。//要实现or的效果看http://zgzty.blog.163.com/blog/static/83831226201302983358670/
* anon:比如/admins/**=anon 没有参数,表示可以匿名使用
* authc:比如/admins/user/**=authc表示需要认证才能使用,没有参数
* authcBasic:比如/admins/user/**=authcBasic没有参数表示httpBasic认证
* ssl:比如/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
* user:比如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查
* 详情见文档 http://shiro.apache.org/web.html#urls-
* @param securityManager
* @return org.apache.shiro.spring.web.ShiroFilterFactoryBean
* @author dolyw.com
* @date 2018/8/31 10:57
*/
@Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
// 添加自己的过滤器取名为jwt
Map<String, Filter> filterMap = new HashMap<>(16);
filterMap.put("jwt", new JwtFilter());
factoryBean.setFilters(filterMap);
factoryBean.setSecurityManager(securityManager);
// 自定义url规则使用LinkedHashMap有序Map
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(16);
// Swagger接口文档
// filterChainDefinitionMap.put("/v2/api-docs", "anon");
// filterChainDefinitionMap.put("/webjars/**", "anon");
// filterChainDefinitionMap.put("/swagger-resources/**", "anon");
// filterChainDefinitionMap.put("/swagger-ui.html", "anon");
// filterChainDefinitionMap.put("/doc.html", "anon");
// 公开接口
// filterChainDefinitionMap.put("/api/**", "anon");
// 登录接口放开
filterChainDefinitionMap.put("/user/login", "anon");
// 所有请求通过我们自己的JWTFilter
filterChainDefinitionMap.put("/**", "jwt");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return factoryBean;
}
/**
* @throws Exception In case of an error.
*/
@Test
public void testValueReadQueryEntities() throws Exception {
Ignite ignite = startGrid(0);
LinkedHashMap<String, String> fields = new LinkedHashMap<>();
fields.put("id", "java.lang.Integer");
fields.put("str", "java.lang.String");
IgniteCache binary = ignite.createCache(new CacheConfiguration<>()
.setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
.setKeyFieldName("id").setValueType("Payload").setFields(fields).setTableName("binary"))));
binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (1, 'foo');"));
binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (2, 'bar');"));
GridTestUtils.assertThrowsAnyCause(
log,
new Callable<Object>() {
@Override public Object call() {
return ignite.cache("binary").get(1);
}
},
BinaryInvalidTypeException.class,
"Payload");
}
FunctionPatchTransition(
StarlarkDefinedConfigTransition starlarkDefinedConfigTransition, Rule rule) {
super(starlarkDefinedConfigTransition);
LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
RawAttributeMapper attributeMapper = RawAttributeMapper.of(rule);
for (Attribute attribute : rule.getAttributes()) {
Object val = attributeMapper.getRawAttributeValue(rule, attribute);
if (val instanceof BuildType.SelectorList) {
// For now, don't allow access to attributes that read selects.
// TODO(b/121134880): make this restriction more fine grained.
continue;
}
attributes.put(
Attribute.getStarlarkName(attribute.getPublicName()), Starlark.fromJava(val, null));
}
attrObject =
StructProvider.STRUCT.create(
attributes,
"No attribute '%s'. Either this attribute does "
+ "not exist for this rule or is set by a select. Starlark rule transitions "
+ "currently cannot read attributes behind selects.");
}
private static LinkedHashMap<String, List<GenomeLoc>> splitByContig(final List<GenomeLoc> sorted) {
final LinkedHashMap<String, List<GenomeLoc>> splits = new LinkedHashMap<>();
GenomeLoc last = null;
List<GenomeLoc> contigLocs = null;
for (final GenomeLoc loc: sorted) {
if (GenomeLoc.isUnmapped(loc)) {
continue;
}
if (last == null || !last.onSameContig(loc)) {
contigLocs = new ArrayList<>();
splits.put(loc.getContig(), contigLocs);
}
contigLocs.add(loc);
last = loc;
}
return splits;
}
private void checkQuotes(boolean isBlock, String expectation) {
DumperOptions options = new DumperOptions();
options.setIndent(4);
if (isBlock) {
options.setDefaultFlowStyle(FlowStyle.BLOCK);
}
Representer representer = new Representer();
Yaml yaml = new Yaml(new SafeConstructor(), representer, options);
LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>();
lvl1.put("steak:cow", "11");
LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>();
root.put("cows", lvl1);
String output = yaml.dump(root);
assertEquals(expectation + "\n", output);
// parse the value back
@SuppressWarnings("unchecked")
Map<String, Object> cows = (Map<String, Object>) yaml.load(output);
@SuppressWarnings("unchecked")
Map<String, String> cow = (Map<String, String>) cows.get("cows");
assertEquals("11", cow.get("steak:cow"));
}
/**
* Reloads the internal SPI list from the given {@link ClassLoader}.
* Changes to the service list are visible after the method ends, all
* iterators ({@link #iterator()},...) stay consistent.
*
* <p><b>NOTE:</b> Only new service providers are added, existing ones are
* never removed or replaced.
*
* <p><em>This method is expensive and should only be called for discovery
* of new service providers on the given classpath/classloader!</em>
*/
public void reload(ClassLoader classloader) {
Objects.requireNonNull(classloader, "classloader");
final LinkedHashMap<String,S> services = new LinkedHashMap<>(this.services);
for (final S service : ServiceLoader.load(clazz, classloader)) {
final String name = service.getName();
// only add the first one for each name, later services will be ignored
// this allows to place services before others in classpath to make
// them used instead of others
if (!services.containsKey(name)) {
checkServiceName(name);
services.put(name, service);
}
}
this.services = Collections.unmodifiableMap(services);
}
/**
* @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap m = new LinkedHashMap();
m.put(KFSPropertyConstants.DOCUMENT_NUMBER, this.documentNumber);
if (this.correctionChangeGroupLineNumber != null) {
m.put("correctionChangeGroupLineNumber", this.correctionChangeGroupLineNumber.toString());
}
if (this.correctionCriteriaLineNumber != null) {
m.put("correctionCriteriaLineNumber", this.correctionCriteriaLineNumber.toString());
}
return m;
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void addMultipleRatesContainingEntryWithNoCommonCurrency() {
LinkedHashMap<Pair<Currency, Currency>, Double> rates = new LinkedHashMap<>();
rates.put(currencyPair(GBP, USD), 1.6);
rates.put(currencyPair(EUR, USD), 1.4);
rates.put(currencyPair(JPY, CAD), 0.01); // Neither currency linked to one of the others
FxMatrix.builder().addRates(rates);
}
public void rebuildIndex() {
LinkedHashMap<Vec3D, Vertex> newV = new LinkedHashMap<Vec3D, Vertex>(
vertices.size());
for (Vertex v : vertices.values()) {
newV.put(v, v);
}
vertices = newV;
LinkedHashMap<Line3D, WingedEdge> newE = new LinkedHashMap<Line3D, WingedEdge>(
edges.size());
for (WingedEdge e : edges.values()) {
newE.put(e, e);
}
edges = newE;
}
private JsonObject getPipeLineResponse(LinkedHashMap<String, List<JsonObject>> map, JsonObject dataModel)
throws InsightsCustomException {
JsonArray pipeLineArray = new JsonArray();
JsonObject pipeLineObject = new JsonObject();
LinkedHashMap<String, String> sortedHandoverTimeMap = new LinkedHashMap<>();
Set<Entry<String, List<JsonObject>>> keyset = map.entrySet();
for (Map.Entry<String, List<JsonObject>> keyvaluePair : keyset) {
List<JsonObject> limitedList = keyvaluePair.getValue().stream().limit(4).collect(Collectors.toList());
limitedList.forEach(obj -> pipeLineArray.add(obj));
// Handover time object extraction and sorting
try {
List<String> childNodes = getDownTool(keyvaluePair.getKey(), dataModel);
for (String eachNode : childNodes) {
String construct = keyvaluePair.getKey() + " To " + eachNode;
sortedHandoverTimeMap.put(construct, handOverTimeMap.get(construct));
}
} catch (InsightsCustomException e) {
LOG.debug(e.getMessage());
}
}
/* Prepare Summary */
JsonObject summaryObj = prepareSummary(map, dataModel);
JsonArray summaryArray = new JsonArray();
summaryArray.add(summaryObj);
/* Timelag Response */
JsonObject handOverTime = new JsonObject();
sortedHandoverTimeMap.forEach((k, v) -> handOverTime.addProperty(k, v));
JsonArray handOverArray = new JsonArray();
handOverArray.add(handOverTime);
/* Pipeline Response */
pipeLineObject.add("pipeline", pipeLineArray);
pipeLineObject.add("summary", summaryArray);
pipeLineObject.add("timelag", handOverArray);
return pipeLineObject;
}
/**
* If a CollectionEntry represents a batch loadable collection, add
* it to the queue.
*/
public void addBatchLoadableCollection(PersistentCollection collection, CollectionEntry ce) {
final CollectionPersister persister = ce.getLoadedPersister();
LinkedHashMap<CollectionEntry, PersistentCollection> map = batchLoadableCollections.get( persister.getRole() );
if ( map == null ) {
map = new LinkedHashMap<>( 16 );
batchLoadableCollections.put( persister.getRole(), map );
}
map.put( ce, collection );
}
private Map<PartitionInfoCacheSupport.PartitionValues, String> getDefaultPartitionValuesInfo() {
Map<PartitionInfoCacheSupport.PartitionValues, String> defaultPartitionValues = new HashMap<>();
LinkedHashMap<String, String> partition1 = new LinkedHashMap<>();
partition1.put("dt", "12-25-2015");
partition1.put("year", "2015");
partition1.put("month", "12");
partition1.put("day", "25");
defaultPartitionValues.put(new PartitionInfoCacheSupport.PartitionValues(partition1), "1");
LinkedHashMap<String, String> partition2 = new LinkedHashMap<>();
partition2.put("dt", "11-25-2015");
partition2.put("year", "2015");
partition2.put("month", "11");
partition2.put("day", "25");
defaultPartitionValues.put(new PartitionInfoCacheSupport.PartitionValues(partition2), "2");
LinkedHashMap<String, String> partition3 = new LinkedHashMap<>();
partition3.put("dt", "12-26-2015");
partition3.put("year", "2015");
partition3.put("month", "12");
partition3.put("day", "26");
defaultPartitionValues.put(new PartitionInfoCacheSupport.PartitionValues(partition3), "3");
return defaultPartitionValues;
}
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap<String, String> m = new LinkedHashMap<String, String>();
if (this.documentNumber != null) {
m.put("documentNumber", this.documentNumber.toString());
}
if (this.capitalAssetNumber != null) {
m.put("capitalAssetNumber", this.capitalAssetNumber.toString());
}
return m;
}
@CliCommand(value = STREAM_PLATFORM_LIST, help = "List Skipper platforms")
public Table listPlatforms() {
Collection<Deployer> platforms = streamOperations().listPlatforms();
LinkedHashMap<String, Object> headers = new LinkedHashMap<>();
headers.put("name", "Name");
headers.put("type", "Type");
headers.put("description", "Description");
BeanListTableModel<Deployer> model = new BeanListTableModel<>(platforms, headers);
return DataFlowTables.applyStyle(new TableBuilder(model)).build();
}
public static LinkedHashMap<String, Object> getLinkedHashMapObject() {
LinkedHashMap<String, Object> ruleMap = new LinkedHashMap<>();
ruleMap.put("datasource", "aws");
ruleMap.put("targetType", "ec2");
ruleMap.put("annotationid", "annotationid");
ruleMap.put("status", "open");
ruleMap.put("auditdate", "2017-11-09T18:03:30.263Z");
ruleMap.put("_auditdate", "2017-11-09");
ruleMap.put("ruleId", "PacMan_TaggingRule_version-1_Ec2TaggingRule_ec2");
return ruleMap;
}
/**
* The method will get triggered from Rule Engine with following parameters
*
* @param ruleParam
*
************** Following are the Rule Parameters********* <br><br>
*
* ruleKey : check-for-unused-ebs-rule <br><br>
*
* threadsafe : if true , rule will be executed on multiple threads <br><br>
*
* esEbsWithInstanceUrl : Enter the ebs es api <br><br>
*
* severity : Enter the value of severity <br><br>
*
* ruleCategory : Enter the value of category <br><br>
*
* @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
*
*/
public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
logger.debug("========UnusedEBSRule started=========");
Annotation annotation = null;
String volumeId = null;
String region = null;
String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
String ebsUrl = null;
String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_EBS_WITH_INSTANCE_URL);
if(!StringUtils.isNullOrEmpty(formattedUrl)){
ebsUrl = formattedUrl;
}
MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
if (!PacmanUtils.doesAllHaveValue(severity,category,ebsUrl)) {
logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
}
if (resourceAttributes != null) {
volumeId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.VOLUME_ID));
region = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.REGION_ATTR));
boolean isEbsWithEc2Exists = false;
try{
isEbsWithEc2Exists = PacmanUtils.checkResourceIdFromElasticSearch(volumeId,ebsUrl,PacmanRuleConstants.VOLUME_ID,region);
} catch (Exception e) {
logger.error("unable to determine",e);
throw new RuleExecutionFailedExeption("unable to determine"+e);
}
if (!isEbsWithEc2Exists) {
annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
annotation.put(PacmanSdkConstants.DESCRIPTION,"Unused EBS found!!");
annotation.put(PacmanRuleConstants.SEVERITY, severity);
annotation.put(PacmanRuleConstants.SUBTYPE, Annotation.Type.RECOMMENDATION.toString());
annotation.put(PacmanRuleConstants.CATEGORY, category);
issue.put(PacmanRuleConstants.VIOLATION_REASON, "EBS volume is not attached to an ec2 instance");
issueList.add(issue);
annotation.put("issueDetails",issueList.toString());
logger.debug("========UnusedEBSRule ended with annotation {} :=========",annotation);
return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
}
}
logger.debug("========UnusedEBSRule ended=========");
return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
/**
* @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap m = new LinkedHashMap();
m.put("financialHigherEdFunctionCd", this.financialHigherEdFunctionCd);
return m;
}
/** Runs with defaults, starting today */
public static void main(String[] args) throws UnsupportedEncodingException {
String[] jarPath = pathToUberJar();
long day = args.length == 1 ? parseDay(args[0]) : System.currentTimeMillis();
String storageType = System.getenv("STORAGE_TYPE");
if (storageType == null) {
throw new IllegalArgumentException("STORAGE_TYPE not set");
}
String zipkinLogLevel = System.getenv("ZIPKIN_LOG_LEVEL");
if (zipkinLogLevel == null) zipkinLogLevel = "INFO";
Runnable logInitializer = LogInitializer.create(zipkinLogLevel);
logInitializer.run(); // Ensures local log commands emit
final LinkedHashMap<String, String> sparkConf = new LinkedHashMap<>();
String sparkConfRaw = System.getenv("SPARK_CONF");
if (sparkConfRaw != null && !sparkConfRaw.isEmpty() && sparkConfRaw.indexOf("=") > -1) {
for (String pair : sparkConfRaw.split(",", -1)) {
final String[] splits = pair.split("=", -1);
if (splits.length == 2) {
sparkConf.put(splits[0], splits[1]);
}
}
}
switch (storageType) {
case "cassandra":
CassandraDependenciesJob.builder()
.logInitializer(logInitializer)
.jars(jarPath)
.day(day)
.conf(sparkConf)
.build()
.run();
break;
case "cassandra3":
zipkin2.dependencies.cassandra3.CassandraDependenciesJob.builder()
.logInitializer(logInitializer)
.jars(jarPath)
.day(day)
.conf(sparkConf)
.build()
.run();
break;
case "mysql":
MySQLDependenciesJob.builder()
.logInitializer(logInitializer)
.jars(jarPath)
.day(day)
.conf(sparkConf)
.build()
.run();
break;
case "elasticsearch":
ElasticsearchDependenciesJob.builder()
.logInitializer(logInitializer)
.jars(jarPath)
.day(day)
.conf(sparkConf)
.build()
.run();
break;
default:
throw new UnsupportedOperationException("Unsupported STORAGE_TYPE: " + storageType);
}
}
@Override
public Map<String, Object> asJson() throws Exception {
LinkedHashMap<String, Object> json = new LinkedHashMap<>();
json.put("Available Toggles", featureToggleService.allToggles().all());
return json;
}