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:net.opentsdb.tsd.GraphHandler.java

/**
 * Pops out of the query string the given parameter.
 * @param querystring The query string.//from www  . jav a  2 s . co  m
 * @param param The name of the parameter to pop out.
 * @return {@code null} if the parameter wasn't passed, otherwise the
 * value of the last occurrence of the parameter.
 */
private static String popParam(final Map<String, List<String>> querystring, final String param) {
    final List<String> params = querystring.remove(param);
    if (params == null) {
        return null;
    }
    return params.get(params.size() - 1);
}

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

/**
 * Authenticate using S3-spec query string authentication
 *
 * @param httpRequest//w  ww. j av  a2  s .  co  m
 * @throws com.eucalyptus.objectstorage.exceptions.s3.AccessDeniedException
 */
static void authenticateQueryString(MappingHttpRequest httpRequest) throws S3Exception {
    // Standard S3 query string authentication
    Map<String, String> parameters = httpRequest.getParameters();
    String verb = httpRequest.getMethod().getName();
    String content_md5 = httpRequest.getHeader("Content-MD5");
    content_md5 = content_md5 == null ? "" : content_md5;
    String content_type = httpRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE);
    content_type = content_type == null ? "" : content_type;
    String addrString = getS3AddressString(httpRequest, true);
    String accessKeyId = parameters.remove(SecurityParameter.AWSAccessKeyId.toString());

    try {
        // Parameter url decode happens during MappingHttpRequest construction.
        String signature = parameters.remove(SecurityParameter.Signature.toString());
        if (signature == null) {
            throw new InvalidSecurityException("No signature found");
        }
        String expires = parameters.remove(SecurityParameter.Expires.toString());
        if (expires == null) {
            throw new InvalidSecurityException("Expiration parameter must be specified.");
        }
        String securityToken = parameters.get(ObjectStorageProperties.X_AMZ_SECURITY_TOKEN);

        if (checkExpires(expires)) {
            String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(httpRequest, true);
            String stringToSign = verb + "\n" + content_md5 + "\n" + content_type + "\n"
                    + Long.parseLong(expires) + "\n" + canonicalizedAmzHeaders + addrString;
            try {
                SecurityContext
                        .getLoginContext(new ObjectStorageWrappedCredentials(httpRequest.getCorrelationId(),
                                stringToSign, accessKeyId, signature, securityToken))
                        .login();
            } catch (Exception ex) {
                // Try adding back the '/services/objectStorage' portion of the addrString and retry the signature calc
                if (httpRequest.getUri().startsWith(ComponentIds.lookup(ObjectStorage.class).getServicePath())
                        || httpRequest.getUri()
                                .startsWith(ObjectStorageProperties.LEGACY_WALRUS_SERVICE_PATH)) {
                    try {
                        String modifiedAddrString = getS3AddressString(httpRequest, false);
                        stringToSign = verb + "\n" + content_md5 + "\n" + content_type + "\n"
                                + Long.parseLong(expires) + "\n" + canonicalizedAmzHeaders + modifiedAddrString;
                        SecurityContext.getLoginContext(
                                new ObjectStorageWrappedCredentials(httpRequest.getCorrelationId(),
                                        stringToSign, accessKeyId, signature, securityToken))
                                .login();
                    } catch (Exception ex2) {
                        LOG.error("CorrelationId: " + httpRequest.getCorrelationId()
                                + " authentication failed due to signature mismatch:", ex2);
                        throw new SignatureDoesNotMatchException(stringToSign);
                    }
                } else {
                    LOG.error("CorrelationId: " + httpRequest.getCorrelationId()
                            + " authentication failed due to signature mismatch:", ex);
                    throw new SignatureDoesNotMatchException(stringToSign);
                }
            }
        } else {
            throw new AccessDeniedException("Cannot process request. Expired.");
        }
    } catch (Exception ex) {
        throw new AccessDeniedException("Could not verify request " + ex.getMessage());
    }
}

From source file:org.elasticsearch.client.RestClientTestCase.java

/**
 * Assert that the actual headers are the expected ones given the original default and request headers. Some headers can be ignored,
 * for instance in case the http client is adding its own automatically.
 *
 * @param defaultHeaders the default headers set to the REST client instance
 * @param requestHeaders the request headers sent with a particular request
 * @param actualHeaders the actual headers as a result of the provided default and request headers
 * @param ignoreHeaders header keys to be ignored as they are not part of default nor request headers, yet they
 *                      will be part of the actual ones
 *///from  w w  w .  ja  v  a  2 s .  c om
protected static void assertHeaders(final Header[] defaultHeaders, final Header[] requestHeaders,
        final Header[] actualHeaders, final Set<String> ignoreHeaders) {
    final Map<String, List<String>> expectedHeaders = new HashMap<>();
    final Set<String> requestHeaderKeys = new HashSet<>();
    for (final Header header : requestHeaders) {
        final String name = header.getName();
        addValueToListEntry(expectedHeaders, name, header.getValue());
        requestHeaderKeys.add(name);
    }
    for (final Header defaultHeader : defaultHeaders) {
        final String name = defaultHeader.getName();
        if (requestHeaderKeys.contains(name) == false) {
            addValueToListEntry(expectedHeaders, name, defaultHeader.getValue());
        }
    }
    Set<String> actualIgnoredHeaders = new HashSet<>();
    for (Header responseHeader : actualHeaders) {
        final String name = responseHeader.getName();
        if (ignoreHeaders.contains(name)) {
            expectedHeaders.remove(name);
            actualIgnoredHeaders.add(name);
            continue;
        }
        final String value = responseHeader.getValue();
        final List<String> values = expectedHeaders.get(name);
        assertNotNull("found response header [" + name + "] that wasn't originally sent: " + value, values);
        assertTrue("found incorrect response header [" + name + "]: " + value, values.remove(value));
        if (values.isEmpty()) {
            expectedHeaders.remove(name);
        }
    }
    assertEquals("some headers meant to be ignored were not part of the actual headers", ignoreHeaders,
            actualIgnoredHeaders);
    assertTrue("some headers that were sent weren't returned " + expectedHeaders, expectedHeaders.isEmpty());
}

From source file:com.sworddance.util.CUtilities.java

/**
 * This is a safe put when using {@link java.util.concurrent.ConcurrentMap} which throw exceptions if key or value is null
 * @param <K>//from www .  j ava2 s  .  co  m
 * @param <T>
 * @param map if null then nothing happens
 * @param key if null then nothing happens
 * @param value if null then {@link Map#remove(Object)} is called, otherwise
 * @return map.{@link Map#put(Object, Object)}
 */
public static <K, T> T put(Map<K, T> map, K key, T value) {
    if (map != null && key != null) {
        if (value == null) {
            return map.remove(key);
        } else {
            return map.put(key, value);
        }
    } else {
        return null;
    }
}

From source file:org.apache.hive.jdbc.Utils.java

/**
 * Remove the deprecatedName param from the fromMap and put the key value in the toMap.
 * Also log a deprecation message for the client.
 * @param fromMap/*  www .j a  v  a2  s  . c  o  m*/
 * @param toMap
 * @param deprecatedName
 * @param newName
 * @param newUsage
 */
private static void handleParamDeprecation(Map<String, String> fromMap, Map<String, String> toMap,
        String deprecatedName, String newName, String newUsage) {
    if (fromMap.containsKey(deprecatedName)) {
        LOG.warn("***** JDBC param deprecation *****");
        LOG.warn("The use of " + deprecatedName + " is deprecated.");
        LOG.warn("Please use " + newName + " like so: " + newUsage);
        String paramValue = fromMap.remove(deprecatedName);
        toMap.put(newName, paramValue);
    }
}

From source file:com.chiorichan.util.WebFunc.java

@SuppressWarnings("unchecked")
public static String createTable(Map<Object, Object> tableData, Collection<String> headerArray, String tableId,
        String altTableClass) {/*from  ww w  .  j a  v a2  s . co m*/
    if (tableId == null)
        tableId = "";

    if (tableData == null)
        return "";

    if (altTableClass == null || altTableClass.isEmpty())
        altTableClass = "altrowstable";

    StringBuilder sb = new StringBuilder();
    int x = 0;
    sb.append("<table id=\"" + tableId + "\" class=\"" + altTableClass + "\">\n");

    if (headerArray != null) {
        sb.append("<tr>\n");
        for (String col : headerArray)
            sb.append("<th>" + col + "</th>\n");
        sb.append("</tr>\n");
    }

    int colLength = headerArray != null ? headerArray.size() : tableData.size();
    for (Object row : tableData.values())
        if (row instanceof Map)
            colLength = Math.max(((Map<String, Object>) row).size(), colLength);

    for (Object row : tableData.values()) {
        String clss = x % 2 == 0 ? "evenrowcolor" : "oddrowcolor";
        x++;

        if (row instanceof Map || row instanceof Collection) {
            Map<Object, Object> map = Maps.newLinkedHashMap();

            if (row instanceof Map)
                map = (Map<Object, Object>) row;
            else {
                int y = 0;
                for (Object o : (Collection<Object>) row) {
                    map.put(Integer.toString(y), o);
                    y++;
                }
            }

            sb.append("<tr");

            for (Entry<Object, Object> e : map.entrySet())
                try {
                    if (ObjectFunc.castToStringWithException(e.getKey()).startsWith(":")) {
                        map.remove(e.getKey());
                        sb.append(" " + ObjectFunc.castToStringWithException(e.getKey()).substring(1) + "=\""
                                + ObjectFunc.castToStringWithException(e.getValue()) + "\"");
                    }
                } catch (ClassCastException ex) {
                    ex.printStackTrace();
                }

            sb.append(" class=\"" + clss + "\">\n");

            if (map.size() == 1)
                sb.append("<td style=\"text-align: center; font-weight: bold;\" class=\"\" colspan=\""
                        + colLength + "\">" + map.get(0) + "</td>\n");
            else {
                int cc = 0;
                for (Object col : map.values())
                    if (col != null) {
                        String subclass = col instanceof String && ((String) col).isEmpty() ? " emptyCol" : "";
                        sb.append("<td id=\"col_" + cc + "\" class=\"" + subclass + "\">" + col + "</td>\n");
                        cc++;
                    }
            }
            sb.append("</tr>\n");
        } else if (row instanceof String)
            sb.append("<tr><td class=\"" + clss + "\" colspan=\"" + colLength + "\"><b><center>" + (String) row
                    + "</b></center></td></tr>\n");
        else
            sb.append("<tr><td class=\"" + clss + "\" colspan=\"" + colLength + "\"><b><center>"
                    + row.toString() + "</b></center></td></tr>\n");
    }
    sb.append("</table>\n");

    return sb.toString();
}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Obtain collection of Parameters from request
 *
 * @param httpServletRequest/*from  ww  w  . j a v  a 2  s .  c  o m*/
 * @return
 * @throws Exception
 */
public static Map<String, String[]> mapUrlEncodedParameters(HttpServletRequest httpServletRequest)
        throws Exception {

    InputStream body = httpServletRequest.getInputStream();
    java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A");
    Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();

    try {
        if (s.hasNext()) {
            String requestData = s.next();
            String[] splitRequestData = requestData.split("&");
            for (String requestPart : splitRequestData) {
                String[] parts = requestPart.split("=");
                ArrayList<String> values = new ArrayList<String>();
                if (mapPostParameters.containsKey(parts[0])) {
                    values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(parts[0])));
                    mapPostParameters.remove(parts[0]);
                }

                if (parts.length > 1) {
                    values.add(parts[1]);
                }

                mapPostParameters.put(parts[0], values.toArray(new String[values.size()]));
            }
        }
    } catch (Exception e) {
        throw new Exception("Could not parse request data: " + e.getMessage());
    }

    return mapPostParameters;
}

From source file:com.zimbra.cs.service.formatter.VCard.java

private static void removeField(String firstKey, boolean skipFirstKey, int firstSuffix,
        Map<String, String> fields) {
    if (!skipFirstKey) {
        fields.remove(firstKey);
    }/*from w w  w.  j a v  a 2  s  .c  om*/
    for (int suffix = firstSuffix; suffix < 20; suffix++) {
        String trialKey = new StringBuilder(firstKey).append(String.valueOf(suffix)).toString();
        if (fields.remove(trialKey) == null) {
            break;
        }
    }
}

From source file:com.day.cq.wcm.foundation.forms.FormResourceEdit.java

/**
 * Performs a Sling POST servlet modify operation, but on multiple
 * resources./*w w  w  .j  av a2 s . com*/
 * <p>
 * The Sling POST servlet (more specifically, its modify operation) itself
 * can only handle a single resource (using the request resource) or by
 * using absolute paths to properties. This method will automatically
 * rewrite the parameters for the multiple resources and then call the Sling
 * POST servlet. All resources will be changed in a single transaction. The
 * response will look like the standard Sling POST response.
 * 
 * @param resources
 *            list of resources to bulk-edit
 * @param request
 *            current POST request, including the parameters for the Sling
 *            POST servlet
 * @param response
 *            current response
 * @throws ServletException
 * @throws IOException
 */
public static void multiPost(List<Resource> resources, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws ServletException, IOException {
    // 1. rewrite request params

    final RequestParameterMap originalParams = request.getRequestParameterMap();

    // group params by their property
    //
    // foo => foo = 1.1.2011
    //        foo@Delete = x
    //        foo@TypeHint = Date
    // bar => bar = test
    // ...
    Map<String, Map<String, RequestParameter[]>> groupedParams = new TreeMap<String, Map<String, RequestParameter[]>>();

    // 1. collect params, identify which to consider for writing

    boolean requireItemPrefix = false;

    Set<String> paramsToKeep = new HashSet<String>();
    Set<String> paramsToRemove = new HashSet<String>();

    for (Entry<String, RequestParameter[]> param : originalParams.entrySet()) {
        final String name = param.getKey();

        if (RP_OPERATION.equals(name)) {
            String op = originalParams.getValue(name).getString();
            // abort if operation is not modify as we can't bulk create/copy/move/checkin/checkout
            if (!"modify".equals(op)) {
                throw new ServletException(
                        "Only :operation=modify can be used when posting to multiple resources (was: '" + op
                                + "')");
            }
        }

        if (name.startsWith(ITEM_PREFIX_RELATIVE_CURRENT)) {
            requireItemPrefix = true;
        }

        // if param name ends with "@something", the property name is the part before it
        final int pos = name.indexOf("@");
        String propName = pos >= 0 ? name.substring(0, pos) : name;

        // add to map or use already existing entry for this property
        Map<String, RequestParameter[]> map = groupedParams.get(propName);
        if (map == null) {
            groupedParams.put(propName, map = new TreeMap<String, RequestParameter[]>());
        }
        map.put(name, param.getValue());

        // properties to write end with @Write
        if (name.endsWith(WRITE_SUFFIX)) {
            paramsToKeep.add(propName);
            map.remove(name); // we don't need the "@Write" param in the sling post servlet
        }

        // remove form params (for cleaner request, technically not needed, as they are ignored by sling anyway)
        if (FormsConstants.REQUEST_PROPERTY_FORMID.equals(name)
                || FormsConstants.REQUEST_PROPERTY_FORM_START.equals(name) || RESOURCES_PARAM.equals(name)) {
            continue;
        }

        // all special :something sling post params must be kept
        if (name.startsWith(RP_PREFIX)) {
            paramsToKeep.add(name);
        }

        // @MoveFrom must be ignored (doesn't work for multiple resources)
        if (name.endsWith(SUFFIX_MOVE_FROM)) {
            paramsToRemove.add(propName);
        }
    }

    // 2. remove params that should not be written

    for (Iterator<String> iter = groupedParams.keySet().iterator(); iter.hasNext();) {
        String name = iter.next();
        if (!paramsToKeep.contains(name) || paramsToRemove.contains(name)) {
            iter.remove();
        }
    }

    // 3. rewrite params for each resource

    ParameterMap params = new ParameterMap();

    log.debug("posting to multiple resources:");

    boolean first = true;
    for (Resource r : resources) {
        String path = r.getPath();
        log.debug("{}", path);

        for (Map<String, RequestParameter[]> p : groupedParams.values()) {
            for (Entry<String, RequestParameter[]> param : p.entrySet()) {
                String name = param.getKey();

                // include :params and absolute paths only once and don't rewrite them
                if (name.startsWith(RP_PREFIX) || name.startsWith(ITEM_PREFIX_ABSOLUTE)) {
                    if (first) {
                        params.put(name, param.getValue());
                    }
                } else if (requireItemPrefix) {
                    // only use params with item prefix (and skip others)
                    if (name.startsWith(ITEM_PREFIX_RELATIVE_CURRENT)) {
                        params.put(path + "/" + name.substring(ITEM_PREFIX_RELATIVE_CURRENT.length()),
                                param.getValue());
                    } else if (name.startsWith(ITEM_PREFIX_RELATIVE_PARENT)) {
                        path = Text.getRelativeParent(path, 1);
                        params.put(path + "/" + name.substring(ITEM_PREFIX_RELATIVE_PARENT.length()),
                                param.getValue());
                    }
                } else /* if (!requireItemPrefix) */ {
                    // rewrite all params
                    params.put(path + "/" + name, param.getValue());
                }
            }
        }
        first = false;
    }

    if (log.isDebugEnabled()) {
        log.debug("rewritten parameters:");
        logParams(params);
    }

    // 4. send new internal request to sling post servlet

    // forward but make sure we remove the "forms" selector and the suffix
    RequestDispatcherOptions options = new RequestDispatcherOptions();
    options.setReplaceSelectors("");
    options.setReplaceSuffix("");
    RequestDispatcher dispatcher = request.getRequestDispatcher(request.getResource(), options);
    dispatcher.forward(new CustomParameterRequest(request, params), response);
}

From source file:com.zimbra.cs.service.formatter.VCard.java

private static void removeVCardFields(Map<String, String> fields) {
    fields.remove(ContactConstants.A_fullName);
    fields.remove(ContactConstants.A_company);
    fields.remove(ContactConstants.A_lastName);
    fields.remove(ContactConstants.A_firstName);
    fields.remove(ContactConstants.A_middleName);
    fields.remove(ContactConstants.A_namePrefix);
    fields.remove(ContactConstants.A_nameSuffix);
    fields.remove(ContactConstants.A_nickname);
    fields.remove(ContactConstants.A_image);
    fields.remove(ContactConstants.A_birthday);
    fields.remove(ContactConstants.A_company);
    fields.remove(ContactConstants.A_department);
    fields.remove(ContactConstants.A_jobTitle);
    fields.remove(ContactConstants.A_notes);
    fields.remove(ContactConstants.A_type);
    fields.remove(ContactConstants.A_groupMember);
    fields.remove(ContactConstants.A_vCardXProps);

    removeField(ContactConstants.A_homeStreet, false, 2, fields);
    removeField(ContactConstants.A_homeCity, false, 2, fields);
    removeField(ContactConstants.A_homeState, false, 2, fields);
    removeField(ContactConstants.A_homePostalCode, false, 2, fields);
    removeField(ContactConstants.A_homeCountry, false, 2, fields);
    removeField(ContactConstants.A_workStreet, false, 2, fields);
    removeField(ContactConstants.A_workCity, false, 2, fields);
    removeField(ContactConstants.A_workState, false, 2, fields);
    removeField(ContactConstants.A_workPostalCode, false, 2, fields);
    removeField(ContactConstants.A_workCountry, false, 2, fields);
    removeField(ContactConstants.A_otherStreet, false, 2, fields);
    removeField(ContactConstants.A_otherCity, false, 2, fields);
    removeField(ContactConstants.A_otherState, false, 2, fields);
    removeField(ContactConstants.A_otherPostalCode, false, 2, fields);
    removeField(ContactConstants.A_otherCountry, false, 2, fields);

    removeField(ContactConstants.A_carPhone, false, 2, fields);
    removeField(ContactConstants.A_homeFax, false, 2, fields);
    removeField(ContactConstants.A_homePhone, false, 2, fields);
    removeField(ContactConstants.A_mobilePhone, false, 2, fields);
    removeField(ContactConstants.A_otherFax, false, 2, fields);
    removeField(ContactConstants.A_otherPhone, false, 2, fields);
    removeField(ContactConstants.A_pager, false, 2, fields);
    removeField(ContactConstants.A_workFax, false, 2, fields);
    removeField(ContactConstants.A_workPhone, false, 2, fields);
    removeField(ContactConstants.A_email, false, 2, fields);

    removeField(ContactConstants.A_homeURL, false, 2, fields);
    removeField(ContactConstants.A_otherURL, false, 2, fields);
    removeField(ContactConstants.A_workURL, false, 2, fields);

    removeField("workEmail", true, 1, fields);
}