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:com.concursive.connect.web.portal.PortalUtils.java

/**
 * When a form is submitted with enctype="multipart/form-data", then the
 * parameters and values are placed into a parts HashMap which can now
 * be auto-populated/*from  ww w  . j av a2 s.co m*/
 *
 * @param bean
 * @param parts
 */
public static void populateObject(Object bean, HashMap parts) {
    if (parts != null) {
        Iterator names = parts.keySet().iterator();
        while (names.hasNext()) {
            String paramName = (String) names.next();
            Object paramValues = parts.get(paramName);
            if (paramValues != null && paramValues instanceof String) {
                ObjectUtils.setParam(bean, paramName, paramValues, "_");
            }
        }
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 *  Returns all those types that have been requested so far.
 *
 * @param ctx the wiki context//  w  w w  .  j a v a 2s .  com
 * @return the array of types requested
 */
@SuppressWarnings("unchecked")
public static String[] getResourceTypes(WikiContext ctx) {
    String[] res = new String[0];

    if (ctx != null) {
        HashMap<String, String> hm = (HashMap<String, String>) ctx.getVariable(RESOURCE_INCLUDES);

        if (hm != null) {
            Set<String> keys = hm.keySet();

            res = keys.toArray(res);
        }
    }

    return res;
}

From source file:models.NotificationMail.java

/**
 * Sends notification mails for the given event.
 *
 * @param event/* w w  w. ja  v  a2  s .c  o m*/
 * @see <a href="https://github.com/nforge/yobi/blob/master/docs/technical/watch.md>watch.md</a>
 */
private static void sendNotification(NotificationEvent event) {
    Set<User> receivers = event.receivers;

    // Remove inactive users.
    Iterator<User> iterator = receivers.iterator();
    while (iterator.hasNext()) {
        User user = iterator.next();
        if (user.state != UserState.ACTIVE) {
            iterator.remove();
        }
    }

    receivers.remove(User.anonymous);

    if (receivers.isEmpty()) {
        return;
    }

    HashMap<String, List<User>> usersByLang = new HashMap<>();

    for (User receiver : receivers) {
        String lang = receiver.lang;

        if (lang == null) {
            lang = Locale.getDefault().getLanguage();
        }

        if (usersByLang.containsKey(lang)) {
            usersByLang.get(lang).add(receiver);
        } else {
            usersByLang.put(lang, new ArrayList<>(Arrays.asList(receiver)));
        }
    }

    for (String langCode : usersByLang.keySet()) {
        final EventEmail email = new EventEmail(event);

        try {
            if (hideAddress) {
                email.setFrom(Config.getEmailFromSmtp(), event.getSender().name);
                email.addTo(Config.getEmailFromSmtp(), utils.Config.getSiteName());
            } else {
                email.setFrom(event.getSender().email, event.getSender().name);
            }

            for (User receiver : usersByLang.get(langCode)) {
                if (hideAddress) {
                    email.addBcc(receiver.email, receiver.name);
                } else {
                    email.addTo(receiver.email, receiver.name);
                }
            }

            if (email.getToAddresses().isEmpty()) {
                continue;
            }

            Lang lang = Lang.apply(langCode);

            String message = event.getMessage(lang);
            String urlToView = event.getUrlToView();
            String reference = Url.removeFragment(event.getUrlToView());

            email.setSubject(event.title);

            Resource resource = event.getResource();
            if (resource.getType() == ResourceType.ISSUE_COMMENT) {
                IssueComment issueComment = IssueComment.find.byId(Long.valueOf(resource.getId()));
                resource = issueComment.issue.asResource();
            }
            email.setHtmlMsg(getHtmlMessage(lang, message, urlToView, resource));
            email.setTextMsg(getPlainMessage(lang, message, Url.create(urlToView)));
            email.setCharset("utf-8");
            email.addReferences();
            email.setSentDate(event.created);
            Mailer.send(email);
            String escapedTitle = email.getSubject().replace("\"", "\\\"");
            String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
            play.Logger.of("mail").info(logEntry);
        } catch (Exception e) {
            Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
        }
    }
}

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 {//  ww  w. j a va 2  s.co m
        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:LineageSimulator.java

public static void writeVAFsToFile(String fileName, HashMap<Mutation.SNV, double[]> snvToVAFs,
        HashMap<Mutation.SNV, String> binaryProfiles, int numSamples) {
    String vafs = "";
    vafs += "#chrom\tpos\tdesc";
    if (binaryProfiles != null) {
        vafs += "\tprofile";
    }/*from w  w w .  ja v  a 2 s . co m*/
    vafs += "\tnormal";
    for (int i = 1; i < numSamples; i++) {
        vafs += "\tsample" + i;
    }
    vafs += "\n";
    DecimalFormat df = new DecimalFormat("#.####");
    for (Mutation.SNV snv : snvToVAFs.keySet()) {
        String v = (snv.chr + 1) + "\t" + snv.position + "\t" + snv.name;
        if (binaryProfiles != null) {
            v += "\t" + binaryProfiles.get(snv);
        }
        for (int i = 0; i < numSamples; i++) {
            v += "\t" + df.format(snvToVAFs.get(snv)[i]);
        }
        v += "\n";
        vafs += v;
    }
    writeOutputFile(fileName, vafs);
}

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  ww  w  . ja  v a  2 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;
}

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;/*from   w  w w  . j av a 2s  .co 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));
        }
        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:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPost post = null;/*from  w w w  .  jav a  2 s .  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));
        }

        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:edu.ehu.galan.wiki2wordnet.wikipedia2wordnet.Mapper.java

private static void disambiguateUKB(HashMap<String, List<Wiki2WordnetMapping>> pUkbList,
        List<String> pDesambContext, String pFile, IDictionary pWordnet, HashMap<String, Integer> pMappings,
        String pUkbBinDir) {/* w w w  .  jav a  2 s  . c o  m*/
    logger.debug("Desambiguating Wornet synsets via UKB method");
    HashMap<String, List<String>> toDisam = new HashMap<>();
    logger.debug("Finding gold topics for disambiguation...");
    Function<String, String> contextSynsets = (String t) -> pWordnet
            .getSynset(new SynsetID(pMappings.get(t), POS.NOUN)).getWords().get(0).getLemma();
    List<String> context = pDesambContext.stream().map(contextSynsets).collect(toList());
    for (String topics21 : pUkbList.keySet()) {
        toDisam.put(pWordnet.getSynset(new SynsetID(pMappings.get(topics21), POS.NOUN)).getWords().get(0)
                .getLemma().toLowerCase(), context);
    }
    UKBUtils.prepareInput(toDisam, pFile);
    HashMap<String, Integer> synsets = UKBUtils.processUKB(pUkbBinDir, pFile);
    if (toDisam.size() == synsets.size()) {
        for (String topics21 : pUkbList.keySet()) {
            Integer inte = synsets.get(pWordnet.getSynset(new SynsetID(pMappings.get(topics21), POS.NOUN))
                    .getWords().get(0).getLemma().toLowerCase());
            pMappings.put(topics21, inte);
        }
        logger.debug("UKB disambiguation using WordNet finished");
    } else {
        logger.error("The number of topics to disambiguate via ukb must be the same than the ouput size");
    }

}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do get./*from  w  w  w .ja  va2  s.c  om*/
 *
 * @param uri
 *            the uri
 * @param headers
 *            the headers
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String doGet(URI uri, HashMap<String, String> headers) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String respString = null;
    try {
        /*
         * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs.
         * 
         * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q",
         * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build();
         */

        HttpGet httpGet = new HttpGet(uri);

        for (String key : headers.keySet()) {
            httpGet.addHeader(key, headers.get(key));
        }

        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity = response1.getEntity();
            // do something useful with the response body
            if (entity != null) {
                respString = EntityUtils.toString(entity);
            }
            // and ensure it is fully consumed
            EntityUtils.consume(entity);
        } finally {
            response1.close();
        }
    } finally {
        httpclient.close();
    }
    return respString;
}