Example usage for java.util HashMap entrySet

List of usage examples for java.util HashMap entrySet

Introduction

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

Prototype

Set entrySet

To view the source code for java.util HashMap entrySet.

Click Source Link

Document

Holds cached entrySet().

Usage

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {//from   w w  w. ja v a  2  s.co m

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:net.opentracker.android.OTSend.java

/**
 * Sends the key value pairs to Opentracker's logging/ analytics engines via
 * HTTP POST requests.//  w w  w .j  av a  2s .  c om
 * 
 * Based on sending key value pairs documentated at:
 * http://api.opentracker.net/api/inserts/insert_event.jsp
 * 
 * @param keyValuePairs
 *            the key value pairs (plain text utf-8 strings) to send to the
 *            logging service.
 * 
 * @return the response as string, null if an exception is caught
 */
protected static String send(HashMap<String, String> keyValuePairs) {
    LogWrapper.v(TAG, "send(HashMap<String, String> keyValuePairs)");

    // http://www.wikihow.com/Execute-HTTP-POST-Requests-in-Android
    // http://hc.apache.org/httpclient-3.x/tutorial.html
    HttpClient client = new DefaultHttpClient();

    // time to wait before throwing timeout exception
    client.getParams().setParameter("http.socket.timeout", new Integer(HTTP_SOCKET_TIMEOUT));

    HttpPost post = new HttpPost(DEFAULT_LOG_URL);
    post.getParams().setParameter("http.socket.timeout", new Integer(HTTP_SOCKET_TIMEOUT));

    Iterator<Entry<String, String>> it = keyValuePairs.entrySet().iterator();

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    while (it.hasNext()) {

        Map.Entry<String, String> pair = (Map.Entry<String, String>) it.next();
        pairs.add(new BasicNameValuePair(pair.getKey(), pair.getValue()));
        if (pair.getKey().equals("ots") || pair.getKey().equals("otui"))
            LogWrapper.v(TAG, pair.getKey() + " = " + pair.getValue());
        else
            LogWrapper.v(TAG, pair.getKey() + " = " + pair.getValue());

    }

    String responseText = null;
    try {

        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();

        // http://hc.apache.org/httpclient-3.x/tutorial.html
        // It is vital that the response body is always read regardless of
        // the status returned by the server.
        responseText = getResponseBody(entity);

        LogWrapper.v(TAG, "Success url:" + post.getURI());
        LogWrapper.v(TAG, "Success url:" + pairs);
        return responseText;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        LogWrapper.w(TAG, "Failed:" + e);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LogWrapper.w(TAG, "Failed:" + e);
    } catch (IOException e) {
        e.printStackTrace();
        LogWrapper.w(TAG, "Failed:" + e);
    } catch (ParseException e) {
        e.printStackTrace();
        LogWrapper.w(TAG, "Failed:" + e);
    }
    LogWrapper.e(TAG, "Got response " + responseText);
    return responseText;
}

From source file:com.yahoo.ycsb.db.couchbase2.Couchbase2Client.java

/**
 * Helper method to turn the map of values into a {@link JsonObject} for further use.
 *
 * @param values the values to transform.
 * @return the created json object.//w ww .  j a  v  a  2 s  . c  om
 */
private static JsonObject valuesToJsonObject(final HashMap<String, ByteIterator> values) {
    JsonObject result = JsonObject.create();
    for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
        result.put(entry.getKey(), entry.getValue().toString());
    }
    return result;
}

From source file:com.flipkart.fdp.migration.distcp.core.MirrorDistCPDriver.java

@SuppressWarnings("static-access")
public static DCMConfig getParams(String[] args) throws Exception {

    Options options = new Options();

    options.addOption("p", true, "properties filename from the classpath");
    options.addOption("P", true, "external properties filename");
    options.addOption("D", true, "JVM and Hadoop Configuration Override");
    options.addOption("V", true, "Custom runtime config variables");
    options.addOption("J", true, "properties as JSON String");
    options.addOption("libjars", true, "JVM and Hadoop Configuration Override");

    options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String path = null;//from   w w  w  . j a v a  2s.  c o  m
    if (cmd.hasOption('p')) {
        path = cmd.getOptionValue('p');
    } else if (cmd.hasOption('P')) {
        path = cmd.getOptionValue('P');
    }
    HashMap<String, String> varMap = new HashMap<String, String>();
    if (cmd.hasOption('V')) {
        String runtimeVars[] = cmd.getOptionValues('V');
        for (String var : runtimeVars) {
            String kv[] = var.split("=");
            varMap.put("#" + kv[0], kv[1]);
        }
    }
    if (cmd.hasOption('J')) {
        String configString = cmd.getOptionValue('J');
        Gson gson = new Gson();
        return gson.fromJson(configString, DCMConfig.class);
    }

    if (path == null || !new File(path).exists()) {
        throw new Exception("Unable to load Config File...");
    }
    String configString = MirrorUtils.getFileAsString(path);

    if (varMap.size() > 0) {

        for (Entry<String, String> kv : varMap.entrySet()) {
            System.out.println("Custom Config Replacer: " + kv.getKey() + ", with: " + kv.getValue());
            configString = configString.replace(kv.getKey(), kv.getValue());
        }
    }
    Gson gson = new Gson();
    return gson.fromJson(configString, DCMConfig.class);
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java

private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric,
        HashMap<String, String> tags) throws OpenTSDBException {

    urlString = urlString + API_METHOD;/*from www  .j  a v  a2 s.  c  o m*/
    String result = "";

    try {
        HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
        OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

        JSONObject mainObject = new JSONObject();
        mainObject.put("start", startEpoch);
        mainObject.put("end", endEpoch);

        JSONArray queryArray = new JSONArray();

        JSONObject queryParams = new JSONObject();
        queryParams.put("aggregator", "sum");
        queryParams.put("metric", metric);

        queryArray.put(queryParams);

        if (tags != null) {
            JSONObject queryTags = new JSONObject();

            Iterator<Entry<String, String>> entries = tags.entrySet().iterator();
            while (entries.hasNext()) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) entries.next();
                queryTags.put((String) entry.getKey(), (String) entry.getValue());
            }

            queryParams.put("tags", queryTags);
        }

        mainObject.put("queries", queryArray);
        String queryString = mainObject.toString();

        wr.write(queryString);
        wr.flush();
        wr.close();

        result = TimeSeriesUtility.readHttpResponse(httpConnection);

    } catch (IOException e) {
        throw new OpenTSDBException("Unable to connect to server", e);
    } catch (JSONException e) {
        throw new OpenTSDBException("Error on request data", e);
    }

    return TimeSeriesUtility.makeResponseJSONArray(result);
}

From source file:com.ibm.bi.dml.runtime.util.DataConverter.java

/**
 * NOTE: this method also ensures the specified matrix dimensions
 * /*w w w . j a  v  a2 s.  c o  m*/
 * @param map
 * @return
 */
public static MatrixBlock convertToMatrixBlock(HashMap<MatrixIndexes, Double> map, int rlen, int clen) {
    int nnz = map.size();
    boolean sparse = MatrixBlock.evalSparseFormatInMemory(rlen, clen, nnz);
    MatrixBlock mb = new MatrixBlock(rlen, clen, sparse, nnz);

    // copy map values into new block
    if (sparse) //SPARSE <- cells
    {
        //append cells to sparse target (prevent shifting)
        for (Entry<MatrixIndexes, Double> e : map.entrySet()) {
            MatrixIndexes index = e.getKey();
            double value = e.getValue();
            int rix = (int) index.getRowIndex();
            int cix = (int) index.getColumnIndex();
            if (value != 0 && rix <= rlen && cix <= clen)
                mb.appendValue(rix - 1, cix - 1, value);
        }

        //sort sparse target representation
        mb.sortSparseRows();
    } else //DENSE <- cells
    {
        //directly insert cells into dense target 
        for (Entry<MatrixIndexes, Double> e : map.entrySet()) {
            MatrixIndexes index = e.getKey();
            double value = e.getValue();
            int rix = (int) index.getRowIndex();
            int cix = (int) index.getColumnIndex();
            if (value != 0 && rix <= rlen && cix <= clen)
                mb.quickSetValue(rix - 1, cix - 1, value);
        }
    }

    return mb;
}

From source file:com.yahoo.ycsb.db.couchbase2.Couchbase2Client.java

/**
 * Helper method to turn the values into a String, used with {@link #upsertN1ql(String, HashMap)}.
 *
 * @param values the values to encode./*ww w  . j av  a 2  s .  c  om*/
 * @return the encoded string.
 */
private static String encodeN1qlFields(final HashMap<String, ByteIterator> values) {
    if (values.isEmpty()) {
        return "";
    }

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
        String raw = entry.getValue().toString();
        String escaped = raw.replace("\"", "\\\"").replace("\'", "\\\'");
        sb.append(entry.getKey()).append("=\"").append(escaped).append("\" ");
    }
    String toReturn = sb.toString();
    return toReturn.substring(0, toReturn.length() - 1);
}

From source file:de.tor.tribes.util.VillageUtils.java

public static Village[] getVillagesByTag(Tag[] pTags, Tribe pTribe, RELATION pRelation, boolean pWithBarbarians,
        Comparator pComparator) {
    if (pTags == null) {
        return new Village[0];
    }/*ww w .j  av  a2  s .  c  o  m*/
    List<Village> villages = new ArrayList<>();
    HashMap<Village, Integer> usageCount = new HashMap<>();
    for (Tag tag : pTags) {
        for (Integer id : tag.getVillageIDs()) {
            Village v = DataHolder.getSingleton().getVillagesById().get(id);
            if (pWithBarbarians || !v.getTribe().equals(Barbarians.getSingleton())) {
                if (pTribe == null || v.getTribe().getId() == pTribe.getId()) {
                    usageCount.put(v, (usageCount.get(v) == null) ? 1 : usageCount.get(v) + 1);
                    if (!villages.contains(v)) {
                        villages.add(v);
                    }
                }
            }
        }
    }
    if (pRelation.equals(RELATION.AND)) {
        //remove villages that are tagges by less tags than tagCount
        int tagAmount = pTags.length;
        for (Entry<Village, Integer> entry : usageCount.entrySet()) {
            if (entry.getValue() == null || entry.getValue() != tagAmount) {
                villages.remove(entry.getKey());
            }
        }
    }

    if (pComparator != null) {
        Collections.sort(villages, pComparator);
    }

    return villages.toArray(new Village[villages.size()]);
}

From source file:Main.java

public static Node applyXslToDocument2(Source xslt, Source doc, URIResolver resolver,
        Properties transformerProperties, HashMap<String, String> params, String transformerClassName)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException,
        NoSuchMethodException, TransformerConfigurationException, TransformerException {
    TransformerFactory transformerFactory = null;
    if (transformerClassName == null)
        transformerFactory = TransformerFactory.newInstance();
    else {/* w  w  w .j av a  2 s  .  com*/
        Class transformerClass = Class.forName(transformerClassName);
        Constructor defaultConstructor = transformerClass.getConstructor(null);
        transformerFactory = (TransformerFactory) transformerClass.newInstance();
    }

    if (resolver != null)
        transformerFactory.setURIResolver(resolver);

    Transformer transformer = transformerFactory.newTransformer(xslt);
    if (transformerFactory != null)
        transformer.setOutputProperties(transformerProperties);

    if (params != null) {
        for (Map.Entry<String, String> cursor : params.entrySet()) {
            transformer.setParameter(cursor.getKey(), cursor.getValue());
        }
    }

    DOMResult result = new DOMResult();
    transformer.transform(doc, result);

    return (result.getNode());
}

From source file:Main.java

public static String applyXslToDocument(Source xslt, Source doc, URIResolver resolver,
        Properties transformerProperties, HashMap<String, String> params, String transformerClassName)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException,
        NoSuchMethodException, TransformerConfigurationException, TransformerException {
    TransformerFactory transformerFactory = null;
    if (transformerClassName == null)
        transformerFactory = TransformerFactory.newInstance();
    else {/*w w  w  . j  a  v  a 2 s  . co  m*/
        Class transformerClass = Class.forName(transformerClassName);
        Constructor defaultConstructor = transformerClass.getConstructor(null);
        transformerFactory = (TransformerFactory) transformerClass.newInstance();
    }

    if (resolver != null)
        transformerFactory.setURIResolver(resolver);

    Transformer transformer = transformerFactory.newTransformer(xslt);
    if (transformerFactory != null)
        transformer.setOutputProperties(transformerProperties);

    if (params != null) {
        for (Map.Entry<String, String> cursor : params.entrySet()) {
            transformer.setParameter(cursor.getKey(), cursor.getValue());
        }
    }

    StringWriter strWriter = new StringWriter();
    StreamResult result = new StreamResult(strWriter);
    transformer.transform(doc, result);

    return (strWriter.toString());
}