Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

In this page you can find the example usage for java.util HashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:es.pode.soporte.auditoria.registrar.Registrar.java

private static void hashMap2Traza(HashMap tabla) {

    for (Iterator it = tabla.keySet().iterator(); it.hasNext();) {
        String s = (String) it.next();
        String s1 = (String) tabla.get(s);
        log.debug("Valores Hash: " + s + " " + s1);
    }/* w  ww .  ja  v  a  2s .co  m*/
}

From source file:info.mtgdb.api.Db.java

/**
 * //  ww w . ja va2  s  . c  o  m
 * @param filters HashMap<String, String> containing a mapping of keys to values.  For example colors and black.
 * @return ArrayList
 */
public static ArrayList<Card> filterCards(HashMap<String, String> filters) {
    StringBuilder sb = new StringBuilder();
    sb.append(API_URL + "/cards/?");
    for (String key : filters.keySet()) {
        String value = filters.get(key);
        sb.append(key + "=" + value + "&");
    }
    if (filters.size() > 0)
        sb.deleteCharAt(sb.length() - 1);
    return getCardsFromUrl(sb.toString());
}

From source file:com.nubits.nubot.trading.TradeUtils.java

/**
 *
 * @param args/* w  ww.j av  a2 s. co m*/
 * @param encoding
 * @return
 */
public static String buildQueryString(HashMap<String, String> args, String encoding) {
    String result = new String();
    for (String hashkey : args.keySet()) {
        if (result.length() > 0) {
            result += '&';
        }
        try {
            result += URLEncoder.encode(hashkey, encoding) + "="
                    + URLEncoder.encode(args.get(hashkey), encoding);
        } catch (Exception ex) {
            LOG.severe(ex.toString());
        }
    }
    return result;
}

From source file:com.ibm.util.merge.CompareArchives.java

/**
 * @param zip1/*  www  .  j av a2 s .  co m*/
 * @param files1
 * @param zip2
 * @param files2
 * @throws IOException
 */
private static final void assertMembersEqual(ZipFile zip1, HashMap<String, ZipEntry> files1, ZipFile zip2,
        HashMap<String, ZipEntry> files2) throws IOException {
    if (files1.size() != files2.size()) {
        fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found "
                + Integer.toString(files2.size()));
    }

    for (String key : files1.keySet()) {
        if (!files2.containsKey(key)) {
            fail("Expected file not in target " + key);
        }
        String file1 = IOUtils.toString(zip1.getInputStream(files1.get(key)));
        String file2 = IOUtils.toString(zip2.getInputStream(files2.get(key)));
        assertEquals(file1, file2);
    }
}

From source file:fr.mixit.android.utils.NetworkUtils.java

static String buildParams(HashMap<String, String> args) {
    if (args != null && !args.isEmpty()) {
        final StringBuilder params = new StringBuilder();
        final Set<String> keys = args.keySet();
        for (final Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
            final String key = iterator.next();
            final String value = args.get(key);

            params.append(key);// w  ww .j a v  a  2 s  .co m
            params.append(EQUAL);
            params.append(value);
            if (iterator.hasNext()) {
                params.append(AND);
            }
        }

        return params.toString();
    }
    return null;
}

From source file:fredboat.audio.MusicPersistenceHandler.java

public static void handlePreShutdown(int code) {
    File dir = new File("music_persistence");
    if (!dir.exists()) {
        dir.mkdir();/*  ww  w  .  j av a 2  s  .co  m*/
    }
    HashMap<String, GuildPlayer> reg = PlayerRegistry.getRegistry();

    boolean isUpdate = code == ExitCodes.EXIT_CODE_UPDATE;
    boolean isRestart = code == ExitCodes.EXIT_CODE_RESTART;

    for (String gId : reg.keySet()) {
        try {
            GuildPlayer player = reg.get(gId);

            if (!player.isPlaying()) {
                continue;//Nothing to see here
            }

            String msg;

            if (isUpdate) {
                msg = I18n.get(player.getGuild()).getString("shutdownUpdating");
            } else if (isRestart) {
                msg = I18n.get(player.getGuild()).getString("shutdownRestarting");
            } else {
                msg = I18n.get(player.getGuild()).getString("shutdownIndef");
            }

            player.getActiveTextChannel().sendMessage(msg).queue();

            JSONObject data = new JSONObject();
            data.put("vc", player.getUserCurrentVoiceChannel(player.getGuild().getSelfMember()).getId());
            data.put("tc", player.getActiveTextChannel().getId());
            data.put("isPaused", player.isPaused());
            data.put("volume", Float.toString(player.getVolume()));
            data.put("repeatMode", player.getRepeatMode());
            data.put("shuffle", player.isShuffle());

            if (player.getPlayingTrack() != null) {
                data.put("position", player.getPlayingTrack().getEffectivePosition());
            }

            ArrayList<JSONObject> identifiers = new ArrayList<>();

            for (AudioTrackContext atc : player.getRemainingTracks()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                AbstractPlayer.getPlayerManager().encodeTrack(new MessageOutput(baos), atc.getTrack());

                JSONObject ident = new JSONObject()
                        .put("message", Base64.encodeBase64String(baos.toByteArray()))
                        .put("user", atc.getMember().getUser().getId());

                if (atc instanceof SplitAudioTrackContext) {
                    JSONObject split = new JSONObject();
                    SplitAudioTrackContext c = (SplitAudioTrackContext) atc;
                    split.put("title", c.getEffectiveTitle()).put("startPos", c.getStartPosition())
                            .put("endPos", c.getStartPosition() + c.getEffectiveDuration());

                    ident.put("split", split);
                }

                identifiers.add(ident);
            }

            data.put("sources", identifiers);

            try {
                FileUtils.writeStringToFile(new File(dir, gId), data.toString(), Charset.forName("UTF-8"));
            } catch (IOException ex) {
                player.getActiveTextChannel()
                        .sendMessage(MessageFormat.format(
                                I18n.get(player.getGuild()).getString("shutdownPersistenceFail"),
                                ex.getMessage()))
                        .queue();
            }
        } catch (Exception ex) {
            log.error("Error when saving persistence file", ex);
        }
    }
}

From source file:com.nuance.expertassistant.HTTPConnection.java

public static String sendPost(String postURL, HashMap<String, String> paramMap) throws Exception {

    String url = postURL;/*from   www  .  j  a  v a  2s .  c o m*/

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    post.setHeader("User-Agent", USER_AGENT);

    if (paramMap != null) {
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        System.out.println(" Printing Parameters ");
        for (String key : paramMap.keySet()) {
            System.out.println(key + " :: " + paramMap.get(key));

            urlParameters.add(new BasicNameValuePair(key, paramMap.get(key)));

        }

        post.setEntity(new UrlEncodedFormEntity(urlParameters));
    }
    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuilder builder = new StringBuilder();
    for (String line = null; (line = rd.readLine()) != null;) {
        builder.append(line).append("\n");
    }
    /*
     System.out.print("JSON TEXT : " + builder.toString());
             
     String jsonText = builder.toString();
             
         jsonText = "{\"response\":" + jsonText + "}";
            
                     
             JSONObject object = new JSONObject(jsonText); */

    System.out.println(" The response code is :" + response.getStatusLine().getStatusCode());

    System.out.println(" The string returned is :" + builder.toString());

    return builder.toString();

}

From source file:DecorateMutationsSNP.java

/**
 * The procedure updates the SNPs of all populations that are directly connected to the ancestral population in input.
 * There can be at most two populations directly connected to an ancestral one. The procedure updates their SNPs based on the SNPs of the ancestral population that are transmitted 
 * @param pop_up instance of the class PopulationARG that represents the ARG of a single population (in this case an ancestral population)
 * @see PopulationARG/*from  w w w .jav  a 2s.  c  o  m*/
 */
public static void updateMutationsForTheBottomPop(PopulationARG pop_up) {

    if (pop_up.getKind() == 1 || pop_up.getKind() == 2) {

        //Add all mutations to the mutation set
        Iterator<Integer> it_map = pop_up.getMaps_leaves_roots().keySet().iterator();
        //System.out.println("**** UPDATING MUTATIONS FROM POPULATION  "+pop_up.getId_pop()+" ****");

        while (it_map.hasNext()) {
            Integer key_pop = it_map.next();
            PopulationARG pop_buttom = GenerateAdmixturePopulations.getPopulations().get(key_pop);
            //System.out.println("------- Mapping with Population "+key_pop+" --------- \n");
            HashMap<Integer, Integer> map_nodes = pop_up.getMaps_leaves_roots().get(key_pop);
            Iterator<Integer> it_mapping_nodes = map_nodes.keySet().iterator();
            while (it_mapping_nodes.hasNext()) {
                Integer node_buttom = it_mapping_nodes.next();
                Integer node_up = map_nodes.get(node_buttom);
                //System.out.println("node_up - node_buttom\n");
                //System.out.println(node_up+" - "+node_buttom+"\n");
                TreeSet<Integer> leaves_from_node_buttom = computeLeaves(node_buttom, pop_buttom);

                //for each mutation in node_up
                TreeSet<Double> muts = pop_up.getNodeSet().get(node_up).getMutation_set();
                Iterator<Double> it_muts = muts.iterator();

                while (it_muts.hasNext()) {
                    //Prendo la mutazione
                    Double mut_id = it_muts.next();
                    Mutation mut_up = pop_up.getMutationSet().get(mut_id);
                    Mutation mut = new Mutation();
                    mut.setPositionID(mut_up.getPositionID());
                    mut.setSegment(mut_up.getSegment());
                    mut.setLeaves(leaves_from_node_buttom);
                    mut.setIDfather(mut_up.getIDfather());
                    mut.setIDson(mut_up.getIDson());
                    mut.setID_original_pop(mut_up.getID_original_pop());

                    pop_buttom.getSNPpositionsList().add(mut.getPositionID());
                    pop_buttom.getMutationSet().put(mut.getPositionID(), mut);

                    //For each leaf (in the treeset) that has the mutation mut, add mut to the leaf 
                    TreeSet<Integer> leaves = mut.getLeaves();
                    Iterator<Integer> it_leaves = leaves.iterator();

                    while (it_leaves.hasNext()) {
                        int l = it_leaves.next();
                        pop_buttom.getNodeSet().get(l).getMutation_set().add(mut.getPositionID());
                    }
                }
            }
            //System.out.println("------------------------ End mapping ------------------------------- \n");
        }
    }
}

From source file:net.dv8tion.jda.utils.DebugUtil.java

public static JSONObject fromJDA(JDA iJDA, boolean includeUsers, boolean includeGuilds,
        boolean includeGuildUsers, boolean includeChannels, boolean includePrivateChannels) {
    JDAImpl jda = (JDAImpl) iJDA;/*from  w ww  .jav a2s.co  m*/
    JSONObject obj = new JSONObject();
    obj.put("self_info", fromUser(jda.getSelfInfo()))
            .put("proxy",
                    jda.getGlobalProxy() == null ? JSONObject.NULL
                            : new JSONObject().put("host", jda.getGlobalProxy().getHostName()).put("port",
                                    jda.getGlobalProxy().getPort()))
            .put("response_total", jda.getResponseTotal()).put("audio_enabled", jda.isAudioEnabled())
            .put("auto_reconnect", jda.isAutoReconnect());

    JSONArray array = new JSONArray();
    for (Object listener : jda.getRegisteredListeners())
        array.put(listener.getClass().getCanonicalName());
    obj.put("event_listeners", array);

    try {
        Field f = EntityBuilder.class.getDeclaredField("cachedJdaGuildJsons");
        f.setAccessible(true);
        HashMap<String, JSONObject> cachedJsons = ((HashMap<JDA, HashMap<String, JSONObject>>) f.get(null))
                .get(jda);

        array = new JSONArray();
        for (String guildId : cachedJsons.keySet())
            array.put(guildId);
        obj.put("second_pass_json_guild_ids", array);

        f = EntityBuilder.class.getDeclaredField("cachedJdaGuildCallbacks");
        f.setAccessible(true);
        HashMap<String, Consumer<Guild>> cachedCallbacks = ((HashMap<JDA, HashMap<String, Consumer<Guild>>>) f
                .get(null)).get(jda);

        array = new JSONArray();
        for (String guildId : cachedCallbacks.keySet())
            array.put(guildId);
        obj.put("second_pass_callback_guild_ids", array);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    if (includeGuilds) {
        array = new JSONArray();
        for (Guild guild : jda.getGuilds())
            array.put(fromGuild(guild, includeGuildUsers, includeChannels, true, true));
        obj.put("guilds", array);
    }

    if (includePrivateChannels) {
        array = new JSONArray();
        for (PrivateChannel chan : jda.getPrivateChannels())
            array.put(fromPrivateChannel(chan, false));
        obj.put("private_channels", array);

        array = new JSONArray();
        for (Map.Entry<String, String> entry : jda.getOffline_pms().entrySet()) {
            array.put(new JSONObject().put("id", entry.getValue()).put("user_id", entry.getKey()));
        }
        obj.put("offline_private_channels", array);
    }

    if (includeUsers) {
        array = new JSONArray();
        for (User user : jda.getUsers())
            array.put(fromUser(user));
        obj.put("users", array);
    }

    return obj;
}

From source file:net.mutil.util.HttpUtil.java

public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap)
        throws ClientProtocolException, IOException {
    String strResult = "";
    URL url = new URL(HttpUtil.getPCURL() + strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    StringBuilder entitySb = new StringBuilder("");

    Object[] entityKeys = entityMap.keySet().toArray();
    for (int i = 0; i < entityKeys.length; i++) {
        String key = (String) entityKeys[i];
        if (i == 0) {
            entitySb.append(key + "=" + entityMap.get(key));
        } else {/*  w ww  . j a va 2 s. com*/
            entitySb.append("&" + key + "=" + entityMap.get(key));
        }
    }
    byte[] entity = entitySb.toString().getBytes("UTF-8");
    System.out.println(url.toString() + entitySb.toString());
    conn.setConnectTimeout(5000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
    conn.getOutputStream().write(entity);
    if (conn.getResponseCode() == 200) {
        InputStream inputstream = conn.getInputStream();
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = inputstream.read(b)) != -1;) {
            buffer.append(new String(b, 0, n));
        }
        strResult = buffer.toString();
    }
    return strResult;
}