Java Code Examples for java.util.Map.keySet()

The following are Jave code examples for showing how to use keySet() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: KBUnitTest   File: ShadowResources.java   View Source Code Vote up 6 votes
/**
 * 获取integer-array "数组名-items"表
 *
 * @return
 */
protected Map<String, List<Integer>> getResourceIntArrayMap() {
    Map<String, List<String>>  arrayMap    = getResourceArrayMap("integer-array");
    Map<String, List<Integer>> intArrayMap = new HashMap<>();

    Set<String> keys = arrayMap.keySet();

    for (String key : keys) {
        List<Integer> integerList = new ArrayList<>();
        List<String>  stringList  = arrayMap.get(key);

        for (String item : stringList) {
            integerList.add(Integer.valueOf(item));
        }

        intArrayMap.put(key, integerList);
    }
    return intArrayMap;
}
 
Example 2
Project: fcrepo3-security-jaas   File: DrupalMultisiteAuthModuleTest.java   View Source Code Vote up 6 votes
@Test
@SuppressWarnings({
    "rawtypes", "unchecked"
})
public void testFindUserAuthenticatedUser() throws IOException, DocumentException {
    Map<String, String> users = new HashMap<String, String>();
    users.put("alpha", "first");
    users.put("bravo", "second");
    users.put("charlie", "third");

    for (String key : users.keySet()) {
        mockInstance = new DrupalMultisiteAuthModuleMock();
        Set<String> roles = findRoles(key, users.get(key));
        assertTrue(roles.contains("authenticated user"));
    }
}
 
Example 3
Project: javaide   File: AvdManager.java   View Source Code Vote up 6 votes
/**
 * Writes a .ini file from a set of properties, using UTF-8 encoding.
 * The keys are sorted.
 * The file should be read back later by {@link #parseIniFile(IAbstractFile, ILogger)}.
 *
 * @param iniFile The file to generate.
 * @param values The properties to place in the ini file.
 * @param addEncoding When true, add a property {@link #AVD_INI_ENCODING} indicating the
 *                    encoding used to write the file.
 * @throws IOException if {@link FileWriter} fails to open, write or close the file.
 */
private static void writeIniFile(File iniFile, Map<String, String> values, boolean addEncoding)
        throws IOException {

    Charset charset = Charsets.ISO_8859_1;
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(iniFile), charset);

    if (addEncoding) {
        // Write down the charset used in case we want to use it later.
        writer.write(String.format("%1$s=%2$s\n", AVD_INI_ENCODING, charset.name()));
    }

    ArrayList<String> keys = new ArrayList<String>(values.keySet());
    Collections.sort(keys);

    for (String key : keys) {
        String value = values.get(key);
        writer.write(String.format("%1$s=%2$s\n", key, value));
    }
    writer.close();
}
 
Example 4
Project: elasticsearch-queryexpansion-plugin   File: RocchioIT.java   View Source Code Vote up 6 votes
@Test
@SuppressWarnings("unchecked")
public void testPluginIsLoaded() throws Exception {

	Response response = client.performRequest("GET", "/_nodes/plugins");

	Map<String, Object> nodes = (Map<String, Object>) entityAsMap(response).get("nodes");
	for (String nodeName : nodes.keySet()) {
		boolean pluginFound = false;
		Map<String, Object> node = (Map<String, Object>) nodes.get(nodeName);
		List<Map<String, Object>> plugins = (List<Map<String, Object>>) node.get("plugins");
		for (Map<String, Object> plugin : plugins) {
			String pluginName = (String) plugin.get("name");
			if (pluginName.equals("rocchio")) {
				pluginFound = true;
				break;
			}
		}
		assertThat(pluginFound, is(true));
	}
}
 
Example 5
Project: Server-Quickstart-Vert.x   File: NetworkingHelper.java   View Source Code Vote up 6 votes
static String createRequestAddress(String targetAddress, String uri, Map<String, Object> params) {
	/*
	 * GET request with parameter
	 * URI?key=value&key=value
	 */
	
	StringBuilder requestAddress = new StringBuilder();
	requestAddress.append(validateUri(targetAddress, uri)).append("?");
	for(String key : params.keySet()) {
		String value = (String) params.get(key);
		try {
			requestAddress.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	String requestAddressStr = requestAddress.toString();
	requestAddressStr = requestAddressStr.substring(0, requestAddressStr.length() - 1);
	return requestAddressStr;
}
 
Example 6
Project: lams   File: BasicLTIUtil.java   View Source Code Vote up 5 votes
/**
 * Any properties which are not well known (i.e. in
 * {@link BasicLTIConstants#validPropertyNames}) will be mapped to custom
 * properties per the specified semantics.
 *
 * @param rawProperties A set of properties that will be cleaned.
 * @param blackList An array of {@link String}s which are considered unsafe
 * to be included in launch data. Any matches will be removed from the
 * return.
 * @return A cleansed version of rawProperties.
 */
public static Map<String, String> cleanupProperties(
        final Map<String, String> rawProperties, final String[] blackList) {
    final Map<String, String> newProp = new HashMap<String, String>(
            rawProperties.size()); // roughly the same size
    for (String okey : rawProperties.keySet()) {
        final String key = okey.trim();
        if (blackList != null) {
            boolean blackListed = false;
            for (String blackKey : blackList) {
                if (blackKey.equals(key)) {
                    blackListed = true;
                    break;
                }
            }
            if (blackListed) {
                continue;
            }
        }
        final String value = rawProperties.get(key);
        if (value == null || "".equals(value)) {
            // remove null or empty values
            continue;
        }
        if (isSpecifiedPropertyName(key)) {
            // a well known property name
            newProp.put(key, value);
        } else {
            // convert to a custom property name
            newProp.put(adaptToCustomPropertyName(key), value);
        }
    }
    return newProp;
}
 
Example 7
Project: recipe-interpretation   File: ActionDiagram.java   View Source Code Vote up 5 votes
public int numDestinations() {
	int cnt = 0;
	for (String output : output_components_to_destinations_.keySet()) {
		Map<Integer, Set<Triple<ActionNode, Argument, String>>> dests = output_components_to_destinations_.get(output);
		for (Integer dest_id : dests.keySet()) {
			cnt += dests.get(dest_id).size();
		}
	}
	return cnt;
}
 
Example 8
Project: hashsdn-controller   File: JMXGenerator.java   View Source Code Vote up 5 votes
private static Map<String, String> extractNamespaceMapping(
        final Map<String, String> additionalCfg) {
    final Map<String, String> namespaceToPackage = Maps.newHashMap();
    for (final String key : additionalCfg.keySet()) {
        if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
            final String mapping = additionalCfg.get(key);
            final NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
            namespaceToPackage.put(mappingResolved.namespace,
                    mappingResolved.packageName);
        }
    }
    return namespaceToPackage;
}
 
Example 9
Project: asgdrivestrength   File: CellDelayAggregator.java   View Source Code Vote up 5 votes
private Map<String, DelayParameterTriple> extractDelayParameters(
           Map<String, Map<String, DelayLine>> delayLines, Map<String, Integer> stageCounts) {

    Map<String, DelayParameterTriple> delayParameterTriplesPerPin = new HashMap<>();

    for (String pinName : delayLines.keySet()) {
        Map<String, DelayLine> delayLinesForPin = this.filterOutDeviatingSizeDelayLines(delayLines.get(pinName));
        int stageCountForPin = stageCounts.get(pinName);
        delayParameterTriplesPerPin.put(pinName, new DelayParametersExtractor(delayLinesForPin, stageCountForPin).run());
    }

    return delayParameterTriplesPerPin;
}
 
Example 10
Project: convertigo-engine   File: MobileBuilder.java   View Source Code Vote up 5 votes
private void writeAppPackageJson(ApplicationComponent app) throws EngineException {
	try {
		if (app != null) {
			Map<String, String> pkg_dependencies = new HashMap<>();
			
			List<PageComponent> pages = forceEnable ? 
											app.getPageComponentList() :
													getEnabledPages(app);
			for (PageComponent page : pages) {
				List<Contributor> contributors = page.getContributors();
				for (Contributor contributor : contributors) {
					pkg_dependencies.putAll(contributor.getPackageDependencies());
				}
			}
			
			File appPkgJsonTpl = new File(ionicTplDir, "package.json");
			String mContent = FileUtils.readFileToString(appPkgJsonTpl, "UTF-8");
			mContent = mContent.replaceAll("../DisplayObjects","../../DisplayObjects");
			
			JSONObject jsonPackage = new JSONObject(mContent);
			JSONObject jsonDependencies = jsonPackage.getJSONObject("dependencies");
			for (String pkg : pkg_dependencies.keySet()) {
				jsonDependencies.put(pkg, pkg_dependencies.get(pkg));
				if (!existPackage(pkg)) {
					setNeedPkgUpdate(true);
				}
			}
			
			File appPkgJson = new File(ionicWorkDir, "package.json");
			writeFile(appPkgJson, jsonPackage.toString(2), "UTF-8");
			
			if (initDone) {
				Engine.logEngine.debug("(MobileBuilder) Ionic package json file generated");
			}
		}
	} catch (Exception e) {
		throw new EngineException("Unable to write ionic package json file",e);
	}
}
 
Example 11
Project: hashsdn-controller   File: ServiceRegistryWrapper.java   View Source Code Vote up 5 votes
public ObjectName getByServiceAndRefName(final String namespace, final String serviceType, final String refName) {
    Map<String, Map<String, Map<String, String>>> mappedServices = getMappedServices();
    Map<String, Map<String, String>> serviceNameToRefNameToInstance = mappedServices.get(namespace);

    Preconditions.checkArgument(serviceNameToRefNameToInstance != null,
            "No service mapped to %s:%s:%s. Wrong namespace, available namespaces: %s", namespace, serviceType,
            refName, mappedServices.keySet());

    Map<String, String> refNameToInstance = serviceNameToRefNameToInstance.get(serviceType);
    Preconditions.checkArgument(refNameToInstance != null,
            "No service mapped to %s:%s:%s. Wrong service type, available service types: %s", namespace,
            serviceType, refName, serviceNameToRefNameToInstance.keySet());

    String instanceId = refNameToInstance.get(refName);
    Preconditions.checkArgument(instanceId != null,
            "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
            refName, refNameToInstance.keySet());

    Services.ServiceInstance serviceInstance = Services.ServiceInstance.fromString(instanceId);
    Preconditions.checkArgument(serviceInstance != null,
            "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
            refName, refNameToInstance.keySet());

    String serviceName = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceType);
    try {
        /*
         * Remove transaction name as this is redundant - will be stripped in
         * DynamicWritableWrapper, and makes it hard to compare with service references
         * got from MXBean attributes
         */
        return ObjectNameUtil
                .withoutTransactionName(configServiceRefRegistry.getServiceReference(serviceName, refName));
    } catch (final InstanceNotFoundException e) {
        throw new IllegalArgumentException("No serviceInstance mapped to " + refName + " under service name "
                + serviceType + " , " + refNameToInstance.keySet(), e);

    }
}
 
Example 12
Project: GitHub   File: SaveHandler.java   View Source Code Vote up 5 votes
/**
 * Update the foreign keys in the associated model's table.
 * 
 * @param baseObj
 *            Current model that is persisted.
 */
private void updateAssociatedTableWithFK(DataSupport baseObj) {
	Map<String, Set<Long>> associatedModelMap = baseObj.getAssociatedModelsMapWithFK();
	ContentValues values = new ContentValues();
	for (String associatedTableName : associatedModelMap.keySet()) {
		values.clear();
		String fkName = getForeignKeyColumnName(baseObj.getTableName());
		values.put(fkName, baseObj.getBaseObjId());
		Set<Long> ids = associatedModelMap.get(associatedTableName);
		if (ids != null && !ids.isEmpty()) {
			mDatabase.update(associatedTableName, values, getWhereOfIdsWithOr(ids), null);
		}
	}
}
 
Example 13
Project: empiria.player   File: JsStyleSocketUserExtension.java   View Source Code Vote up 5 votes
private JavaScriptObject getStyle(com.google.gwt.dom.client.Element element) {

        Element xmlElement = XMLParser.createDocument().createElement(element.getNodeName().toLowerCase());
        Map<String, String> styles = styleSocket.getStyles(xmlElement);
        JavaScriptObject stylesJsArray = JavaScriptObject.createObject();

        for (String currKey : styles.keySet()) {
            JSArrayUtils.fillArray(stylesJsArray, currKey, styles.get(currKey));
        }

        return stylesJsArray;
    }
 
Example 14
Project: updatebot   File: StatusInfo.java   View Source Code Vote up 5 votes
/**
 * Lets return the current status by combining the old and new status maps to handle new maps
 * not including links to old pending issues or pull requests that are now closed
 */
public static Map<String, StatusInfo> changedStatuses(Configuration configuration, Map<String, StatusInfo> oldMap, Map<String, StatusInfo> newMap) {
    Set<String> allKeys = new LinkedHashSet(oldMap.keySet());
    allKeys.addAll(newMap.keySet());
    Map<String, StatusInfo> answer = new LinkedHashMap<>();
    for (String key : allKeys) {
        StatusInfo status = changedStatus(configuration, oldMap.get(key), newMap.get(key));
        if (status != null) {
            answer.put(key, status);
        }
    }
    return answer;
}
 
Example 15
Project: SparkSeq   File: AlleleBiasedDownsamplingUtils.java   View Source Code Vote up 5 votes
/**
 * Computes reads to remove based on an allele biased down-sampling
 *
 * @param alleleReadMap             original list of records per allele
 * @param downsamplingFraction      the fraction of total reads to remove per allele
 * @return list of reads TO REMOVE from allele biased down-sampling
 */
public static <A extends Allele> List<GATKSAMRecord> selectAlleleBiasedReads(final Map<A, List<GATKSAMRecord>> alleleReadMap, final double downsamplingFraction) {
    int totalReads = 0;
    for ( final List<GATKSAMRecord> reads : alleleReadMap.values() )
        totalReads += reads.size();

    int numReadsToRemove = (int)(totalReads * downsamplingFraction);

    // make a listing of allele counts
    final List<Allele> alleles = new ArrayList<Allele>(alleleReadMap.keySet());
    alleles.remove(Allele.NO_CALL);    // ignore the no-call bin
    final int numAlleles = alleles.size();

    final int[] alleleCounts = new int[numAlleles];
    for ( int i = 0; i < numAlleles; i++ )
        alleleCounts[i] = alleleReadMap.get(alleles.get(i)).size();

    // do smart down-sampling
    final int[] targetAlleleCounts = runSmartDownsampling(alleleCounts, numReadsToRemove);

    final List<GATKSAMRecord> readsToRemove = new ArrayList<GATKSAMRecord>(numReadsToRemove);
    for ( int i = 0; i < numAlleles; i++ ) {
        if ( alleleCounts[i] > targetAlleleCounts[i] ) {
            readsToRemove.addAll(downsampleElements(alleleReadMap.get(alleles.get(i)), alleleCounts[i] - targetAlleleCounts[i]));
        }
    }

    return readsToRemove;
}
 
Example 16
Project: smart-testing   File: ConfigurationReader.java   View Source Code Vote up 5 votes
private static void overwriteInnerProperties(Map<String, Object> effective, Map<String, Object> inner) {
    for (String key: inner.keySet()) {
        if (isNonTrivialPropertyContainedInMap(key, inner, effective)) {
            effective.put(key, inner.get(key));
        } else {
            final Map<String, Object> effectiveValue = ((Map<String, Object>) effective.get(key));
            final Map<String, Object> innerValue = ((Map<String, Object>) inner.get(key));
            overwriteInnerProperties(effectiveValue, innerValue);
            effective.put(key, effectiveValue);
        }
    }
}
 
Example 17
Project: buddybox   File: Library.java   View Source Code Vote up 5 votes
private static void createNewSongs(Map<Hash, File> files) {
    for (Hash hash : files.keySet()) {
        if (hashMp3(hash))
            updateSongPath(hash, files.get(hash).getPath());
        else
            createNewSong(hash, files.get(hash));
    }
}
 
Example 18
Project: crnk-framework   File: ProjectToTaskRepository.java   View Source Code Vote up 5 votes
@Override
public Task findOneTarget(Long sourceId, String fieldName, QueryParams queryParams) {
	Map<Relation<Project>, Integer> repo = getRepo();
	for (Relation<Project> relation : repo.keySet()) {
		if (relation.getSource().getId().equals(sourceId) &&
				relation.getFieldName().equals(fieldName)) {
			Task task = new Task();
			task.setId((Long) relation.getTargetId());
			return task;
		}
	}
	return null;
}
 
Example 19
Project: dhbw-timetable-android   File: AlarmSupervisor.java   View Source Code Vote up 4 votes
public void rescheduleAllAlarms(Context context) {
    if (rescheduling) {
        Log.i("ALARM", "Request denied. Already rescheduling...");
        return;
    }
    rescheduling = true;
    Log.i("ALARM", "Rescheduling all alarms...");
    cancelAllAlarms(context);

    SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    if (sharedPref.getBoolean("alarmOnFirstEvent", false)) {
        Map<TimelessDate, ArrayList<BackportAppointment>> globals = TimetableManager.getInstance().getGlobals();
        ArrayList<BackportAppointment> appointmentsOfWeek;
        TimelessDate tempDay;
        BackportAppointment firstAppointment;
        for (TimelessDate week : globals.keySet()) {
            appointmentsOfWeek = globals.get(week);
            for (int day = 0; day < 5; day++) {
                tempDay = (TimelessDate) week.clone();
                DateUtilities.Backport.AddDays(tempDay, day);
                firstAppointment = DateUtilities.Backport.GetFirstAppointmentOfDay(appointmentsOfWeek, tempDay);
                // Only if there are appointments
                if (firstAppointment != null) {
                    // apply shifting
                    int shifter = 0;
                    shifter += sharedPref.getInt("alarmFirstShiftHour", 0) * 60 * 60 * 1000;
                    shifter += sharedPref.getInt("alarmFirstShiftMinute", 0) * 60 * 1000;

                    GregorianCalendar afterShift = (GregorianCalendar) firstAppointment.getStartDate().clone();
                    afterShift.setTimeInMillis(afterShift.getTimeInMillis() - shifter);
                    // If is not over
                    GregorianCalendar today = (GregorianCalendar) Calendar.getInstance();
                    if (today.getTimeInMillis() < afterShift.getTimeInMillis()) {
                        addAlarm(context, afterShift);
                    }
                }
            }
        }
        Log.i("ALARM", "Rescheduled " + getAlarmIds(context).size() + " alarms");
    } else {
        Log.i("ALARM", "Not needed. Alarm not active.");
    }
    rescheduling = false;
}
 
Example 20
Project: properties-resolver   File: PropertiesResolverService.java   View Source Code Vote up 3 votes
/**
 * Evaluates properties map and resolve its values.
 * <p>
 * It resolves map values by the following syntax:
 * <p>
 * {@code key1 -> hello }
 * <p>
 * {@code key2 -> ${key1} world}
 * <p>
 * will produce a new map:
 * <p>
 * {@code key1 -> hello }
 * <p>
 * {@code key2 -> hello world }
 *
 * @param properties properties map to resolve.
 *
 * @return new {@link Map} instance with resolved properties.
 *
 * @throws RecursionPropertyEvaluationException in case of recursion key evaluation. A simple example:
 *                                              {@code key1 -> ${key1} }
 * @throws UnknownPropertyKeyException          in case of unknown property key for evaluation.
 */
public static Map<String, String> resolve (Map<String, String> properties)
        throws UnknownPropertyKeyException, RecursionPropertyEvaluationException {
    Map<String, String> result = new HashMap<>(properties.size(), 1.F);
    for (String key : properties.keySet()) {
        if (result.containsKey(key)) {
            continue;
        }

        String value = evaluate(key, properties, result);
        result.put(key, value);
    }
    return result;
}