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:org.owasp.benchmark.score.report.ScatterHome.java

private void makeDataLabels(Set<Report> toolResults, XYPlot xyplot) {
    HashMap<Point2D, String> map = makePointList(toolResults);
    for (Entry<Point2D, String> e : map.entrySet()) {
        if (e.getValue() != null) {
            Point2D p = e.getKey();
            String label = sort(e.getValue());
            XYTextAnnotation annotation = new XYTextAnnotation(label, p.getX(), p.getY());
            annotation.setTextAnchor(p.getX() < 3 ? TextAnchor.TOP_LEFT : TextAnchor.TOP_CENTER);
            annotation.setBackgroundPaint(Color.white);
            if (label.toCharArray()[0] == averageLabel) {
                annotation.setPaint(Color.magenta);
            } else {
                annotation.setPaint(Color.blue);
            }/*from w w  w  .j  ava2s .c om*/
            annotation.setFont(theme.getRegularFont());
            xyplot.addAnnotation(annotation);
        }
    }
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {/*from  w w w  . ja va 2s  . c om*/
        String data = new String();
        Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.eucalyptus.objectstorage.pipeline.handlers.ObjectStorageAuthenticationHandler.java

/**
 * This method exists to clean up a problem encountered periodically where the HTTP
 * headers are duplicated/*from   www. ja v a2s. co  m*/
 *
 * @param httpRequest
 */
private static void removeDuplicateHeaderValues(MappingHttpRequest httpRequest) {
    List<String> hdrList = null;
    HashMap<String, List<String>> fixedHeaders = new HashMap<String, List<String>>();
    boolean foundDup = false;
    for (String header : httpRequest.getHeaderNames()) {
        hdrList = httpRequest.getHeaders(header);

        //Only address the specific case where there is exactly one identical copy of the header
        if (hdrList != null && hdrList.size() == 2 && hdrList.get(0).equals(hdrList.get(1))) {
            foundDup = true;
            fixedHeaders.put(header, Lists.newArrayList(hdrList.get(0)));
        } else {
            fixedHeaders.put(header, hdrList);
        }
    }

    if (foundDup) {
        LOG.debug("Found duplicate headers in: " + httpRequest.logMessage());
        httpRequest.clearHeaders();

        for (Map.Entry<String, List<String>> e : fixedHeaders.entrySet()) {
            for (String v : e.getValue()) {
                httpRequest.addHeader(e.getKey(), v);
            }
        }
    }
}

From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java

@Override
public int insert(String table, String key, HashMap<String, ByteIterator> values) {
    HttpResponse response = null;/*  w ww .j  a  v a  2 s.com*/
    try {
        System.out.println("Inserting ....");
        JsonObject object = new JsonObject();
        for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
            object.addProperty(entry.getKey(), entry.getValue().toString());
        }
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SAPRATOR + database.toLowerCase() + CouchDBConstants.URL_SAPRATOR + table
                        + key,
                null, null);

        HttpPut put = new HttpPut(uri);

        StringEntity stringEntity = null;
        object.addProperty("_id", table + key);
        stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);
        stringEntity.setContentType("application/json");
        put.setEntity(stringEntity);

        response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return 1;
        }
        return 0;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        // CouchDBUtils.closeContent(response);
    }
}

From source file:com.marketcloud.marketcloud.Utilities.java

/**
 * Returns a list of objects that comply with the given query.
 *
 * @param baseURL endpoint of the database
 * @param token a session token that identifies the user
 * @param m HashMap containing a list of filters
 * @return a JSONArray containing a list of objects that comply with the given filter
 *//*  w  w  w. ja  va2s . c o m*/
public JSONObject list(final String baseURL, String token, final HashMap<String, Object> m)
        throws ExecutionException, InterruptedException, JSONException {

    String url = baseURL.substring(0, baseURL.length() - 1) + "?";

    //Concatenate the filters to the base URL

    int index = 0;
    int max = m.size() - 1;

    for (Map.Entry<String, Object> entry : m.entrySet()) {

        url += entry.getKey() + "=" + entry.getValue();

        if (index != max)
            url += "&";

        index++;
    }

    return new Connect(context).run("get", url, publicKey + ":" + token);
}

From source file:com.intuit.tank.httpclient3.TankHttpClient3.java

/**
 * Set all the header keys//from  ww w.  j  a  v  a 2  s.  c o  m
 * 
 * @param connection
 */
@SuppressWarnings("rawtypes")
private void setHeaders(BaseRequest request, HttpMethod method, HashMap<String, String> headerInformation) {
    try {
        Set set = headerInformation.entrySet();
        Iterator iter = set.iterator();

        while (iter.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iter.next();
            method.setRequestHeader((String) mapEntry.getKey(), (String) mapEntry.getValue());
        }
    } catch (Exception ex) {
        logger.warn(request.getLogUtil().getLogMessage("Unable to set header: " + ex.getMessage(),
                LogEventType.System));
    }
}

From source file:de.betterform.agent.web.servlet.ErrorServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    WebUtil.nonCachingResponse(response);
    //pick up the exception details
    String xpath = "unknown";
    String cause = "";
    String msg = (String) getSessionAttribute(request, "betterform.exception.message");
    if (msg != null) {
        int start = msg.indexOf("::");
        if (start > 3) {
            xpath = msg.substring(start + 2);
            msg = msg.substring(0, start);
        }/*  www . ja v  a2  s.c o m*/
        //todo: don't we need an 'else' here?
    }
    Exception ex = (Exception) getSessionAttribute(request, "betterform.exception");
    if (ex != null && ex.getCause() != null && ex.getCause().getMessage() != null) {
        cause = ex.getCause().getMessage();
    }

    //create XML structure for exception details
    Element rootNode = DOMUtil.createRootElement("error");
    DOMUtil.appendElement(rootNode, "context", request.getContextPath());
    DOMUtil.appendElement(rootNode, "url", request.getSession().getAttribute("betterform.referer").toString());
    DOMUtil.appendElement(rootNode, "xpath", xpath);
    DOMUtil.appendElement(rootNode, "message", msg);
    DOMUtil.appendElement(rootNode, "cause", cause);

    //transform is different depending on exception type
    if (ex instanceof XFormsErrorIndication) {
        Object o = ((XFormsErrorIndication) ex).getContextInfo();
        if (o instanceof HashMap) {
            HashMap<String, Object> map = (HashMap) ((XFormsErrorIndication) ex).getContextInfo();
            if (map.size() != 0) {
                Element contextinfo = rootNode.getOwnerDocument().createElement("contextInfo");
                rootNode.appendChild(contextinfo);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    DOMUtil.appendElement(rootNode, entry.getKey(), entry.getValue().toString());
                }
            }
        }
        //todo: check -> there are contextInfos containing a simple string but seems to be integrated within above error message already - skip for now
        /*
                    else{
                    }
        */
        Document hostDoc = (Document) getSessionAttribute(request, "betterform.hostDoc");
        String serializedDoc = DOMUtil.serializeToString(hostDoc);
        //reparse
        try {
            byte bytes[] = serializedDoc.getBytes("UTF-8");
            Document newDoc = PositionalXMLReader.readXML(new ByteArrayInputStream(bytes));
            DOMUtil.prettyPrintDOM(newDoc);
            //eval xpath
            Node n = XPathUtil.evaluateAsSingleNode(newDoc, xpath);
            String linenumber = (String) n.getUserData("lineNumber");
            DOMUtil.appendElement(rootNode, "lineNumber", linenumber);

            DOMUtil.prettyPrintDOM(rootNode);

            WebUtil.doTransform(getServletContext(), response, newDoc, "highlightError.xsl", rootNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        WebUtil.doTransform(getServletContext(), response, rootNode.getOwnerDocument(), "error.xsl", null);
    }
}

From source file:com.streamsets.pipeline.stage.processor.kv.redis.RedisLookupProcessor.java

@SuppressWarnings("unchecked")
private void updateRecord(LookupValue value, String outputFieldPath, Record record) throws StageException {
    switch (value.getType()) {
    case STRING:/* w w  w .  jav a 2s.c om*/
        Optional<String> string = Optional.fromNullable((String) value.getValue());
        if (Optional.fromNullable(value.getValue()).isPresent()) {
            record.set(outputFieldPath, Field.create(string.get()));
        }
        break;
    case LIST:
        List<Field> field = new ArrayList<>();
        List<String> list = (List<String>) value.getValue();
        if (!list.isEmpty()) {
            for (String element : list) {
                field.add(Field.create(element));
            }
            record.set(outputFieldPath, Field.create(field));
        }
        break;
    case HASH:
        Map<String, Field> fieldMap = new HashMap<>();
        HashMap<String, String> map = (HashMap<String, String>) value.getValue();
        if (!map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                fieldMap.put(entry.getKey(), Field.create(entry.getValue()));
            }
            record.set(outputFieldPath, Field.create(fieldMap));
        }
        break;
    case SET:
        field = new ArrayList<>();
        Set<String> set = (Set<String>) value.getValue();
        if (!set.isEmpty()) {
            for (String element : set) {
                field.add(Field.create(element));
            }
            record.set(outputFieldPath, Field.create(field));
        }
        break;
    default:
        LOG.error(Errors.REDIS_LOOKUP_04.getMessage(), value.getType().getLabel(),
                record.getHeader().getSourceId());
        throw new StageException(Errors.REDIS_LOOKUP_04, value.getType().getLabel(),
                record.getHeader().getSourceId());
    }
}

From source file:com.polyvi.xface.extension.XExtensionManager.java

/**
 * /*ww w .j a  va2 s  .c  om*/
 */
public void loadExtensions() {
    HashMap<String, XExtensionEntry> loadingExtensions = XConfiguration.getInstance()
            .readLoadingExtensions(mExtensionContext);
    Iterator<Entry<String, XExtensionEntry>> iter = loadingExtensions.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, XExtensionEntry> entry = iter.next();
        String extName = entry.getKey();
        String className = entry.getValue().getExtClassName();
        XExtension ext = createExtension(className);
        if (null == ext) {
            continue;
        }
        registerExtension(extName, ext);
    }
}

From source file:com.seekret.data.flickr.FlickrRequestHandler.java

public Set<PointOfInterest> getPOIsForSpot(Spot spot) {

    Set<PointOfInterest> result = new HashSet<PointOfInterest>();

    HashMap<LatLng, Double> calculateNewPoint = calculateNewPoint(spot);

    List<String> picture_ids = new ArrayList<String>();

    for (Entry<LatLng, Double> entry : calculateNewPoint.entrySet()) {
        int requestedPage = 1;
        int logBarrier = 1;
        int numberPages = 1;
        int maxViewCount = 0;

        LatLng position = entry.getKey();
        double radiusInKm = entry.getValue().doubleValue();
        do {/*from  w  ww .j a v  a  2s.  co m*/
            String urlForRequest = buildPhotoRequestURL(requestedPage, position, radiusInKm, LicenseEnum.ALL);

            JsonObject photosObject;

            try {
                if (requestedPage == logBarrier) {
                    logBarrier *= 2;
                    log.log(Level.INFO, "Retrieving all images for spot " + spot + " (page=" + requestedPage
                            + ",numberPages=" + numberPages + ") -> " + urlForRequest);
                }
                String jsonResponse = Request.Get(urlForRequest.toString()).execute().returnContent()
                        .asString();
                requestedPage++;
                photosObject = JsonObject.readFrom(jsonResponse);
                numberPages = handleFlickrPictureResult(result, picture_ids, numberPages, maxViewCount,
                        photosObject);
            } catch (Exception e) {
                log.log(Level.WARNING, "Could not load picture page from flickr", e);
            }
            // We need to make this algorithm more efficient
        } while ((requestedPage < numberPages) && (requestedPage < MAX_NUMBER_PAGES_TO_CRAWL)
                && result.size() < 10000);
        log.log(Level.INFO, "NUMBER OF PICTURES " + picture_ids.size());
    }
    return result;
}