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:org.LexGrid.LexBIG.caCore.utils.LexEVSCaCoreUtils.java

public static <T> T recurseReflect(final T obj, final DoInReflectionCallback callback) {
    if (obj == null) {
        return null;
    }//from   w  ww  .  ja v a2s . co m
    ReflectionUtils.doWithFields(obj.getClass(), new FieldCallback() {

        public void doWith(Field arg0) throws IllegalArgumentException, IllegalAccessException {

            if (!ClassUtils.isPrimitiveOrWrapper(arg0.getType()) && !ClassUtils.isPrimitiveArray(arg0.getType())
                    && !ClassUtils.isPrimitiveWrapperArray(arg0.getType()) && !arg0.getType().isEnum()
                    && (isLexBigClass(arg0.getType()) || Collection.class.isAssignableFrom(arg0.getType())
                            || Map.class.isAssignableFrom(arg0.getType()))) {

                arg0.setAccessible(true);
                Object recurse = arg0.get(obj);

                if (recurse != null) {

                    if (CycleDetectingCallback.class.isAssignableFrom(recurse.getClass())) {
                        System.out.println("ere");
                    }

                    if (Collection.class.isAssignableFrom(recurse.getClass())) {
                        Collection collection = (Collection) recurse;
                        for (Object o : collection) {
                            if (callback.actionRequired(o)) {
                                collection.remove(o);
                                collection.add(recurseReflect(o, callback));
                            } else {
                                recurseReflect(o, callback);
                            }
                        }
                    } else if (Map.class.isAssignableFrom(recurse.getClass())) {
                        Map map = (Map) recurse;
                        for (Object key : map.keySet()) {
                            Object value = map.get(key);
                            if (callback.actionRequired(key) || callback.actionRequired(value)) {
                                map.remove(key);
                                map.put(recurseReflect(key, callback), recurseReflect(value, callback));
                            } else {
                                recurseReflect(key, callback);
                                recurseReflect(value, callback);
                            }
                        }
                    } else {
                        if (callback.actionRequired(recurse)) {
                            Object newObject = recurseReflect(recurse, callback);
                            arg0.set(obj, newObject);
                        } else {
                            recurseReflect(recurse, callback);
                        }
                    }
                }
            }
        }
    });

    return callback.doInReflection(obj);
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 * @param requestContext a RequestContext object associated with the request
 *
 * @return a decoded RestRequest//ww  w  . j  a  v  a  2 s. c o m
 */
public static RestRequest decode(final RestRequest request, RequestContext requestContext)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                Object content = part.getContent();
                if (content instanceof MimeMultipart) {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ((MimeMultipart) content).writeTo(os);
                    entity = os.toByteArray();
                } else {
                    entity = IOUtils.toByteArray((InputStream) content);
                }
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true);

    return requestBuilder.build();
}

From source file:ch.sdi.core.impl.cfg.ConfigUtils.java

/**
 * @param aEnv/*from w w w .  j a v a2 s. c o  m*/
 * @param aKey
 * @param aValue
 * @throws SdiException
 */
public static void addToEnvironment(ConfigurableEnvironment aEnv, String aKey, Object aValue)
        throws SdiException {
    Map<String, Object> map = getOrCreatePropertySource(aEnv, PROP_SOURCE_NAME_DYNAMIC);

    myLog.debug("setting property " + aKey + " = " + aValue + " into the environment");
    map.remove(aKey);
    map.put(aKey, aValue);
}

From source file:azkaban.reportal.util.ReportalHelper.java

public static void unSubscribeProject(AzkabanWebServer server, Project project, User user)
        throws ProjectManagerException {
    @SuppressWarnings("unchecked")
    Map<String, String> subscription = (Map<String, String>) project.getMetadata().get("subscription");
    if (subscription == null) {
        return;//w w w. j av a  2 s.c  o m
    }
    subscription.remove(user.getUserId());
    project.getMetadata().put("subscription", subscription);
    updateProjectNotifications(project, server.getProjectManager());
    server.getProjectManager().updateProjectSetting(project);
}

From source file:Maps.java

public static <K, V> Map<K, V> remove(Map<K, V> map, K key) {
    switch (map.size()) {
    case 0:/*from w w w.  ja  va 2  s . c om*/
        // Empty
        return map;
    case 1:
        // Singleton -> Empty
        if (map.containsKey(key)) {
            return create();
        }
        return map;
    case 2:
        // HashMap -> Singleton
        if (map.containsKey(key)) {
            map.remove(key);
            key = map.keySet().iterator().next();
            return create(key, map.get(key));
        }
        return map;
    default:
        // IdentityHashMap
        map.remove(key);
        return map;
    }
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Compares the given two objects./*w ww  .ja  va  2 s  . co  m*/
 * 
 * @param sourceOjbect
 *            the source ojbect
 * @param objectToCompare
 *            the object to compare
 * @return true, if successful otherwise false
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
@SuppressWarnings("rawtypes")
public static boolean compare(Object sourceOjbect, Object objectToCompare)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (sourceOjbect == null || objectToCompare == null
            || !sourceOjbect.getClass().equals(objectToCompare.getClass())) {
        throw new IllegalArgumentException("Object should not be null and be the same type.");
    }
    Map beanDescription = BeanUtils.describe(sourceOjbect);
    beanDescription.remove("class");
    Map clonedBeanDescription = BeanUtils.describe(objectToCompare);
    clonedBeanDescription.remove("class");
    for (Object key : beanDescription.keySet()) {
        if (compareTo(sourceOjbect, objectToCompare, key.toString()) != 0) {
            return false;
        }
    }
    return true;
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Gets the compare to result.//www  .  jav a  2  s  .  c o  m
 * 
 * @param sourceOjbect
 *            the source ojbect
 * @param objectToCompare
 *            the object to compare
 * @return the compare to result
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
@SuppressWarnings("rawtypes")
public static Map<String, Integer> getCompareToResult(Object sourceOjbect, Object objectToCompare)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (sourceOjbect == null || objectToCompare == null
            || !sourceOjbect.getClass().equals(objectToCompare.getClass())) {
        throw new IllegalArgumentException("Object should not be null and be the same type.");
    }
    Map beanDescription = BeanUtils.describe(sourceOjbect);
    beanDescription.remove("class");
    Map clonedBeanDescription = BeanUtils.describe(objectToCompare);
    clonedBeanDescription.remove("class");
    Map<String, Integer> compareResult = new HashMap<String, Integer>();
    for (Object key : beanDescription.keySet()) {
        compareResult.put(key.toString(),
                Integer.valueOf(compareTo(sourceOjbect, objectToCompare, key.toString())));
    }
    return compareResult;
}

From source file:com.hurence.logisland.util.string.StringUtilsTest.java

/**
 * Sets an environment variable FOR THE CURRENT RUN OF THE JVM
 * Does not actually modify the system's environment variables,
 *  but rather only the copy of the variables that java has taken,
 *  and hence should only be used for testing purposes!
 * @param key The Name of the variable to set
 * @param value The value of the variable to set
 *//*from  ww  w. j  av  a 2  s  .co  m*/
@SuppressWarnings("unchecked")
public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException {
    try {
        /// we obtain the actual environment
        final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        final boolean environmentAccessibility = theEnvironmentField.isAccessible();
        theEnvironmentField.setAccessible(true);

        final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null);

        if (SystemUtils.IS_OS_WINDOWS) {
            // This is all that is needed on windows running java jdk 1.8.0_92
            if (value == null) {
                env.remove(key);
            } else {
                env.put((K) key, (V) value);
            }
        } else {
            // This is triggered to work on openjdk 1.8.0_91
            // The ProcessEnvironment$Variable is the key of the map
            final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
            final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
            final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
            convertToVariable.setAccessible(true);

            // The ProcessEnvironment$Value is the value fo the map
            final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
            final Method convertToValue = valueClass.getMethod("valueOf", String.class);
            final boolean conversionValueAccessibility = convertToValue.isAccessible();
            convertToValue.setAccessible(true);

            if (value == null) {
                env.remove(convertToVariable.invoke(null, key));
            } else {
                // we place the new value inside the map after conversion so as to
                // avoid class cast exceptions when rerunning this code
                env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));

                // reset accessibility to what they were
                convertToValue.setAccessible(conversionValueAccessibility);
                convertToVariable.setAccessible(conversionVariableAccessibility);
            }
        }
        // reset environment accessibility
        theEnvironmentField.setAccessible(environmentAccessibility);

        // we apply the same to the case insensitive environment
        final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
        final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        if (value == null) {
            // remove if null
            cienv.remove(key);
        } else {
            cienv.put(key, value);
        }
        theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
    } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException
            | InvocationTargetException e) {
        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">",
                e);
    } catch (final NoSuchFieldException e) {
        // we could not find theEnvironment
        final Map<String, String> env = System.getenv();
        Stream.of(Collections.class.getDeclaredClasses())
                // obtain the declared classes of type $UnmodifiableMap
                .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> {
                    try {
                        return c1.getDeclaredField("m");
                    } catch (final NoSuchFieldException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + "> when locating in-class memory map of environment", e1);
                    }
                }).forEach(field -> {
                    try {
                        final boolean fieldAccessibility = field.isAccessible();
                        field.setAccessible(true);
                        // we obtain the environment
                        final Map<String, String> map = (Map<String, String>) field.get(env);
                        if (value == null) {
                            // remove if null
                            map.remove(key);
                        } else {
                            map.put(key, value);
                        }
                        // reset accessibility
                        field.setAccessible(fieldAccessibility);
                    } catch (final ConcurrentModificationException e1) {
                        // This may happen if we keep backups of the environment before calling this method
                        // as the map that we kept as a backup may be picked up inside this block.
                        // So we simply skip this attempt and continue adjusting the other maps
                        // To avoid this one should always keep individual keys/value backups not the entire map
                        System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#"
                                + field.getName() + e1);
                    } catch (final IllegalAccessException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + ">. Unable to access field!", e1);
                    }
                });
    }
    System.out.println(
            "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key));
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Gets the changed data.//from   w  w w .  j  a v  a  2  s. co m
 * 
 * @param sourceOjbect
 *            the source ojbect
 * @param objectToCompare
 *            the object to compare
 * @return the changed data
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
@SuppressWarnings("rawtypes")
public static List<ChangedAttributeResult> getChangedData(Object sourceOjbect, Object objectToCompare)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (sourceOjbect == null || objectToCompare == null
            || !sourceOjbect.getClass().equals(objectToCompare.getClass())) {
        throw new IllegalArgumentException("Object should not be null and be the same type.");
    }
    Map beanDescription = BeanUtils.describe(sourceOjbect);
    beanDescription.remove("class");
    Map clonedBeanDescription = BeanUtils.describe(objectToCompare);
    clonedBeanDescription.remove("class");
    List<ChangedAttributeResult> changedData = new ArrayList<ChangedAttributeResult>();
    for (Object key : beanDescription.keySet()) {
        if (compareTo(sourceOjbect, objectToCompare, key.toString()) != 0) {
            Object sourceAttribute = beanDescription.get(key);
            Object changedAttribute = clonedBeanDescription.get(key);
            changedData.add(new ChangedAttributeResult(key, sourceAttribute, changedAttribute));
        }
    }
    return changedData;
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Compares the given two objects and gets the changed data.
 * /*from  w  w  w  .j  a v a  2 s . c  o m*/
 * @param sourceOjbect
 *            the source ojbect
 * @param objectToCompare
 *            the object to compare
 * @return the changed data
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
@SuppressWarnings("rawtypes")
public static Map<Object, ChangedAttributeResult> getChangedDataMap(Object sourceOjbect, Object objectToCompare)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (sourceOjbect == null || objectToCompare == null
            || !sourceOjbect.getClass().equals(objectToCompare.getClass())) {
        throw new IllegalArgumentException("Object should not be null and be the same type.");
    }
    Map beanDescription = BeanUtils.describe(sourceOjbect);
    beanDescription.remove("class");
    Map clonedBeanDescription = BeanUtils.describe(objectToCompare);
    clonedBeanDescription.remove("class");
    Map<Object, ChangedAttributeResult> changedData = new HashMap<Object, ChangedAttributeResult>();
    for (Object key : beanDescription.keySet()) {
        Object sourceAttribute = beanDescription.get(key);
        Object changedAttribute = clonedBeanDescription.get(key);
        if (compareTo(sourceOjbect, objectToCompare, key.toString()) != 0) {
            changedData.put(key, new ChangedAttributeResult(key, sourceAttribute, changedAttribute));
        }
    }
    return changedData;
}