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:org.jdbcluster.JDBClusterUtil.java

/**
 * Tries to determine the best fitting method for a set of parameter types.
 * Uses getMethod() first, if there is no direct match every parameter is
 * checked if there is a method with a superclass or superinterface match.
 * etc. For this best fitting method a scoring is used. It counts for every
 * parameter the "distance" from the class to the requested superclass or
 * superinterface. These "distances" are cummulated to one value. The method
 * with the lowest scoring value is returned.
 * /* w w w . j  a  va 2 s.  c  om*/
 * @see #getMethod(Class, String, Class[])
 * @param clazz
 *            Class of Object
 * @param methodName
 *            name of the method to find
 * @param parameterTypes
 *            parameter types of method
 * @return Method to find
 */
static public Method getMethodBestParameterFit(Class clazz, String methodName, Class... parameterTypes) {

    /*
     * first try the normal way (exact match)
     */
    try {
        return JDBClusterUtil.getMethod(clazz, methodName, parameterTypes);
    } catch (ConfigurationException e) {
        if (!(e.getCause() instanceof NoSuchMethodException))
            throw e;
    }

    /*
     * get all methods and select only equal name and parameter length in
     * mList
     */
    Method[] mAll = clazz.getMethods();
    List<Method> mList = new ArrayList<Method>();

    for (Method m : mAll) {
        if (m.getParameterTypes().length == parameterTypes.length && m.getName().equals(methodName))
            mList.add(m);
    }

    if (mList.size() > 1)
        logger.warn("possible ambiguity. Found more than one method with name [" + methodName + "]. "
                + "trying best fit method");

    /*
     * check if parameter superclasses do fit for all above selected methods
     */
    HashMap<Method, Integer> methodScore = new HashMap<Method, Integer>();
    for (Method m : mList) {
        Class<?>[] mParameterTypes = m.getParameterTypes();

        for (int i = 0; i < parameterTypes.length; i++) {
            int count = countSuper(mParameterTypes[i], parameterTypes[i]);
            Integer oldInt = methodScore.get(m);
            if (oldInt == null)
                oldInt = 0;
            methodScore.put(m, oldInt + count);
            if (count < 0) {
                methodScore.put(m, -1);
                break; // if there is no match this method is not fitting
            }
        }
    }

    /*
     * evaluate scoring
     */
    Method mResult = null;
    int resultScore = Integer.MAX_VALUE;
    for (Method m : mList) {
        int score = methodScore.get(m);
        if (score != -1) {
            if (score < resultScore) {
                resultScore = score;
                mResult = m;
            }
        }
    }

    if (mResult == null)
        throw new ConfigurationException(
                "cant get MethodBestParameterFit for method [" + methodName + "] with the specified name");

    return mResult;
}

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

public static Pair<Double, Double> GetProbability(int position, String originalWord1, String word1,
        String word2, CSPModel model,
        HashMap<Triple<Integer, String, String>, Pair<Double, Double>> memoizationTable) {
    Pair<Double, Double> result;
    Triple<Integer, String, String> v = new Triple<>(position, word1, word2);
    if (memoizationTable.containsKey(v)) {
        return memoizationTable.get(v);
    }/*w w  w . ja v  a  2  s.c  o  m*/

    result = new Pair<>(0.0, 0.0);

    if (word1.length() == 0 && word2.length() == 0) //record probabilities
    {
        result.setFirst(1.0); //null -> null is always a perfect alignment
        result.setSecond(1.0);
        return result; //end of the line
    }

    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> v2 = new Triple<>(leftContexts[k], substring1, rightContexts[k]);
                if (model.segProbs.containsKey(v2)) {
                    segProb = model.segProbs.get(v2);
                    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> v3 = new Pair<>(
                                new Triple<>(leftContexts[k], substring1, rightContexts[k]), substring2);
                        if (model.productionProbs.containsKey(v3)) {
                            prob = model.productionProbs.get(v3);
                            break;
                        }
                    }

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

                Pair<Double, Double> remainder = GetProbability(position + i, originalWord1, word1.substring(i),
                        word2.substring(j), model, memoizationTable);

                //record this remainder in our results
                result.setFirst(result.getFirst() + remainder.getFirst() * prob * segProb);
                result.setSecond(result.getSecond() + remainder.getSecond() * segProb);

            }
        }
    }

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

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

public static HTTPResponse sendHTTPPost(String url, String payload, HashMap<String, String> headers) {
    HttpPost post = null;//w  ww .  j ava2s  .com
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        post = new HttpPost(url);
        post.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }
        response = httpclient.execute(post);
    } 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;
}

From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java

public static HttpPost getPostForm(final String requestBaseUrl, final Element form,
        final HashMap<String, String> formMapping) throws MalformedURLException {
    final List<NameValuePair> formNvps = new ArrayList<NameValuePair>();
    final String formAction = form.attr("action");
    final HttpPost formPost = new HttpPost(getUrl(requestBaseUrl, formAction));
    final Elements formFields = form.select("input");
    for (final Element element : formFields) {
        final String fieldName = element.attr("name");
        String fieldValue = element.attr("value");
        final String fieldId = element.attr("id");

        if (formMapping != null) {
            final String mappedValue = formMapping.get(fieldId);
            if (mappedValue != null) {
                fieldValue = mappedValue;
            }//from   w  ww.jav a 2  s  . c  o m
        }

        log.debug(String.format("Processing form field: name='%s' value='%s' id='%s'", fieldName, fieldValue,
                fieldId));
        formNvps.add(new BasicNameValuePair(fieldName, fieldValue));
    }
    try {
        formPost.setEntity(new UrlEncodedFormEntity(formNvps, "UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        // This would never happen
        throw new IllegalArgumentException("UTF-8 not recognised");
    }

    return formPost;
}

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

public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPost post = null;// w  w w  .j  av a 2  s.  c o  m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        post = new HttpPost(url);
        post.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }

        post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(post);
    } 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;
}

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

public static boolean verifyEvents(String fileName, String level, String host, String account) {
    boolean result = false;
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    String key = "";

    File file = new File(fileName);
    if (file.exists()) {
        Properties pro = new Properties();
        try {/*  www  . j  av  a  2 s  . c o  m*/
            // get expected events
            FileInputStream in = new FileInputStream(file);
            pro.load(in);
            Enumeration<?> en = pro.propertyNames();
            while (en.hasMoreElements()) {
                key = (String) en.nextElement();
                expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
            }

            // get actual events
            String url = host + "/?command=listEvents&account=" + account + "&level=" + level
                    + "&domainid=1&pagesize=100";
            s_logger.info("Getting events with the following url " + url);
            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();

            // compare actual events with expected events

            // compare expected result and actual result
            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;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    } else {
        s_logger.info("File " + fileName + " not found");
    }
    return result;
}

From source file:com.act.reachables.Network.java

public static JSONObject edgeObj(Edge e, HashMap<Node, Integer> order) throws JSONException {
    JSONObject eo = new JSONObject();
    if (order != null) {
        // 1. when printing a graph (and not a tree), the source and target nodeMapping are identified
        // by the array index they appear in the nodeMapping JSONArray. Those indices are contained in the order-map.
        // 2. such an ordering is not required when we are working with trees, so these fields not output there.
        eo.put("source", order.get(e.src)); // required, and have to lookup its order in the node spec
        eo.put("target", order.get(e.dst)); // required, and have to lookup its order in the node spec
    }//from  w ww. ja  v a2  s. c  o  m
    // eo.put("source_id", e.src.id); // only informational
    // eo.put("target_id", e.dst.id); // only informational
    // eo.put("value", 1); // weight of edge: not really needed
    HashMap<String, Serializable> attr = e.getAttr();
    for (String k : attr.keySet()) {
        // only output the fields relevant to the reachables tree structures
        if (k.equals("under_root") || k.equals("functionalCategory") || k.equals("importantAncestor"))
            eo.put(k, attr.get(k).toString());
    }
    return eo;
}

From source file:com.proctorcam.proctorserv.HashedAuthenticator.java

public static HashMap<String, Object> applyReverseGuidAndSign(HashMap<String, Object> params,
        String customer_identifier, String shared_secret) {
    //Create random GUID
    SecureRandom secRandom = null;
    try {/* w w  w  . j a va2  s. com*/
        secRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
        System.err.println(ex.getMessage());
    }
    String guid = new Integer(secRandom.nextInt()).toString();
    params.put("customer_id", customer_identifier);
    params.put("guid", guid);
    params.put("signature", "");

    //Create query string using key-value pairs in params and
    //appending shared_secret
    StringBuilder query = new StringBuilder();

    for (String key : params.keySet()) {
        if (key != "signature") {
            Object data = params.get(key);

            if (is_hashmap(data)) {
                HashMap<String, Object> map = (HashMap<String, Object>) data;
                String hashMapQuery = hashQuery(key, map);
                query.append(hashMapQuery);

            } else if (is_array(data)) {
                Object[] array = getArray(data);
                String arrayString = arrayQuery(key, array);
                query.append(arrayString);

            } else {
                query.append(key).append("=").append(data).append("&");
            }
        }
    }

    //Deletes trailing & from query and append shared_secret
    query.deleteCharAt(query.length() - 1);
    query.append(shared_secret);
    String signature = buildSig(query);

    //Add signature to params
    params.put("signature", signature);

    //Reverse guid in params
    String reverseGUID = new StringBuilder(guid).reverse().toString();
    params.put("guid", reverseGUID);

    return params;
}

From source file:edu.yale.cs.hadoopdb.sms.SQLQueryGenerator.java

/**
 * Performs Hive's plan analysis and SQL generation for all tables
 *///from w  ww  . j a  va  2s .c  om
public static void process(HiveConf conf, QB qb, HashMap<String, Operator<? extends Serializable>> topOps) {

    for (String alias : qb.getMetaData().getAliasToTable().keySet()) {
        LOG.debug("Table : " + alias);
        Table tbl = qb.getMetaData().getTableForAlias(alias);

        if (tbl.getInputFormatClass().equals(SMSInputFormat.class)) {

            SQLQuery sqlStructure = SQLQueryGenerator.processTable(alias, tbl,
                    (TableScanOperator) topOps.get(alias));
            conf.set(SMSInputFormat.DB_QUERY_SCHEMA_PREFIX + "_" + tbl.getName(),
                    sqlStructure.getDBQuerySchema());
            conf.set(SMSInputFormat.DB_SQL_QUERY_PREFIX + "_" + tbl.getName(), sqlStructure.getSqlQuery());

            SQLQueryGenerator.hackMapredWorkSchema(sqlStructure, tbl);

            LOG.info(SMSInputFormat.DB_QUERY_SCHEMA_PREFIX + "_" + tbl.getName() + "---"
                    + sqlStructure.getDBQuerySchema());
            LOG.info(SMSInputFormat.DB_SQL_QUERY_PREFIX + "_" + tbl.getName() + "---"
                    + sqlStructure.getSqlQuery());

        }
    }

}

From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java

@SuppressWarnings("unchecked")
private static final void putElementValue(HashMap<String, Object> dataMap, ColumnDefinition defn,
        Object value) {// w ww .jav a2s .  c o m
    List<ColumnDefinition> nesting = new ArrayList<ColumnDefinition>();
    ColumnDefinition cur = defn.getParent();
    while (cur != null) {
        nesting.add(cur);
        cur = cur.getParent();
    }

    HashMap<String, Object> elem = dataMap;
    for (int i = nesting.size() - 1; i >= 0; --i) {
        cur = nesting.get(i);
        if (elem.containsKey(cur.getElementName())) {
            elem = (HashMap<String, Object>) elem.get(cur.getElementName());
        } else {
            elem.put(cur.getElementName(), new HashMap<String, Object>());
            elem = (HashMap<String, Object>) elem.get(cur.getElementName());
        }
    }
    elem.put(defn.getElementName(), value);
}