Java Code Examples for java.util.Map#keySet()
The following examples show how to use
java.util.Map#keySet() .
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: Magical.java From neohabitat with MIT License | 6 votes |
private void random_porter(User from, HabitatMod target) { Avatar avatar = (Avatar) avatar_target_check(target); if (avatar != null) { object_broadcast(noid, "Where she stops, nobody knows!"); send_magic_success(from); avatar.x = 80; avatar.y = 132; String destination = avatar.turf; if(magic_data != 0) { // Lookup a random teleport as destination! // @SuppressWarnings("unchecked") Map<String, String> directory = (Map <String, String>) context().getStaticObject("teleports"); List<String> keys = new ArrayList<String>(directory.keySet()); destination = directory.get(keys.get(rand.nextInt(keys.size() - 1) + 1)); } avatar.change_regions(destination, AUTO_TELEPORT_DIR, TELEPORT_ENTRY); } else { object_say(from, "Nothing happens."); send_magic_error(from); } }
Example 2
Source File: ConfigTools.java From MyBox with Apache License 2.0 | 6 votes |
public static boolean writeValues(File file, Map<String, String> values) { try { if (file == null || values == null) { return false; } Properties conf = new Properties(); try ( BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { for (String key : values.keySet()) { conf.setProperty(key, values.get(key)); } conf.store(out, "Update "); } return true; } catch (Exception e) { logger.error(e.toString()); return false; } }
Example 3
Source File: InstanceAdminExample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** Demonstrates how to get an instance. */ public Instance getInstance() { System.out.println("\nGet Instance"); // [START bigtable_get_instance] Instance instance = null; try { instance = adminClient.getInstance(instanceId); System.out.println("Instance ID: " + instance.getId()); System.out.println("Display Name: " + instance.getDisplayName()); System.out.print("Labels: "); Map<String, String> labels = instance.getLabels(); for (String key : labels.keySet()) { System.out.printf("%s - %s", key, labels.get(key)); } System.out.println("\nState: " + instance.getState()); System.out.println("Type: " + instance.getType()); } catch (NotFoundException e) { System.err.println("Failed to get non-existent instance: " + e.getMessage()); } // [END bigtable_get_instance] return instance; }
Example 4
Source File: JWTClient.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
public AccessTokenInfo getAccessToken(String consumerKey, String consumerSecret, String username, String scopes, Map<String, String> paramsMap) throws JWTClientException { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(JWTConstants.GRANT_TYPE_PARAM_NAME, jwtConfig.getJwtGrantType())); String assertion = JWTClientUtil.generateSignedJWTAssertion(username, jwtConfig, isDefaultJWTClient); if (assertion == null) { throw new JWTClientException("JWT is not configured properly for user : " + username); } params.add(new BasicNameValuePair(JWTConstants.JWT_PARAM_NAME, assertion)); if (scopes != null && !scopes.isEmpty()) { params.add(new BasicNameValuePair(JWTConstants.SCOPE_PARAM_NAME, scopes)); } if (paramsMap != null) { for (String key : paramsMap.keySet()) { params.add(new BasicNameValuePair(key, paramsMap.get(key))); } } return getTokenInfo(params, consumerKey, consumerSecret); }
Example 5
Source File: SnifferStatusResourceController.java From logsniffer with GNU Lesser General Public License v3.0 | 6 votes |
@RequestMapping(value = "/sniffers/{snifferId}/status/summary", method = RequestMethod.GET) @ResponseBody Map<String, Object> getStatusSummary(@PathVariable("snifferId") final long snifferId) throws IOException, ResourceNotFoundException { final Sniffer sniffer = getSniffer(snifferId); final LogSource<?> source = getSource(sniffer); final List<LogSniffingStatus> logsStatus = new ArrayList<LogSniffingStatus>(); final Map<Log, IncrementData> logsIncData = snifferPersistence.getIncrementDataByLog(sniffer, source); for (final Log log : logsIncData.keySet()) { final LogRawAccess<?> logAccess = source.getLogAccess(log); final IncrementData incData = logsIncData.get(log); LogPointer currentPointer = null; long currentOffset = 0; if (incData.getNextOffset() != null) { currentPointer = logAccess.refresh(logAccess.getFromJSON(incData.getNextOffset().getJson())).get(); } if (currentPointer != null) { currentOffset = Math.abs(logAccess.getDifference(null, currentPointer)); } logsStatus.add(new LogSniffingStatus(log, currentPointer, currentOffset, log.getSize())); } final HashMap<String, Object> summary = new HashMap<>(); summary.put("scheduleInfo", snifferScheduler.getScheduleInfo(snifferId)); summary.put("logsStatus", logsStatus); return summary; }
Example 6
Source File: HBaseTableSchema.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Returns the names of all registered column qualifiers of a specific column family. * * @param family The name of the column family for which the column qualifier names are returned. * @return The names of all registered column qualifiers of a specific column family. */ String[] getQualifierNames(String family) { Map<String, TypeInformation<?>> qualifierMap = familyMap.get(family); if (qualifierMap == null) { throw new IllegalArgumentException("Family " + family + " does not exist in schema."); } String[] qualifierNames = new String[qualifierMap.size()]; int i = 0; for (String qualifier: qualifierMap.keySet()) { qualifierNames[i] = qualifier; i++; } return qualifierNames; }
Example 7
Source File: TransitionsExtension.java From litho with Apache License 2.0 | 6 votes |
private void createNewTransitions(TransitionsExtensionInput input, Transition rootTransition) { prepareTransitionManager(); Map<TransitionId, OutputUnitsAffinityGroup<LayoutOutput>> lastTransitions = mLastTransitionsExtensionInput == null ? null : mLastTransitionsExtensionInput.getTransitionIdMapping(); mTransitionManager.setupTransitions( lastTransitions, input.getTransitionIdMapping(), rootTransition); final Map<TransitionId, ?> nextTransitionIds = input.getTransitionIdMapping(); for (TransitionId transitionId : nextTransitionIds.keySet()) { if (mTransitionManager.isAnimating(transitionId)) { mAnimatingTransitionIds.add(transitionId); } } }
Example 8
Source File: DistinctDeriver.java From envelope with Apache License 2.0 | 6 votes |
private void validate(Map<String, Dataset<Row>> dependencies) { switch (dependencies.size()) { case 0: throw new RuntimeException("Distinct deriver requires at least one dependency"); case 1: if (stepName == null) { stepName = dependencies.keySet().iterator().next(); } else { if (!dependencies.containsKey(stepName)) { throw new RuntimeException( "Invalid \"step\" configuration: " + stepName + " is not a dependency: " + dependencies.keySet() + ""); } } break; default: if (stepName == null) throw new RuntimeException( "Distinct deriver requires a \"step\" configuration when multiple dependencies have been listed: " + dependencies.keySet() + ""); if (!dependencies.containsKey(stepName)) throw new RuntimeException("Invalid \"step\" configuration: " + stepName + " is not listed as dependency: " + dependencies.keySet() + ""); } }
Example 9
Source File: DominatorTreeExceptionFilter.java From javaide with GNU General Public License v3.0 | 6 votes |
private Map<Integer, Integer> buildExceptionDoms(Integer id) { Map<Integer, Integer> map = new HashMap<>(); Set<Integer> children = mapTreeBranches.get(id); if (children != null) { for (Integer childid : children) { Map<Integer, Integer> mapChild = buildExceptionDoms(childid); for (Integer handler : mapChild.keySet()) { map.put(handler, map.containsKey(handler) ? id : mapChild.get(handler)); } } } for (Entry<Integer, Set<Integer>> entry : mapExceptionRanges.entrySet()) { if (entry.getValue().contains(id)) { map.put(entry.getKey(), id); } } return map; }
Example 10
Source File: DynamoDBScanItems.java From aws-doc-sdk-examples with Apache License 2.0 | 6 votes |
public static void scanItems( DynamoDbClient ddb,String tableName ) { try { ScanRequest scanRequest = ScanRequest.builder() .tableName(tableName) .build(); ScanResponse response = ddb.scan(scanRequest); for (Map<String, AttributeValue> item : response.items()) { Set<String> keys = item.keySet(); for (String key : keys) { System.out.println ("The key name is "+key +"\n" ); System.out.println("The value is "+item.get(key).s()); } } } catch (DynamoDbException e) { e.printStackTrace(); } // snippet-end:[dynamodb.java2.dynamoDB_scan.main] }
Example 11
Source File: PDGSlice.java From JDeodorant with MIT License | 6 votes |
private boolean duplicatedSliceNodeWithClassInstantiationHasDependenceOnRemovableNode() { Set<PDGNode> duplicatedNodes = new LinkedHashSet<PDGNode>(); duplicatedNodes.addAll(sliceNodes); duplicatedNodes.retainAll(indispensableNodes); for(PDGNode duplicatedNode : duplicatedNodes) { if(duplicatedNode.containsClassInstanceCreation()) { Map<VariableDeclaration, ClassInstanceCreation> classInstantiations = duplicatedNode.getClassInstantiations(); for(VariableDeclaration variableDeclaration : classInstantiations.keySet()) { for(GraphEdge edge : duplicatedNode.outgoingEdges) { PDGDependence dependence = (PDGDependence)edge; if(edges.contains(dependence) && dependence instanceof PDGDependence) { PDGDependence dataDependence = (PDGDependence)dependence; PDGNode dstPDGNode = (PDGNode)dataDependence.dst; if(removableNodes.contains(dstPDGNode)) { if(dstPDGNode.changesStateOfReference(variableDeclaration) || dstPDGNode.assignsReference(variableDeclaration) || dstPDGNode.accessesReference(variableDeclaration)) return true; } } } } } } return false; }
Example 12
Source File: StrUtil.java From DataLink with Apache License 2.0 | 6 votes |
public static String replaceVariable(final String param) { Map<String, String> mapping = new HashMap<String, String>(); Matcher matcher = VARIABLE_PATTERN.matcher(param); while (matcher.find()) { String variable = matcher.group(2); String value = System.getProperty(variable); if (StringUtils.isBlank(value)) { value = matcher.group(); } mapping.put(matcher.group(), value); } String retString = param; for (final String key : mapping.keySet()) { retString = retString.replace(key, mapping.get(key)); } return retString; }
Example 13
Source File: RulesView.java From geofence with GNU General Public License v2.0 | 5 votes |
/** * On rule custom prop update key. * * @param event * the event */ private void onRuleCustomPropUpdateKey(AppEvent event) { if (event.getData() != null) { LayerCustomPropsTabItem layersCustomPropsItem = (LayerCustomPropsTabItem) this.ruleEditorDialog .getTabWidget() .getItemByItemId( RuleDetailsEditDialog.RULE_LAYER_CUSTOM_PROPS_DIALOG_ID); final LayerCustomPropsGridWidget layerCustomPropsInfo = layersCustomPropsItem .getLayerCustomPropsWidget().getLayerCustomPropsInfo(); Map<String, LayerCustomProps> updateDTO = event.getData(); for (String key : updateDTO.keySet()) { for (LayerCustomProps prop : layerCustomPropsInfo.getStore() .getModels()) { if (prop.getPropKey().equals(key)) { layerCustomPropsInfo.getStore().remove(prop); LayerCustomProps newModel = updateDTO.get(key); layerCustomPropsInfo.getStore().add(newModel); } } } layerCustomPropsInfo.getGrid().repaint(); } else { // TODO: i18n!! Dispatcher.forwardEvent(GeofenceEvents.SEND_ERROR_MESSAGE, new String[] { "Rules Details Editor", "Could not found any associated rule!" }); } }
Example 14
Source File: GenericDaoImpl.java From olat with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private <K> Iterator<K> getQueryIterator(String queryName, Map<String, Object> queryParameters) { Query query = getNamedQuery(queryName); for (String key : queryParameters.keySet()) { query.setParameter(key, queryParameters.get(key)); } return query.iterate(); }
Example 15
Source File: EntityREST.java From incubator-atlas with Apache License 2.0 | 5 votes |
/** * Validate that each attribute given is an unique attribute * @param entityType the entity type * @param attributes attributes */ private void validateUniqueAttribute(AtlasEntityType entityType, Map<String, Object> attributes) throws AtlasBaseException { if (MapUtils.isEmpty(attributes)) { throw new AtlasBaseException(AtlasErrorCode.ATTRIBUTE_UNIQUE_INVALID, entityType.getTypeName(), ""); } for (String attributeName : attributes.keySet()) { AtlasAttributeDef attribute = entityType.getAttributeDef(attributeName); if (attribute == null || !attribute.getIsUnique()) { throw new AtlasBaseException(AtlasErrorCode.ATTRIBUTE_UNIQUE_INVALID, entityType.getTypeName(), attributeName); } } }
Example 16
Source File: DataLoader.java From Shuffle-Move with GNU General Public License v3.0 | 5 votes |
/** * Folds all results from the secondary into the primary map. The primary is altered, the * secondary is not. Does not return anything. */ public static <X> void mergeSafely(Map<String, List<X>> primary, Map<String, List<X>> secondary) { if (primary == null || secondary == null) { return; } for (String key : secondary.keySet()) { if (primary.containsKey(key)) { primary.get(key).addAll(secondary.get(key)); } else { primary.put(key, secondary.get(key)); } } }
Example 17
Source File: TestHsWebServicesAttempts.java From big-c with Apache License 2.0 | 5 votes |
@Test public void testTaskAttemptIdDefault() throws JSONException, Exception { WebResource r = resource(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); for (Task task : jobsMap.get(id).getTasks().values()) { String tid = MRApps.toString(task.getID()); for (TaskAttempt att : task.getAttempts().values()) { TaskAttemptId attemptid = att.getID(); String attid = MRApps.toString(attemptid); ClientResponse response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("tasks") .path(tid).path("attempts").path(attid).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); assertEquals("incorrect number of elements", 1, json.length()); JSONObject info = json.getJSONObject("taskAttempt"); verifyHsTaskAttempt(info, att, task.getType()); } } } }
Example 18
Source File: Application.java From dr-elephant with Apache License 2.0 | 4 votes |
/** * The data for plotting the flow history graph * * <pre> * {@code * [ * { * "flowtime": <Last job's finish time>, * "score": 1000, * "jobscores": [ * { * "jobdefurl:" "url", * "jobexecurl:" "url", * "jobscore": 500 * }, * { * "jobdefurl:" "url", * "jobexecurl:" "url", * "jobscore": 500 * } * ] * }, * { * "flowtime": <Last job's finish time>, * "score": 700, * "jobscores": [ * { * "jobdefurl:" "url", * "jobexecurl:" "url", * "jobscore": 0 * }, * { * "jobdefurl:" "url", * "jobexecurl:" "url", * "jobscore": 700 * } * ] * } * ] * } * </pre> */ public static Result restFlowGraphData(String flowDefId) { JsonArray datasets = new JsonArray(); if (flowDefId == null || flowDefId.isEmpty()) { return ok(new Gson().toJson(datasets)); } // Fetch available flow executions with latest JOB_HISTORY_LIMIT mr jobs. List<AppResult> results = getRestFlowAppResults(flowDefId); if (results.size() == 0) { logger.info("No results for Job url"); } Map<IdUrlPair, List<AppResult>> flowExecIdToJobsMap = ControllerUtil.limitHistoryResults(ControllerUtil.groupJobs(results, ControllerUtil.GroupBy.FLOW_EXECUTION_ID), results.size(), MAX_HISTORY_LIMIT); // Compute the graph data starting from the earliest available execution to latest List<IdUrlPair> keyList = new ArrayList<IdUrlPair>(flowExecIdToJobsMap.keySet()); for (int i = keyList.size() - 1; i >= 0; i--) { IdUrlPair flowExecPair = keyList.get(i); int flowPerfScore = 0; JsonArray jobScores = new JsonArray(); List<AppResult> mrJobsList = Lists.reverse(flowExecIdToJobsMap.get(flowExecPair)); Map<IdUrlPair, List<AppResult>> jobDefIdToJobsMap = ControllerUtil.groupJobs(mrJobsList, ControllerUtil.GroupBy.JOB_DEFINITION_ID); // Compute the execution records. Note that each entry in the jobDefIdToJobsMap will have at least one AppResult for (IdUrlPair jobDefPair : jobDefIdToJobsMap.keySet()) { // Compute job perf score int jobPerfScore = 0; for (AppResult job : jobDefIdToJobsMap.get(jobDefPair)) { jobPerfScore += job.score; } // A job in jobscores list JsonObject jobScore = new JsonObject(); jobScore.addProperty("jobscore", jobPerfScore); jobScore.addProperty("jobdefurl", jobDefPair.getUrl()); jobScore.addProperty("jobexecurl", jobDefIdToJobsMap.get(jobDefPair).get(0).jobExecUrl); jobScores.add(jobScore); flowPerfScore += jobPerfScore; } // Execution record JsonObject dataset = new JsonObject(); dataset.addProperty("flowtime", Utils.getFlowTime(mrJobsList.get(mrJobsList.size() - 1))); dataset.addProperty("score", flowPerfScore); dataset.add("jobscores", jobScores); datasets.add(dataset); } JsonArray sortedDatasets = Utils.sortJsonArray(datasets); return ok(new Gson().toJson(sortedDatasets)); }
Example 19
Source File: ServiceGovenImpl.java From hippo with Apache License 2.0 | 4 votes |
@Override public int register(String arg0, Map<String, String> metaMap) { synchronized (ServiceGovenImpl.class) { LOGGER.info("------------正在注册------------" + arg0); EurekaInstanceConfigBean eureInstanceConfigBean = new EurekaInstanceConfigBean(); EurekaClientConfigBean eureClientConfigBean = new EurekaClientConfigBean(); String host = System.getenv("HOST"); String port = System.getenv("PORT"); if (StringUtils.isNotBlank(host)) { eureInstanceConfigBean.setIpAddress(host.trim()); } else { if (!"localhost".equals(ipAddress)) { eureInstanceConfigBean.setIpAddress(ipAddress); } else { try { eureInstanceConfigBean.setIpAddress(InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { LOGGER.error("InetAddress.getLocalHost() error", e); } } } if (StringUtils.isNotBlank(port)) { eureInstanceConfigBean.setNonSecurePort(Integer.parseInt(port.trim())); } else { if (eurekaPort != 0) { eureInstanceConfigBean.setNonSecurePort(eurekaPort); } else { eureInstanceConfigBean.setNonSecurePort(ServiceGovernUtil.getAvailablePort()); } } eureInstanceConfigBean.setAppname(arg0 == null ? "eureka" : arg0); eureInstanceConfigBean.setPreferIpAddress(preferIpAddress); eureInstanceConfigBean.setLeaseRenewalIntervalInSeconds(leaseRenewalIntervalInSeconds); eureInstanceConfigBean.setLeaseExpirationDurationInSeconds(leaseExpirationDurationInSeconds); eureInstanceConfigBean.setVirtualHostName(eureInstanceConfigBean.getAppname()); if (metaMap != null) { //check class name is exist? Map<String, String> metaMap1 = getMetaMap(); for (String key : metaMap.keySet()) { if (metaMap1.get(key) != null && !metaMap1.get(key).equals(arg0)) { discoveryShutdown(); throw new HippoServiceException("服务注册异常,原因:[" + key + "]已被注册"); } } eureInstanceConfigBean.setMetadataMap(metaMap); } eureClientConfigBean.setRegisterWithEureka(registerWithEureka); eureClientConfigBean.setPreferSameZoneEureka(preferSameZoneEureka); Map<String, String> zones = new HashMap<>(); Map<String, String> serviceUrls = new HashMap<>(); zones.put(region, zone); serviceUrls.put(zone, serviceUrl); eureClientConfigBean.setAvailabilityZones(zones); eureClientConfigBean.setServiceUrl(serviceUrls); registerClient = new DiscoveryClient( initializeRegiestApplicationInfoManager(eureInstanceConfigBean), eureClientConfigBean); registerClient.getApplicationInfoManager().setInstanceStatus(InstanceStatus.UP); int nonSecurePort = eureInstanceConfigBean.getNonSecurePort(); LOGGER.info(arg0 + "------------注册成功------------port:" + nonSecurePort); return nonSecurePort; } }
Example 20
Source File: AbstractSourcedListFacet.java From pcgen with GNU Lesser General Public License v2.1 | 3 votes |
/** * Removes all objects (and all sources for those objects) from the list of * objects stored in this AbstractSourcedListFacet for the resource * represented by the given PCGenIdentifier * * This method is value-semantic in that ownership of the returned Map is * transferred to the class calling this method. Since this is a remove all * function, modification of the returned Map will not modify this * AbstractSourcedListFacet and modification of this * AbstractSourcedListFacet will not modify the returned Map. Modifications * to the returned Map will also not modify any future or previous objects * returned by this (or other) methods on AbstractSourcedListFacet. If you * wish to modify the information stored in this AbstractSourcedListFacet, * you must use the add*() and remove*() methods of * AbstractSourcedListFacet. * * @param id * The PCGenIdentifier representing the resource from which all * items should be removed * @return A non-null Set of objects removed from the list of objects stored * in this AbstractSourcedListFacet for the resource represented by * the given PCGenIdentifier */ public Map<T, Set<Object>> removeAll(IDT id) { Map<T, Set<Object>> componentMap = getCachedMap(id); if (componentMap == null) { return Collections.emptyMap(); } removeCache(id); for (T obj : componentMap.keySet()) { fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED); } return componentMap; }