下面列出了java.util.Map#containsKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static Map<String, List<Button>> groupButtonsByName(Button[] btns, String buttonType) {
Map<String, List<Button>> buttonGroups = new HashMap<>();
if (btns != null) {
for (Button btn : btns) {
if (buttonType.equals(btn.getType())) {
String name = btn.getName();
log.debug("Got " + buttonType + " " + name + " and its value is " + btn.getValue());
if (!buttonGroups.containsKey(name)) {
buttonGroups.get(name).add(btn);
} else {
List<Button> buttons = new ArrayList<>();
buttons.add(btn);
buttonGroups.put(name, buttons);
}
}
}
}
return buttonGroups;
}
public Map<DatasetPath, List<UserBitShared.LayoutMaterializedViewProfile>> getDatasetGroupedLayoutList() {
Map<DatasetPath, List<UserBitShared.LayoutMaterializedViewProfile>> map = Maps.newHashMap();
UserBitShared.AccelerationProfile accelerationProfile = profile.getAccelerationProfile();
List<UserBitShared.LayoutMaterializedViewProfile> layoutProfilesList = accelerationProfile.getLayoutProfilesList();
for (UserBitShared.LayoutMaterializedViewProfile viewProfile : layoutProfilesList) {
String reflectionDatasetPath = accelerationDetails.getReflectionDatasetPath(viewProfile.getLayoutId());
DatasetPath path;
if ("".equals(reflectionDatasetPath)) {
path = new DatasetPath(Arrays.asList("unknown", "missing dataset"));
} else {
path = new DatasetPath(reflectionDatasetPath);
}
if (!map.containsKey(path)) {
map.put(path, new ArrayList<UserBitShared.LayoutMaterializedViewProfile>());
}
map.get(path).add(viewProfile);
}
return map;
}
/**
* Register all metrics in the provided {@link MetricSet}, optionally skipping those that
* already exist.
*
* @param registry registry name
* @param metrics metric set to register
* @param strategy the conflict resolution strategy to use if the named metric already exists.
* @param metricPath (optional) additional top-most metric name path elements
* @throws Exception if a metric with this name already exists.
*/
public void registerAll(String registry, MetricSet metrics, ResolutionStrategy strategy, String... metricPath) throws Exception {
MetricRegistry metricRegistry = registry(registry);
synchronized (metricRegistry) {
Map<String, Metric> existingMetrics = metricRegistry.getMetrics();
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
String fullName = mkName(entry.getKey(), metricPath);
if (existingMetrics.containsKey(fullName)) {
if (strategy == ResolutionStrategy.REPLACE) {
metricRegistry.remove(fullName);
} else if (strategy == ResolutionStrategy.IGNORE) {
continue;
} // strategy == ERROR will fail when we try to register later
}
metricRegistry.register(fullName, entry.getValue());
}
}
}
private void setMaxNumRecordsConfigIfSpecified(Job job) {
TableCustomConfig tableCustomConfig = _tableConfig.getCustomConfig();
if (tableCustomConfig == null) {
return;
}
Map<String, String> customConfigsMap = tableCustomConfig.getCustomConfigs();
if (customConfigsMap != null && customConfigsMap
.containsKey(InternalConfigConstants.PARTITION_MAX_RECORDS_PER_FILE)) {
int maxNumRecords =
Integer.parseInt(customConfigsMap.get(InternalConfigConstants.PARTITION_MAX_RECORDS_PER_FILE));
Preconditions.checkArgument(maxNumRecords > 0,
"The value of " + InternalConfigConstants.PARTITION_MAX_RECORDS_PER_FILE
+ " should be positive. Current value: " + maxNumRecords);
_logger.info("Setting {} to {}", InternalConfigConstants.PARTITION_MAX_RECORDS_PER_FILE, maxNumRecords);
job.getConfiguration()
.set(InternalConfigConstants.PARTITION_MAX_RECORDS_PER_FILE, Integer.toString(maxNumRecords));
}
}
private String getColumnName(JSONObject jsonObject, Map<String, String> columnAliasToName) throws JSONException {
if (jsonObject.isNull("id") && jsonObject.isNull("columnName")) {
return getColumnAlias(jsonObject, columnAliasToName);
} else {
if (jsonObject.has("formula")) {
// it is a calculated field
return jsonObject.getString("formula");
}
String id = jsonObject.getString("id");
boolean isIdMatching = columnAliasToName.containsKey(id) || columnAliasToName.containsValue(id);
String columnName = jsonObject.getString("columnName");
boolean isColumnNameMatching = columnAliasToName.containsKey(columnName) || columnAliasToName.containsValue(columnName);
Assert.assertTrue(isIdMatching || isColumnNameMatching, "Column name [" + columnName + "] not found in dataset metadata");
return isColumnNameMatching ? columnName : id;
}
}
private void verifyMessageArguments(Map<String,Object> args, Map<String,AttributeDefinition> attrs, String type) {
for (Map.Entry<String,AttributeDefinition> entry : attrs.entrySet()) {
AttributeDefinition attr = entry.getValue();
if (!attr.isOptional() && !args.containsKey(entry.getKey())) {
GroovyValidator.error(type + " must contain values for all required parameters: missing '" + attr.getName() + "'");
}
}
for (String arg : args.keySet()) {
if (!attrs.containsKey(arg)) {
GroovyValidator.error("cannot " + type + " message with unknown parameter: '" + arg + "'");
}
}
}
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
String authorities = "ROLE_USER";
if (map.containsKey(AUTHORITIES)) {
authorities = asAuthorities(map.get(AUTHORITIES));
}
return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
}
/**
* Organize failing test cases by their class names
*
* @param caseResultList all the failing test cases list
* @return the map with class name and the set of test methods in each class
*/
static Map<String, Set<String>> getFailingTestClassMethodMap(List<CaseResult> caseResultList) {
Map<String, Set<String>> classMethodMap = new HashMap<String, Set<String>>();
if (caseResultList != null) {
for (CaseResult caseResult : caseResultList) {
if (!classMethodMap.containsKey(caseResult.getClassName())) {
classMethodMap.put(caseResult.getClassName(), new HashSet<String>());
}
classMethodMap.get(caseResult.getClassName()).add(caseResult.getName());
}
}
return classMethodMap;
}
@Test(dependsOnMethods = "testMaintenanceModeInstanceDown")
public void testMaintenanceModeInstanceBack() {
_participants[0] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[0].getInstanceName());
_participants[0].syncStart();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
if (stateMap.containsKey(_participants[0].getInstanceName())) {
Assert.assertEquals(stateMap.get(_participants[0].getInstanceName()), "SLAVE");
}
}
}
private Collection<DatasourceAckFlushTask> createAckFlushTasks(Topic topic) {
Map<String, DatasourceAckFlushTask> tasks = new HashMap<>();
AckFlushHolder flushHolder = m_ackFlushHolders.get(topic.getName());
if (flushHolder != null) {
for (Partition partition : topic.getPartitions()) {
DatasourceAckFlushTask dsTask = tasks.get(partition.getWriteDatasource());
if (dsTask == null) {
dsTask = new DatasourceAckFlushTask(partition.getReadDatasource(), topic.getId());
}
for (ConsumerGroup consumer : topic.getConsumerGroups()) {
OffsetMessage priorityOffsetMessage = flushHolder.getMaxAndResetOffsetMessageHolder(new Triple<>(partition.getId(), true, consumer.getId()));
if (priorityOffsetMessage != null) {
dsTask.addOffsetMessage(priorityOffsetMessage);
}
OffsetMessage nonPriorityOffsetMessage = flushHolder.getMaxAndResetOffsetMessageHolder(new Triple<>(partition.getId(), false, consumer.getId()));
if (nonPriorityOffsetMessage != null) {
dsTask.addOffsetMessage(nonPriorityOffsetMessage);
}
Pair<Integer, Integer> offsetResendKey = new Pair<>(partition.getId(), consumer.getId());
OffsetResend offsetResend = flushHolder.getMaxAndResetOffsetResendHolder(offsetResendKey);
if (offsetResend != null) {
dsTask.addOffsetResend(offsetResend);
}
if (!tasks.containsKey(partition.getWriteDatasource()) && dsTask.getExpectedAffectedOffsetCount() > 0) {
tasks.put(partition.getWriteDatasource(), dsTask);
}
}
}
}
return tasks.values();
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param text String to encode.
* @param lineArray List of unique strings.
* @param lineHash Map of strings to indices.
* @return Encoded string.
*/
private String diff_linesToCharsMunge(String text, List<String> lineArray,
Map<String, Integer> lineHash) {
int lineStart = 0;
int lineEnd = -1;
String line;
StringBuilder chars = new StringBuilder();
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
while (lineEnd < text.length() - 1) {
lineEnd = text.indexOf('\n', lineStart);
if (lineEnd == -1) {
lineEnd = text.length() - 1;
}
line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
if (lineHash.containsKey(line)) {
chars.append(String.valueOf((char) (int) lineHash.get(line)));
} else {
lineArray.add(line);
lineHash.put(line, lineArray.size() - 1);
chars.append(String.valueOf((char) (lineArray.size() - 1)));
}
}
return chars.toString();
}
protected <S, P> void filterUnambiguousPaths(final Pda<S, P> pda, S state, Map<S, Integer> dist,
Map<S, List<S>> followers) {
if (followers.containsKey(state))
return;
List<S> f = Lists.newArrayList(pda.getFollowers(state));
if (f.size() <= 1) {
followers.put(state, f);
if (f.size() == 1)
filterUnambiguousPaths(pda, f.get(0), dist, followers);
return;
}
int closestDist = dist.get(f.get(0));
S closest = f.get(0);
for (int i = 1; i < f.size(); i++) {
int d = dist.get(f.get(i));
if (d < closestDist) {
closestDist = d;
closest = f.get(i);
}
}
IsPop<S, P> isPop = new IsPop<S, P>(pda);
Set<S> closestPops = nfaUtil.findFirst(pda, Collections.singleton(closest), isPop);
Iterator<S> it = f.iterator();
while (it.hasNext()) {
S next = it.next();
if (next != closest) {
Set<S> nextPops = nfaUtil.findFirst(pda, Collections.singleton(next), isPop);
if (!closestPops.equals(nextPops))
it.remove();
}
}
followers.put(state, f);
for (S follower : f)
filterUnambiguousPaths(pda, follower, dist, followers);
}
private static void addMethod(Map<Signature, Method> sigs, Method method) {
Signature signature = new Signature(method);
if (!sigs.containsKey(signature)) {
sigs.put(signature, method);
} else if (!method.getDeclaringClass().isInterface()){
/*
* Superclasses beat interfaces.
*/
Method old = sigs.get(signature);
if (old.getDeclaringClass().isInterface()) {
sigs.put(signature, method);
}
}
}
/**
* Determine variable mappings between two query triples. Note a variable cannot be mapped to multiple variables. If it is, this is an inconsistent mapping
* at a local level that can be dropped
* @param other
* @return
*/
public Map<Variable, Variable> getVariableMappings(QueryTriple other) {
Map<Variable, Variable> ret = HashMapFactory.make();
if (subject.isVariable() && other.getSubject().isVariable()) {
if (ret.containsKey(subject.getVariable())) {
if (!ret.get(subject.getVariable()).equals(other.getSubject().getVariable())) {
return null;
}
} else {
ret.put(subject.getVariable(), other.getSubject().getVariable());
}
}
if (predicate.isVariable() && other.getPredicate().isVariable()) {
if (ret.containsKey(predicate.getVariable())) {
if (!ret.get(predicate.getVariable()).equals(other.getPredicate().getVariable())) {
return null;
}
} else {
ret.put(predicate.getVariable(), other.getPredicate().getVariable());
}
}
if (object.isVariable() && other.getObject().isVariable()) {
if (ret.containsKey(object.getVariable())) {
if (!ret.get(object.getVariable()).equals(other.getObject().getVariable())) {
return null;
}
} else {
ret.put(object.getVariable(), other.getObject().getVariable());
}
}
return ret;
}
protected void initProcessInstanceStateChangedCallbacks(ProcessEngineConfigurationImpl processEngineConfiguration) {
if (processEngineConfiguration.getProcessInstanceStateChangedCallbacks() == null) {
processEngineConfiguration.setProcessInstanceStateChangedCallbacks(new HashMap<>());
}
Map<String, List<RuntimeInstanceStateChangeCallback>> callbacks = processEngineConfiguration.getProcessInstanceStateChangedCallbacks();
if (!callbacks.containsKey(CallbackTypes.PLAN_ITEM_CHILD_PROCESS)) {
callbacks.put(CallbackTypes.PLAN_ITEM_CHILD_PROCESS, new ArrayList<>());
}
callbacks.get(CallbackTypes.PLAN_ITEM_CHILD_PROCESS).add(new ChildProcessInstanceStateChangeCallback(cmmnEngineConfiguration));
}
/**
* Retrieves the class of the bean defined by the xml element.
*
* @param bean the xml element for the bean being parsed
* @return the class associated with the provided tag
*/
@Override
protected Class<?> getBeanClass(Element bean) {
Map<String, BeanTagInfo> beanType = CustomTagAnnotations.getBeanTags();
if (!beanType.containsKey(bean.getLocalName())) {
return null;
}
// retrieve the connected class in the tag map using the xml tag's name.
return beanType.get(bean.getLocalName()).getBeanClass();
}
private HierarchyNode checkAndAddNode(HierarchyNode parentNode, String title, String description, String term){
HierarchyNode node = null;
if(title != null && !"".equals(title)){
Map<String, List<String>> nodeIds = dao.getNodesBySiteRef(new String[]{title}, DelegatedAccessConstants.HIERARCHY_ID);
boolean hasChild = false;
String childNodeId = "";
if(nodeIds != null && nodeIds.containsKey(title) && nodeIds.get(title).size() > 0){
for(String id : nodeIds.get(title)){
if(parentNode.directChildNodeIds.contains(id)){
hasChild = true;
childNodeId = id;
}else if(title.startsWith("/site/")){
//If this is a site, there should (and can only be) 1 parent, delete
//delete the other nodes since they are old
projectLogic.removeNode(hierarchyService.getNodeById(id));
}
}
}
if(!hasChild){
//if this parent/child relationship hasn't been created, create it
HierarchyNode newNode = hierarchyService.addNode(DelegatedAccessConstants.HIERARCHY_ID, parentNode.id);
hierarchyService.saveNodeMetaData(newNode.id, title, description, term);
hierarchyService.addChildRelation(parentNode.id, newNode.id);
node = newNode;
//since we don't want to keep lookup up the parent id after every child is added,
//(b/c the data is stale), just add this id to the set
parentNode.directChildNodeIds.add(node.id);
}else{
//just grab the node
node = hierarchyService.getNodeById(childNodeId);
if(!node.description.equals(description) || !node.title.equals(title)){
node = hierarchyService.saveNodeMetaData(node.id, title, description, term);
}
}
}
return node;
}
/**
* Update the rebalanced ideal states according to the real active nodes.
* Since the rebalancing might be done with the delayed logic, the rebalanced ideal states
* might include inactive nodes.
* This overwrite will adjust the final mapping, so as to ensure the result is completely valid.
* @param idealStateMap the calculated ideal states.
* @param clusterData the cluster data cache.
* @param resourceMap the rebalanaced resource map.
* @param baseline the baseline assignment.
* @param algorithm the rebalance algorithm.
*/
private void applyRebalanceOverwrite(Map<String, IdealState> idealStateMap,
ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap,
Map<String, ResourceAssignment> baseline, RebalanceAlgorithm algorithm)
throws HelixRebalanceException {
ClusterModel clusterModel;
try {
// Note this calculation uses the baseline as the best possible assignment input here.
// This is for minimizing unnecessary partition movement.
clusterModel = ClusterModelProvider
.generateClusterModelFromExistingAssignment(clusterData, resourceMap, baseline);
} catch (Exception ex) {
throw new HelixRebalanceException(
"Failed to generate cluster model for delayed rebalance overwrite.",
HelixRebalanceException.Type.INVALID_CLUSTER_STATUS, ex);
}
Map<String, IdealState> activeIdealStates =
convertResourceAssignment(clusterData, calculateAssignment(clusterModel, algorithm));
for (String resourceName : idealStateMap.keySet()) {
// The new calculated ideal state before overwrite
IdealState newIdealState = idealStateMap.get(resourceName);
if (!activeIdealStates.containsKey(resourceName)) {
throw new HelixRebalanceException(
"Failed to calculate the complete partition assignment with all active nodes. Cannot find the resource assignment for "
+ resourceName, HelixRebalanceException.Type.FAILED_TO_CALCULATE);
}
// The ideal state that is calculated based on the real alive/enabled instances list
IdealState newActiveIdealState = activeIdealStates.get(resourceName);
// The current ideal state that exists in the IdealState znode
IdealState currentIdealState = clusterData.getIdealState(resourceName);
Set<String> enabledLiveInstances = clusterData.getEnabledLiveInstances();
int numReplica = currentIdealState.getReplicaCount(enabledLiveInstances.size());
int minActiveReplica = DelayedRebalanceUtil.getMinActiveReplica(ResourceConfig
.mergeIdealStateWithResourceConfig(clusterData.getResourceConfig(resourceName),
currentIdealState), currentIdealState, numReplica);
Map<String, List<String>> finalPreferenceLists =
DelayedRebalanceUtil.getFinalDelayedMapping(newActiveIdealState.getPreferenceLists(),
newIdealState.getPreferenceLists(), enabledLiveInstances,
Math.min(minActiveReplica, numReplica));
newIdealState.setPreferenceLists(finalPreferenceLists);
}
}
/**
* Methods computing stuff that have to iterate over all categories and access category articles can plug-in here.
* Recently plugin-in:
* numberOfCategorizedArticles
* distributionOfArticlesByCategory
* @param pWiki The wikipedia object.
* @param catGraph The category graph.
* @throws WikiPageNotFoundException
*/
private void iterateCategoriesGetArticles(Wikipedia pWiki, CategoryGraph catGraph) throws WikiPageNotFoundException {
Map<Integer,Integer> localDegreeDistribution = new HashMap<Integer,Integer>();
Set<Integer> localCategorizedArticleSet = new HashSet<Integer>();
Set<Integer> categoryNodes = catGraph.getGraph().vertexSet();
// iterate over all categories
int progress = 0;
for (int node : categoryNodes) {
progress++;
ApiUtilities.printProgressInfo(progress, categoryNodes.size(), 100, ApiUtilities.ProgressInfoMode.TEXT, "iterate over categories");
// get the category
Category cat = pWiki.getCategory(node);
if (cat != null) {
Set<Integer> pages = new HashSet<Integer>(cat.__getPages());
// update degree distribution map
int numberOfArticles = pages.size();
if (localDegreeDistribution.containsKey(numberOfArticles)) {
int count = localDegreeDistribution.get(numberOfArticles);
count++;
localDegreeDistribution.put(numberOfArticles, count);
}
else {
localDegreeDistribution.put(numberOfArticles, 1);
}
// add the page to the categorized articles set, if it is to already in it
for (int page : pages) {
if (!localCategorizedArticleSet.contains(page)) {
localCategorizedArticleSet.add(page);
}
}
}
else {
logger.info("{} is not a category.", node);
}
}
this.degreeDistribution = localDegreeDistribution;
this.categorizedArticleSet = localCategorizedArticleSet;
}
/**
* Match input parameter values with the parameters declared to be used in the call.
* @param parameterSource the input values
* @return a Map containing the matched parameter names with the value taken from the input
*/
public Map<String, Object> matchInParameterValuesWithCallParameters(SqlParameterSource parameterSource) {
// For parameter source lookups we need to provide case-insensitive lookup support
// since the database meta-data is not necessarily providing case sensitive parameter names.
Map<String, String> caseInsensitiveParameterNames =
SqlParameterSourceUtils.extractCaseInsensitiveParameterNames(parameterSource);
Map<String, String> callParameterNames = new HashMap<>(this.callParameters.size());
Map<String, Object> matchedParameters = new HashMap<>(this.callParameters.size());
for (SqlParameter parameter : this.callParameters) {
if (parameter.isInputValueProvided()) {
String parameterName = parameter.getName();
String parameterNameToMatch = obtainMetaDataProvider().parameterNameToUse(parameterName);
if (parameterNameToMatch != null) {
callParameterNames.put(parameterNameToMatch.toLowerCase(), parameterName);
}
if (parameterName != null) {
if (parameterSource.hasValue(parameterName)) {
matchedParameters.put(parameterName,
SqlParameterSourceUtils.getTypedValue(parameterSource, parameterName));
}
else {
String lowerCaseName = parameterName.toLowerCase();
if (parameterSource.hasValue(lowerCaseName)) {
matchedParameters.put(parameterName,
SqlParameterSourceUtils.getTypedValue(parameterSource, lowerCaseName));
}
else {
String englishLowerCaseName = parameterName.toLowerCase(Locale.ENGLISH);
if (parameterSource.hasValue(englishLowerCaseName)) {
matchedParameters.put(parameterName,
SqlParameterSourceUtils.getTypedValue(parameterSource, englishLowerCaseName));
}
else {
String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(parameterName);
if (parameterSource.hasValue(propertyName)) {
matchedParameters.put(parameterName,
SqlParameterSourceUtils.getTypedValue(parameterSource, propertyName));
}
else {
if (caseInsensitiveParameterNames.containsKey(lowerCaseName)) {
String sourceName = caseInsensitiveParameterNames.get(lowerCaseName);
matchedParameters.put(parameterName,
SqlParameterSourceUtils.getTypedValue(parameterSource, sourceName));
}
else if (logger.isInfoEnabled()) {
logger.info("Unable to locate the corresponding parameter value for '" +
parameterName + "' within the parameter values provided: " +
caseInsensitiveParameterNames.values());
}
}
}
}
}
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Matching " + caseInsensitiveParameterNames.values() + " with " + callParameterNames.values());
logger.debug("Found match for " + matchedParameters.keySet());
}
return matchedParameters;
}