Example usage for java.util HashMap get

List of usage examples for java.util HashMap get

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Creates a {@link GridCoverage2D coverage} from the {@link WritableRaster writable raster} and the necessary geographic Information.
 * //from w w w. ja  v  a  2s . c o m
 * @param name the name of the coverage.
 * @param writableRaster the raster containing the data.
 * @param envelopeParams the map of boundary parameters.
 * @param crs the {@link CoordinateReferenceSystem}.
 * @return the {@link GridCoverage2D coverage}.
 */
public static GridCoverage2D buildCoverage(String name, WritableRaster writableRaster,
        HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs) {

    double west = envelopeParams.get(WEST);
    double south = envelopeParams.get(SOUTH);
    double east = envelopeParams.get(EAST);
    double north = envelopeParams.get(NORTH);
    Envelope2D writeEnvelope = new Envelope2D(crs, west, south, east - west, north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);

    GridCoverage2D coverage2D = factory.create(name, writableRaster, writeEnvelope);
    return coverage2D;
}

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host,
        String parameters) {//www.j  ava 2  s  . c  om
    boolean result = false;
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    try {
        // get actual events
        String url = host + "/?command=listEvents&" + parameters;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is,
                    new String[] { "event" });

            for (int i = 0; i < eventValues.size(); i++) {
                HashMap<String, String> element = eventValues.get(i);
                if (element.get("level").equals(level)) {
                    if (actualEvents.containsKey(element.get("type")) == true) {
                        actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                    } else {
                        actualEvents.put(element.get("type"), 1);
                    }
                }
            }
        }
        method.releaseConnection();
    } catch (Exception ex) {
        s_logger.error(ex);
    }

    // compare actual events with expected events
    Iterator<?> iterator = expectedEvents.keySet().iterator();
    Integer expected;
    Integer actual;
    int fail = 0;
    while (iterator.hasNext()) {
        expected = null;
        actual = null;
        String type = iterator.next().toString();
        expected = expectedEvents.get(type);
        actual = actualEvents.get(type);
        if (actual == null) {
            s_logger.error("Event of type " + type + " and level " + level
                    + " is missing in the listEvents response. Expected number of these events is " + expected);
            fail++;
        } else if (expected.compareTo(actual) != 0) {
            fail++;
            s_logger.info("Amount of events of  " + type + " type and level " + level
                    + " is incorrect. Expected number of these events is " + expected + ", actual number is "
                    + actual);
        }
    }

    if (fail == 0) {
        result = true;
    }

    return result;
}

From source file:edu.illinois.cs.cogcomp.transliteration.CSPTransliteration.java

public static double GetBestProbability(int position, String originalWord1, String word1, String word2,
        CSPModel model, HashMap<Triple<Integer, String, String>, Double> memoizationTable) {
    double result;
    Triple<Integer, String, String> v = new Triple<Integer, String, String>(position, word1, word2);
    if (memoizationTable.containsKey(v)) {
        return memoizationTable.get(v); //we've been down this road before
    }/*  w  ww. j  a  va  2  s. c  o m*/

    result = 0;

    if (word1.length() == 0 && word2.length() == 0)
        return 1; //perfect null-to-null alignment

    int maxSubstringLength1f = Math.min(word1.length(), model.maxSubstringLength);
    int maxSubstringLength2f = Math.min(word2.length(), model.maxSubstringLength);

    String[] leftContexts = WikiTransliteration.GetLeftFallbackContexts(originalWord1, position,
            Math.max(model.segContextSize, model.productionContextSize));

    double minProductionProbability1 = 1;

    for (int i = 1; i <= maxSubstringLength1f; i++) //for each possible substring in the first word...
    {
        minProductionProbability1 *= model.minProductionProbability;

        String substring1 = word1.substring(0, i);
        String[] rightContexts = WikiTransliteration.GetRightFallbackContexts(originalWord1, position + i,
                Math.max(model.segContextSize, model.productionContextSize));

        double segProb;
        if (model.segProbs.size() == 0)
            segProb = 1;
        else {
            segProb = 0;
            for (int k = model.productionContextSize; k >= 0; k--) {
                Triple<String, String, String> v5 = new Triple<>(leftContexts[k], substring1, rightContexts[k]);
                if (model.segProbs.containsKey(v5)) {
                    segProb = model.segProbs.get(v5);
                    break;
                }
            }
        }

        double minProductionProbability2 = 1;
        for (int j = 1; j <= maxSubstringLength2f; j++) //foreach possible substring in the second
        {
            minProductionProbability2 *= model.minProductionProbability;

            if ((word1.length() - i) * model.maxSubstringLength >= word2.length() - j
                    && (word2.length() - j) * model.maxSubstringLength >= word1.length() - i) //if we get rid of these characters, can we still cover the remainder of word2?
            {
                double minProductionProbability;
                if (model.smoothMode == CSPModel.SmoothMode.BySource)
                    minProductionProbability = minProductionProbability1;
                else if (model.smoothMode == CSPModel.SmoothMode.ByMax)
                    minProductionProbability = Math.min(minProductionProbability1, minProductionProbability2);
                else //if (model.smoothMode == SmoothMode.BySum)
                    minProductionProbability = minProductionProbability1 * minProductionProbability2;

                String substring2 = word2.substring(0, j);
                //Pair<Triple<String, String, String>, String> production = new Pair<Triple<String, String, String>, String>(new Triple<String, String, String>(leftProductionContext, substring1, rightProductionContext), substring2);

                double prob;
                if (model.productionProbs.size() == 0)
                    prob = 1;
                else {
                    prob = 0;
                    for (int k = model.productionContextSize; k >= 0; k--) {
                        Pair<Triple<String, String, String>, String> v4 = new Pair<>(
                                new Triple<>(leftContexts[k], substring1, rightContexts[k]), substring2);
                        if (model.productionProbs.containsKey(v4)) {
                            prob = model.productionProbs.get(v4);
                            break;
                        }

                    }

                    prob = Math.max(prob, minProductionProbability);
                }

                double remainder = prob * GetBestProbability(position + i, originalWord1, word1.substring(i),
                        word2.substring(j), model, memoizationTable);

                if (remainder > result)
                    result = remainder; //maximize

                //record this remainder in our results
                //result.x += remainder.x * prob * segProb;
                //result.y += remainder.y * segProb;
            }
        }
    }

    memoizationTable.put(new Triple<>(position, word1, word2), result);
    return result;
}

From source file:com.evolveum.polygon.test.scim.StandardScimTestUtils.java

public static ScimConnectorConfiguration buildConfiguration(HashMap<String, String> configuration) {
    ScimConnectorConfiguration scimConnectorConfiguration = new ScimConnectorConfiguration();

    for (String configurationParameter : configuration.keySet()) {

        if ("clientID".equals(configurationParameter)) {
            scimConnectorConfiguration.setClientID(configuration.get(configurationParameter));
        } else if ("clientSecret".equals(configurationParameter)) {
            scimConnectorConfiguration.setClientSecret(configuration.get(configurationParameter));
        } else if ("endpoint".equals(configurationParameter)) {
            scimConnectorConfiguration.setEndpoint(configuration.get(configurationParameter));
        } else if ("loginUrl".equals(configurationParameter)) {
            scimConnectorConfiguration.setLoginURL(configuration.get(configurationParameter));
        } else if ("password".equals(configurationParameter)) {
            char[] passChars = configuration.get(configurationParameter).toCharArray();
            GuardedString guardedPass = new GuardedString(passChars);
            scimConnectorConfiguration.setPassword(guardedPass);
        } else if ("service".equals(configurationParameter)) {
            scimConnectorConfiguration.setService(configuration.get(configurationParameter));
        } else if ("userName".equals(configurationParameter)) {
            scimConnectorConfiguration.setUserName(configuration.get(configurationParameter));
        } else if ("version".equals(configurationParameter)) {
            scimConnectorConfiguration.setVersion(configuration.get(configurationParameter));
        } else if ("authentication".equals(configurationParameter)) {
            scimConnectorConfiguration.setAuthentication(configuration.get(configurationParameter));
        } else if ("baseurl".equals(configurationParameter)) {
            scimConnectorConfiguration.setBaseUrl(configuration.get(configurationParameter));
        } else if ("token".equals(configurationParameter)) {
            char[] tokenCharacters = configuration.get(configurationParameter).toCharArray();
            GuardedString guardedToken = new GuardedString(tokenCharacters);
            scimConnectorConfiguration.setToken(guardedToken);

        } else if ("proxy".equals(configurationParameter)) {
            scimConnectorConfiguration.setProxyUrl(configuration.get(configurationParameter));
        } else if ("proxy_port_number".equals(configurationParameter)) {
            String parameterValue = configuration.get(configurationParameter);
            if (!parameterValue.isEmpty()) {
                Integer portNumber = Integer.parseInt(parameterValue);
                scimConnectorConfiguration.setProxyPortNumber(portNumber);
            } else
                scimConnectorConfiguration.setProxyPortNumber(null);
        } else {/*from  w  w w.  ja  v  a  2s  .  c om*/

            LOGGER.warn("Occurrence of an non defined parameter");
        }
    }
    return scimConnectorConfiguration;

}

From source file:com.ibm.bi.dml.hops.globalopt.GDFEnumOptimizer.java

/**
 * /* w ww  .j a v a 2 s.  c  o m*/
 * @param plans
 * @param maxCosts 
 * @throws DMLRuntimeException 
 * @throws DMLUnsupportedOperationException 
 */
private static void pruneSuboptimalPlans(PlanSet plans, double maxCosts)
        throws DMLRuntimeException, DMLUnsupportedOperationException {
    //costing of all plans incl containment check
    for (Plan p : plans.getPlans()) {
        p.setCosts(costRuntimePlan(p));
    }

    //build and probe for optimal plans (hash-groupby on IPC, min costs) 
    HashMap<InterestingProperties, Plan> probeMap = new HashMap<InterestingProperties, Plan>();
    for (Plan p : plans.getPlans()) {
        //max cost pruning filter (branch-and-bound)
        if (BRANCH_AND_BOUND_PRUNING && p.getCosts() > maxCosts) {
            continue;
        }

        //plan cost per IPS pruning filter (allow smaller or equal costs)
        Plan best = probeMap.get(p.getInterestingProperties());
        if (best != null && p.getCosts() > best.getCosts()) {
            continue;
        }

        //non-preferred plan pruning filter (allow smaller cost or equal cost and preferred plan)
        if (PREFERRED_PLAN_SELECTION && best != null && p.getCosts() == best.getCosts()
                && !p.isPreferredPlan()) {
            continue;
        }

        //add plan as best per IPS
        probeMap.put(p.getInterestingProperties(), p);

    }

    //copy over plans per IPC into one plan set
    ArrayList<Plan> optimal = new ArrayList<Plan>(probeMap.values());

    int sizeBefore = plans.size();
    int sizeAfter = optimal.size();
    _prunedSuboptimalPlans += (sizeBefore - sizeAfter);
    LOG.debug("Pruned suboptimal plans: " + sizeBefore + " --> " + sizeAfter);

    plans.setPlans(optimal);
}

From source file:com.clustercontrol.notify.util.NotifyRelationCache.java

public static void refresh() {
    JpaTransactionManager jtm = new JpaTransactionManager();
    if (!jtm.isNestedEm()) {
        m_log.warn("refresh() : transactioin has not been begined.");
        jtm.close();//from  w  w w  .j a va 2  s  .c  o m
        return;
    }

    try {
        _lock.writeLock();

        long start = HinemosTime.currentTimeMillis();
        new JpaTransactionManager().getEntityManager().clear();
        HashMap<String, List<NotifyRelationInfo>> notifyMap = new HashMap<String, List<NotifyRelationInfo>>();
        List<NotifyRelationInfo> nriList = null;
        try {
            nriList = QueryUtil.getAllNotifyRelationInfoWithoutJob();
        } catch (Exception e) {
            m_log.warn("refresh() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
            return;
        }
        for (NotifyRelationInfo nri : nriList) {
            String notifyGroupId = nri.getId().getNotifyGroupId();
            // ???????????
            if (onCache(notifyGroupId)) {
                List<NotifyRelationInfo> notifyList = notifyMap.get(notifyGroupId);
                if (notifyList == null) {
                    notifyList = new ArrayList<NotifyRelationInfo>();
                    notifyList.add(nri);
                    notifyMap.put(notifyGroupId, notifyList);
                } else {
                    notifyList.add(nri);
                }
            }
        }
        for (List<NotifyRelationInfo> notifyList : notifyMap.values()) {
            if (notifyList == null) {
                continue;
            }
            Collections.sort(notifyList);
        }
        storeCache(notifyMap);
        m_log.info("refresh NotifyRelationCache. " + (HinemosTime.currentTimeMillis() - start) + "ms. size="
                + notifyMap.size());
    } finally {
        _lock.writeUnlock();
    }
}

From source file:controllers.SnLocationsController.java

public static void discoverHereNow() {

    String appid = params._contains(PARAM_APPID) ? params.get(PARAM_APPID) : "";
    String limit = params._contains(PARAM_LIMIT) ? params.get(PARAM_LIMIT) : "";
    limit = verifyRecordLimit(limit);/*from  ww  w  . j  a v a 2  s  .  c  o  m*/
    String ids = params._contains(PARAM_IDS) ? params.get(PARAM_IDS) : "";

    //Logger.info("appid, limit, ids : %s, %s, %s \n", appid, limit, ids);
    Logger.info("PARAMS -> appid:%s ; limit:%s ; ids:%s", appid, limit, ids);

    // using Async jobs
    ResponseModel responseModel = new ResponseModel();
    ResponseMeta responseMeta = new ResponseMeta();
    LinkedList<Object> dataList = new LinkedList<Object>();

    HashMap params = new HashMap();

    try {

        params.clear();
        //-if (!StringUtils.isEmpty(limit)) params.put(PARAM_LIMIT, limit);
        FoursquareDiscoverPoiJob mFoursquarePoiJob = new FoursquareDiscoverPoiJob();
        mFoursquarePoiJob.setIds(ids);
        mFoursquarePoiJob.setReqParams(params);
        dataList.addAll((LinkedList<Object>) mFoursquarePoiJob.doJobWithResult());

        // HereNow part
        params.clear();
        if (!StringUtils.isEmpty(limit))
            params.put(PARAM_LIMIT, limit);
        FoursquareDiscoverHereNowJob mFoursquareDiscoverHereNowJob = new FoursquareDiscoverHereNowJob();
        mFoursquareDiscoverHereNowJob.setReqParams(params);
        mFoursquareDiscoverHereNowJob.setPoiList(dataList);
        dataList = new LinkedList<Object>();//dataList.clear();
        dataList.addAll((LinkedList<Object>) mFoursquareDiscoverHereNowJob.doJobWithResult());

        response.status = Http.StatusCode.OK;
        responseMeta.code = response.status;
        responseModel.meta = responseMeta;
        responseModel.data = dataList;

        renderJSON(LocoUtils.getGson().toJson(responseModel));
    } catch (Exception ex) {

        responseMeta.code = Http.StatusCode.INTERNAL_ERROR;
        gotError(responseMeta, ex);
        //renderJSON(responseModel);
    }
}

From source file:com.example.common.ApiRequestFactory.java

/**
 * Generate the API XML request body//from  www .  j a  v a 2  s . c  om
 */
@SuppressWarnings("unchecked")
private static String generateXmlRequestBody(Object params) {

    if (params == null) {
        return "<request version=\"2\"></request>";
    }

    HashMap<String, Object> requestParams;
    if (params instanceof HashMap) {
        requestParams = (HashMap<String, Object>) params;
    } else {
        return "<request version=\"2\"></request>";
    }

    final StringBuilder buf = new StringBuilder();

    // TODO: add local_version parameter if exist
    // 2010/12/29 update version to 2 to get comments from bbs
    buf.append("<request version=\"2\"");
    if (requestParams.containsKey("local_version")) {
        buf.append(" local_version=\"" + requestParams.get("local_version") + "\" ");
        requestParams.remove("local_version");
    }
    buf.append(">");

    // add parameter node
    final Iterator<String> keySet = requestParams.keySet().iterator();
    while (keySet.hasNext()) {
        final String key = keySet.next();

        if ("upgradeList".equals(key)) {
            buf.append("<products>");
            List<PackageInfo> productsList = (List<PackageInfo>) requestParams.get(key);
            for (PackageInfo info : productsList) {
                buf.append("<product package_name=\"").append(info.packageName);
                buf.append("\" version_code=\"").append(info.versionCode).append("\"/>");
            }
            buf.append("</products>");
            continue;
        } else if ("appList".equals(key)) {
            buf.append("<apps>");
            List<UpgradeInfo> productsList = (List<UpgradeInfo>) requestParams.get(key);
            for (UpgradeInfo info : productsList) {
                buf.append("<app package_name=\"").append(info.pkgName);
                buf.append("\" version_code=\"").append(info.versionCode);
                buf.append("\" version_name=\"").append(info.versionName);
                buf.append("\" app_name=\"").append(wrapText(info.name));
                //                    buf.append("\" md5=\"").append(info.md5);
                buf.append("\"/>");
            }
            buf.append("</apps>");
            continue;
        }

        buf.append("<").append(key).append(">");
        buf.append(requestParams.get(key));
        buf.append("</").append(key).append(">");
    }

    // add the enclosing quote
    buf.append("</request>");
    return buf.toString();
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

public static GridCoverage2D removeNovalues(GridCoverage2D geodata) {
    // need to adapt it, for now do it dirty
    HashMap<String, Double> params = getRegionParamsFromGridCoverage(geodata);
    int height = params.get(ROWS).intValue();
    int width = params.get(COLS).intValue();
    WritableRaster tmpWR = createDoubleWritableRaster(width, height, null, null, null);
    WritableRandomIter tmpIter = RandomIterFactory.createWritable(tmpWR, null);
    RenderedImage readRI = geodata.getRenderedImage();
    RandomIter readIter = RandomIterFactory.create(readRI, null);
    for (int r = 0; r < height; r++) {
        for (int c = 0; c < width; c++) {
            double value = readIter.getSampleDouble(c, r, 0);

            if (Double.isNaN(value) || Float.isNaN((float) value) || Math.abs(value - -9999.0) < .0000001) {
                tmpIter.setSample(c, r, 0, Double.NaN);
            } else {
                tmpIter.setSample(c, r, 0, value);
            }/*from  w w w.j av a2s .  c o m*/
        }
    }
    geodata = buildCoverage("newcoverage", tmpWR, params, geodata.getCoordinateReferenceSystem());
    return geodata;
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPutWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPut put = null;//from w  ww.j a  v  a2  s .co  m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        put = new HttpPut(url);
        put.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            put.setHeader(key, headers.get(key));
        }
        put.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(put);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}