Example usage for java.util Map remove

List of usage examples for java.util Map remove

Introduction

In this page you can find the example usage for java.util Map remove.

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:expansionBlocks.ProcessCommunities.java

private static Map<Entity, Double> fusion(Map<Entity, Double> c1, Map<Entity, Double> c2) {
    Map<Entity, Double> result = new HashMap<>();
    Map<Entity, Double> c1c = new HashMap<>(c1);
    Map<Entity, Double> c2c = new HashMap<>(c2);
    Set<Long> intersection = new HashSet(CollectionUtils.intersection(c1c.keySet(), c2c.keySet()));
    for (Map.Entry<Entity, Double> e : c1c.entrySet()) {
        Entity id = e.getKey();// www.  j  a v  a  2 s  . c o m
        Double d = e.getValue();
        if (intersection.contains(id)) {
            Double d2 = c2c.get(id);
            d = (d + d2) / 2;
            c2c.remove(id);
        }
        result.put(id, d);
    }
    for (Map.Entry<Entity, Double> e : c2c.entrySet()) {
        Entity id = e.getKey();
        Double d = e.getValue();
        result.put(id, d);
    }
    return result;

}

From source file:com.core.util.wx.PayUtils.java

/**
 * /*  w  w  w  .  j av  a  2  s . c  om*/
 * 
 * @param xml
 * @return
 */
public static boolean checkSign(Map<String, String> params) {
    Map<String, String> map = new HashMap<String, String>(params);
    String key = "sign";
    String sign = map.get(key);
    if (StringUtils.isBlank(sign))
        return false;
    map.remove(key);
    return sign.equals(getSign(map, ""));
}

From source file:htsjdk.variant.variantcontext.VariantContextUtils.java

/**
 * Update the attributes of the attributes map given the VariantContext to reflect the
 * proper chromosome-based VCF tags// w  w  w  .  j a  va2  s. com
 *
 * @param vc          the VariantContext
 * @param attributes  the attributes map to populate; must not be null; may contain old values
 * @param removeStaleValues should we remove stale values from the mapping?
 * @param founderIds - Set of founders Ids to take into account. AF and FC will be calculated over the founders.
 *                  If empty or null, counts are generated for all samples as unrelated individuals
 * @return the attributes map provided as input, returned for programming convenience
 */
public static Map<String, Object> calculateChromosomeCounts(VariantContext vc, Map<String, Object> attributes,
        boolean removeStaleValues, final Set<String> founderIds) {
    final int AN = vc.getCalledChrCount();

    // if everyone is a no-call, remove the old attributes if requested
    if (AN == 0 && removeStaleValues) {
        if (attributes.containsKey(VCFConstants.ALLELE_COUNT_KEY))
            attributes.remove(VCFConstants.ALLELE_COUNT_KEY);
        if (attributes.containsKey(VCFConstants.ALLELE_FREQUENCY_KEY))
            attributes.remove(VCFConstants.ALLELE_FREQUENCY_KEY);
        if (attributes.containsKey(VCFConstants.ALLELE_NUMBER_KEY))
            attributes.remove(VCFConstants.ALLELE_NUMBER_KEY);
        return attributes;
    }

    if (vc.hasGenotypes()) {
        attributes.put(VCFConstants.ALLELE_NUMBER_KEY, AN);

        // if there are alternate alleles, record the relevant tags
        if (!vc.getAlternateAlleles().isEmpty()) {
            ArrayList<Double> alleleFreqs = new ArrayList<Double>();
            ArrayList<Integer> alleleCounts = new ArrayList<Integer>();
            ArrayList<Integer> foundersAlleleCounts = new ArrayList<Integer>();
            double totalFoundersChromosomes = (double) vc.getCalledChrCount(founderIds);
            int foundersAltChromosomes;
            for (Allele allele : vc.getAlternateAlleles()) {
                foundersAltChromosomes = vc.getCalledChrCount(allele, founderIds);
                alleleCounts.add(vc.getCalledChrCount(allele));
                foundersAlleleCounts.add(foundersAltChromosomes);
                if (AN == 0) {
                    alleleFreqs.add(0.0);
                } else {
                    final Double freq = (double) foundersAltChromosomes / totalFoundersChromosomes;
                    alleleFreqs.add(freq);
                }
            }

            attributes.put(VCFConstants.ALLELE_COUNT_KEY,
                    alleleCounts.size() == 1 ? alleleCounts.get(0) : alleleCounts);
            attributes.put(VCFConstants.ALLELE_FREQUENCY_KEY,
                    alleleFreqs.size() == 1 ? alleleFreqs.get(0) : alleleFreqs);
        } else {
            // if there's no alt AC and AF shouldn't be present
            attributes.remove(VCFConstants.ALLELE_COUNT_KEY);
            attributes.remove(VCFConstants.ALLELE_FREQUENCY_KEY);
        }
    }

    return attributes;
}

From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java

/**
 * ?URL??GET//  w w  w  .  j  av  a 2  s  .  co m
 * 
 * @param client httpclient
 * @param url ??URL
 * @param param ?? name1=value1&name2=value2 ?
 * @return URL ??
 */
public static String sendGet(HttpClient client, String url, Map<String, String> params) {
    if (client == null || StringUtils.isBlank(url)) {
        throw new IllegalArgumentException("client is null");
    }
    if (params == null) {
        params = new HashMap<String, String>(1);
    }

    String newUrl = processPlaceHolder(url, params);
    String cookie = params.remove(COOKIE_PARAM_NAME);

    List<String> paramList = checkUrlAndWrapParam(newUrl, params, true);
    String urlNameString = "";
    if (newUrl.contains("?")) {
        paramList.add(0, newUrl);
        urlNameString = StringUtils.join(paramList, "&");
    } else {
        urlNameString = newUrl + "?" + StringUtils.join(paramList, "&");
    }

    String prefix = "", suffix = "";
    String[] addresses = new String[] { urlNameString };
    if (urlNameString.contains("[") && urlNameString.contains("]")) {
        addresses = urlNameString.substring(urlNameString.indexOf("[") + 1, urlNameString.indexOf("]"))
                .split(" ");
        prefix = urlNameString.substring(0, urlNameString.indexOf("["));
        suffix = urlNameString.substring(urlNameString.indexOf("]") + 1);
    }
    LOGGER.info("start to send get:" + urlNameString);
    long current = System.currentTimeMillis();
    Exception ex = null;
    for (String address : addresses) {
        String requestUrl = prefix + address + suffix;
        try {
            HttpUriRequest request = RequestBuilder.get().setUri(requestUrl).build();

            if (StringUtils.isNotBlank(cookie)) {
                // ?cookie
                request.addHeader(new BasicHeader(COOKIE_PARAM_NAME, cookie));
            }
            HttpResponse response = client.execute(request);
            String content = processHttpResponse(client, response, params, true);
            LOGGER.info("end send get :" + urlNameString + " cost:" + (System.currentTimeMillis() - current));
            return content;
        } catch (Exception e) {
            ex = e;
            LOGGER.warn("send get error " + requestUrl + ",retry next one", e);
        }
    }
    throw new RuntimeException(ex);
}

From source file:com.mashape.client.http.HttpClient.java

public static <T> MashapeResponse<T> doRequest(Class<T> clazz, HttpMethod httpMethod, String url,
        Map<String, Object> parameters, ContentType contentType, ResponseType responseType,
        List<Authentication> authenticationHandlers) {
    if (authenticationHandlers == null)
        authenticationHandlers = new ArrayList<Authentication>();
    if (parameters == null)
        parameters = new HashMap<String, Object>();

    // Sanitize null parameters
    Set<String> keySet = new HashSet<String>(parameters.keySet());
    for (String key : keySet) {
        if (parameters.get(key) == null) {
            parameters.remove(key);
        }/*  www. j  a  v a  2s .  c  o m*/
    }

    List<Header> headers = new LinkedList<Header>();

    // Handle authentications
    for (Authentication authentication : authenticationHandlers) {
        if (authentication instanceof HeaderAuthentication) {
            headers.addAll(authentication.getHeaders());
        } else {
            Map<String, String> queryParameters = authentication.getQueryParameters();
            if (authentication instanceof QueryAuthentication) {
                parameters.putAll(queryParameters);
            } else if (authentication instanceof OAuth10aAuthentication) {
                if (url.endsWith("/oauth_url") == false && (queryParameters == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) {
                    throw new RuntimeException(
                            "Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values");
                }
                headers.add(new BasicHeader("x-mashape-oauth-consumerkey",
                        queryParameters.get(OAuthAuthentication.CONSUMER_KEY)));
                headers.add(new BasicHeader("x-mashape-oauth-consumersecret",
                        queryParameters.get(OAuthAuthentication.CONSUMER_SECRET)));
                headers.add(new BasicHeader("x-mashape-oauth-accesstoken",
                        queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)));
                headers.add(new BasicHeader("x-mashape-oauth-accesssecret",
                        queryParameters.get(OAuthAuthentication.ACCESS_SECRET)));

            } else if (authentication instanceof OAuth2Authentication) {
                if (url.endsWith("/oauth_url") == false && (queryParameters == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) {
                    throw new RuntimeException(
                            "Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value");
                }
                parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN));
            }
        }
    }

    headers.add(new BasicHeader("User-Agent", USER_AGENT));

    HttpUriRequest request = null;

    switch (httpMethod) {
    case GET:
        request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters));
        break;
    case POST:
        request = new HttpPost(url);
        break;
    case PUT:
        request = new HttpPut(url);
        break;
    case DELETE:
        request = new HttpDeleteWithBody(url);
        break;
    }

    for (Header header : headers) {
        request.addHeader(header);
    }

    if (httpMethod != HttpMethod.GET) {
        switch (contentType) {
        case BINARY:
            MultipartEntity entity = new MultipartEntity();
            for (Entry<String, Object> parameter : parameters.entrySet()) {
                if (parameter.getValue() instanceof File) {
                    entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue()));
                } else {
                    try {
                        entity.addPart(parameter.getKey(),
                                new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8")));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
            break;
        case FORM:
            try {
                ((HttpEntityEnclosingRequestBase) request)
                        .setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            break;
        case JSON:
            throw new RuntimeException("Not supported content type: JSON");
        }
    }

    org.apache.http.client.HttpClient client = new DefaultHttpClient();

    try {
        HttpResponse response = client.execute(request);
        MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response);
        return mashapeResponse;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alibaba.jstorm.ui.utils.UIUtils.java

public static Map readUiConfig() {
    File file = new File(confPath);

    //check whether ui config is update, if not , skip reload config
    if (!isFileModified(file)) {
        return uiConfig;
    }//w w w. j  a  v  a2s . c o  m

    // reload config
    Map ret = Utils.readStormConfig();
    ret.remove(Config.STORM_ZOOKEEPER_ROOT);
    ret.remove(Config.STORM_ZOOKEEPER_SERVERS);
    ret.remove("cluster.name");
    if (file.exists()) {
        FileInputStream fileStream;
        try {
            fileStream = new FileInputStream(file);
            Yaml yaml = new Yaml();

            Map clientConf = (Map) yaml.load(fileStream);

            if (clientConf != null) {
                ret.putAll(clientConf);
            }
        } catch (FileNotFoundException e) {
        }
        if (!ret.containsKey(Config.NIMBUS_HOST)) {
            ret.put(Config.NIMBUS_HOST, "localhost");

        }
        uiConfig = ret;
        isInitialized = false;
        //flush cluster config
        flushClusterConfig();
        //flush cluster cache
        flushClusterCache();
    }
    return uiConfig;
}

From source file:com.acc.fulfilmentprocess.test.FraudCheckIntegrationTest.java

/**
 * revert changes made {@link #beforeClass()}
 *//*w  w  w .j av a  2s  .c  o  m*/
@AfterClass
public static void afterClass() {
    LOG.debug("cleanup...");

    final ApplicationContext appCtx = Registry.getApplicationContext();

    assertTrue("Application context of type " + appCtx.getClass() + " is not a subclass of "
            + ConfigurableApplicationContext.class, appCtx instanceof ConfigurableApplicationContext);

    final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx;
    final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
    assertTrue("Bean Factory of type " + beanFactory.getClass() + " is not of type "
            + BeanDefinitionRegistry.class, beanFactory instanceof BeanDefinitionRegistry);

    //cleanup command factory
    final Map<String, CommandFactory> commandFactoryList = applicationContext
            .getBeansOfType(CommandFactory.class);
    commandFactoryList.remove("mockupCommandFactory");
    final DefaultCommandFactoryRegistryImpl commandFactoryReg = appCtx
            .getBean(DefaultCommandFactoryRegistryImpl.class);
    commandFactoryReg.setCommandFactoryList(commandFactoryList.values());
}

From source file:com.ms.commons.test.classloader.util.VelocityTemplateUtil.java

public static String mergeContent(final Map<Object, Object> context, String text) {
    StringReader sr = new StringReader(text);
    StringWriter sw = new StringWriter();
    Context c = new Context() {

        public boolean containsKey(Object key) {
            return context.containsKey(key);
        }//from   w ww.j  a  v  a2s  . c  o m

        public Object get(String key) {
            return context.get(key);
        }

        public Object[] getKeys() {
            return context.keySet().toArray();
        }

        public Object put(String key, Object value) {
            return context.put(key, value);
        }

        public Object remove(Object key) {
            return context.remove(key);
        }
    };

    try {
        VELOCITY_ENGINE.evaluate(c, sw, VelocityTemplateUtil.class.getSimpleName(), sr);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return sw.toString();
}

From source file:net.shibboleth.idp.oidc.util.OIDCUtils.java

/**
 * Build oidc server configuration model for discovery map.
 *
 * @param model the model/*  w w w.  j  a  v  a 2  s . c o m*/
 * @return the map
 */
public static Map<String, Object> buildOidcServerConfigurationModelForDiscovery(final Model model) {
    final Map<String, Object> m = Map.class.cast(model.asMap().get("entity"));
    final String baseUrl = m.get("issuer").toString();
    m.put("authorization_endpoint", baseUrl + "profile" + AuthorizeEndpoint.URL);
    m.put("token_endpoint", baseUrl + "profile" + TokenEndpoint.URL);
    m.put("userinfo_endpoint", baseUrl + "profile" + UserInfoEndpoint.URL);
    m.put("jwks_uri", baseUrl + "profile" + JWKPublishingEndpoint.URL);
    m.put("revocation_endpoint", baseUrl + "profile" + RevocationEndpoint.URL);
    m.put("introspection_endpoint", baseUrl + "profile" + IntrospectionEndpoint.URL);
    m.put("registration_endpoint", baseUrl + "profile" + DynamicRegistrationEndpoint.URL);
    m.remove("service_documentation");
    m.remove("op_policy_uri");
    m.remove("op_tos_uri");
    return m;
}

From source file:cascading.flow.hadoop.util.HadoopUtil.java

public static Configuration removePropertiesFrom(Configuration jobConf, String... keys) {
    Map<Object, Object> properties = createProperties(jobConf);

    for (String key : keys)
        properties.remove(key);

    return copyConfiguration(properties, new JobConf());
}