Example usage for java.util Map getClass

List of usage examples for java.util Map getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.springframework.beans.TypeConverterDelegate.java

@SuppressWarnings("unchecked")
private Map<?, ?> convertToTypedMap(Map<?, ?> original, @Nullable String propertyName, Class<?> requiredType,
        @Nullable TypeDescriptor typeDescriptor) {

    if (!Map.class.isAssignableFrom(requiredType)) {
        return original;
    }/*from w  w  w.  ja v  a 2s.c o m*/

    boolean approximable = CollectionFactory.isApproximableMapType(requiredType);
    if (!approximable && !canCreateCopy(requiredType)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Custom Map type [" + original.getClass().getName()
                    + "] does not allow for creating a copy - injecting original Map as-is");
        }
        return original;
    }

    boolean originalAllowed = requiredType.isInstance(original);
    TypeDescriptor keyType = (typeDescriptor != null ? typeDescriptor.getMapKeyTypeDescriptor() : null);
    TypeDescriptor valueType = (typeDescriptor != null ? typeDescriptor.getMapValueTypeDescriptor() : null);
    if (keyType == null && valueType == null && originalAllowed
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Iterator<?> it;
    try {
        it = original.entrySet().iterator();
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Map of type [" + original.getClass().getName()
                    + "] - injecting original Map as-is: " + ex);
        }
        return original;
    }

    Map<Object, Object> convertedCopy;
    try {
        if (approximable) {
            convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
        } else {
            convertedCopy = (Map<Object, Object>) ReflectionUtils.accessibleConstructor(requiredType)
                    .newInstance();
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot create copy of Map type [" + original.getClass().getName()
                    + "] - injecting original Map as-is: " + ex);
        }
        return original;
    }

    while (it.hasNext()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
        String keyedPropertyName = buildKeyedPropertyName(propertyName, key);
        Object convertedKey = convertIfNecessary(keyedPropertyName, null, key,
                (keyType != null ? keyType.getType() : null), keyType);
        Object convertedValue = convertIfNecessary(keyedPropertyName, null, value,
                (valueType != null ? valueType.getType() : null), valueType);
        try {
            convertedCopy.put(convertedKey, convertedValue);
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Map type [" + original.getClass().getName()
                        + "] seems to be read-only - injecting original Map as-is: " + ex);
            }
            return original;
        }
        originalAllowed = originalAllowed && (key == convertedKey) && (value == convertedValue);
    }
    return (originalAllowed ? original : convertedCopy);
}

From source file:de.javakaffee.kryoserializers.KryoTest.java

/**
 * Test that linked hash map is serialized correctly with the {@link CopyForIterateMapSerializer}:
 * test that insertion order is retained.
 * @throws Exception// w  w  w .j  a  va2s.  co  m
 */
@Test(enabled = true)
public void testCopyForIterateMapSerializer() throws Exception {
    final Map<Double, String> map = new LinkedHashMap<Double, String>();
    // use doubles as e.g. integers hash to the value...
    for (int i = 0; i < 10; i++) {
        map.put(Double.valueOf(String.valueOf(i) + "." + Math.abs(i)), "value: " + i);
    }
    @SuppressWarnings("unchecked")
    final Map<Double, String> deserialized = deserialize(serialize(map), map.getClass());
    assertDeepEquals(deserialized, map);
}

From source file:org.dozer.MappingProcessor.java

private Object mapMap(Object srcObj, Map srcMapValue, FieldMap fieldMap, Object destObj) {
    Map result;/* w ww.j  a v  a 2 s.co m*/
    Map destinationMap = (Map) fieldMap.getDestValue(destObj);
    if (destinationMap == null) {
        result = DestBeanCreator.create(srcMapValue.getClass());
    } else {
        result = destinationMap;
        if (fieldMap.isRemoveOrphans()) {
            result.clear();
        }
    }

    for (Entry<?, Object> srcEntry : ((Map<?, Object>) srcMapValue).entrySet()) {
        Object srcEntryValue = srcEntry.getValue();

        if (srcEntryValue == null) { // overwrites with null in any case
            result.put(srcEntry.getKey(), null);
            continue;
        }

        Object destEntryValue = mapOrRecurseObject(srcObj, srcEntryValue, srcEntryValue.getClass(), fieldMap,
                destObj);
        Object obj = result.get(srcEntry.getKey());
        if (obj != null && obj.equals(destEntryValue) && fieldMap.isNonCumulativeRelationship()) {
            mapToDestObject(null, srcEntryValue, obj, false, null);
        } else {
            result.put(srcEntry.getKey(), destEntryValue);
        }
    }
    return result;
}

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) {
    Class keyType = null;/*  w  w  w .j  ava  2s .c o m*/
    Class valueType = null;
    if (methodParam != null && JdkVersion.isAtLeastJava15()) {
        keyType = GenericCollectionTypeResolver.getMapKeyParameterType(methodParam);
        valueType = GenericCollectionTypeResolver.getMapValueParameterType(methodParam);
    }
    if (keyType == null && valueType == null
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Map convertedCopy = null;
    Iterator it = null;
    try {
        it = original.entrySet().iterator();
        if (it == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Map of type [" + original.getClass().getName()
                        + "] returned null Iterator - injecting original Map as-is");
            }
        }
        convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Map of type [" + original.getClass().getName()
                    + "] - injecting original Map as-is", ex);
        }
        return original;
    }
    boolean actuallyConverted = false;
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
        String keyedPropertyName = buildKeyedPropertyName(propertyName, key);
        if (methodParam != null) {
            methodParam.increaseNestingLevel();
            methodParam.setTypeIndexForCurrentLevel(0);
        }
        Object convertedKey = convertIfNecessary(keyedPropertyName, null, key, keyType, null, methodParam);
        if (methodParam != null) {
            methodParam.setTypeIndexForCurrentLevel(1);
        }
        Object convertedValue = convertIfNecessary(keyedPropertyName, null, value, valueType, null,
                methodParam);
        if (methodParam != null) {
            methodParam.decreaseNestingLevel();
        }
        convertedCopy.put(convertedKey, convertedValue);
        actuallyConverted = actuallyConverted || (key != convertedKey) || (value != convertedValue);
    }
    return (actuallyConverted ? convertedCopy : original);
}

From source file:ezbake.data.elastic.ElasticClientTest.java

@SuppressWarnings("unchecked")
@Test/*from   www  .j  av  a  2s . c  o m*/
public void testQueryOnFields() throws Exception {
    final SearchResult results = client.get(QueryBuilders.matchAllQuery().toString(), TEST_TYPE, null,
            Sets.newHashSet("title", "rating"), null, null, 0, (short) 10, null, COMMON_USER_TOKEN);

    assertEquals(4, results.getTotalHits());
    assertEquals(4, results.getMatchingDocumentsSize());
    Map<String, Object> map = new HashMap<>();
    for (final Document result : results.getMatchingDocuments()) {
        map = gson.fromJson(result.get_jsonObject(), map.getClass());
        assertTrue(map.keySet().contains("title"));
        assertTrue(map.keySet().contains("rating"));
    }
}

From source file:com.github.dozermapper.core.MappingProcessor.java

private Object mapMap(Object srcObj, Map srcMapValue, FieldMap fieldMap, Object destObj) {
    Map result;/*  w  ww.j a  v  a  2s  .  com*/
    Map destinationMap = (Map) fieldMap.getDestValue(destObj);
    if (destinationMap == null) {
        result = destBeanCreator.create(srcMapValue.getClass());
    } else {
        result = destinationMap;
        if (fieldMap.isRemoveOrphans()) {
            result.clear();
        }
    }

    for (Entry<?, Object> srcEntry : ((Map<?, Object>) srcMapValue).entrySet()) {
        Object srcEntryValue = srcEntry.getValue();

        if (srcEntryValue == null) { // overwrites with null in any case
            result.put(srcEntry.getKey(), null);
            continue;
        }

        Object destEntryValue = mapOrRecurseObject(srcObj, srcEntryValue, srcEntryValue.getClass(), fieldMap,
                destObj);
        Object obj = result.get(srcEntry.getKey());
        if (obj != null && obj.equals(destEntryValue) && fieldMap.isNonCumulativeRelationship()) {
            mapToDestObject(null, srcEntryValue, obj, false, null);
        } else {
            result.put(srcEntry.getKey(), destEntryValue);
        }
    }
    return result;
}

From source file:fedora.server.security.servletfilters.ExtendedHttpServletRequestWrapper.java

public final void auditOuterMap(Map map, String desc) {
    if (log.isDebugEnabled()) {
        log.debug("");
        log.debug("auditing " + desc);
        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            Object inner = map.get(key);
            String authority = "";
            if (key instanceof String) {
                authority = (String) key;
            } else {
                authority = "<authority not a string>";
            }/*  w  w w  .  j a va 2  s .c o  m*/
            if (inner instanceof Map) {
                log.debug(authority + " maps to . . .");
                auditInnerMap((Map) inner);
            } else if (inner instanceof Set) {
                log.debug(authority + " maps to . . .");
                auditInnerSet((Set) inner);
            } else {
                log.debug(authority + " maps to an unknown object==" + map.getClass().getName());
            }
        }
    }
}

From source file:org.fcrepo.server.security.servletfilters.ExtendedHttpServletRequestWrapper.java

public final void auditOuterMap(Map map, String desc) {
    if (logger.isDebugEnabled()) {
        logger.debug("");
        logger.debug("auditing " + desc);
        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            Object inner = map.get(key);
            String authority = "";
            if (key instanceof String) {
                authority = (String) key;
            } else {
                authority = "<authority not a string>";
            }//w w  w .  ja  v a 2 s .  com
            if (inner instanceof Map) {
                logger.debug(authority + " maps to . . .");
                auditInnerMap((Map) inner);
            } else if (inner instanceof Set) {
                logger.debug(authority + " maps to . . .");
                auditInnerSet((Set) inner);
            } else {
                logger.debug(authority + " maps to an unknown object==" + map.getClass().getName());
            }
        }
    }
}

From source file:lu.softec.xwiki.macro.internal.ClassRunnerMacro.java

protected String execute(ClassLoader loader, String className, ClassRunnerMacroParameters parameters,
        Object xcontext) throws MacroExecutionException {
    StringWriter stringWriter = new StringWriter();
    boolean hasArgs = (parameters.getRawProperties() != null);
    Map<String, Object> args = (hasArgs) ? parameters.getRawProperties() : new LinkedHashMap<String, Object>();

    Class<?> klass;//from  ww  w . j a va  2  s .c om
    try {
        klass = loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    Method[] methods = klass.getMethods();
    Method run1 = null;
    Method run2 = null;
    Method run3 = null;
    Method setContext1 = null;
    Method setContext2 = null;
    Method getParser = null;
    for (Method m : methods) {
        if (m.getName().equals("run")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(stringWriter.getClass())) {
                run1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                run2 = m;
            } else if (types.length == 3 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(args.getClass())
                    && types[2].isAssignableFrom(xcontext.getClass())) {
                run3 = m;
            }
        } else if (m.getName().equals("setContext")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(xcontext.getClass())) {
                setContext1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(args.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                setContext2 = m;
            }
        } else if (m.getName().equals("getParser")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 0) {
                getParser = m;
            }
        }
        if (run2 != null && run3 != null && setContext1 != null && setContext2 != null && getParser != null)
            break;
    }

    if (run2 == null && run3 == null) {
        throw new MacroExecutionException(
                "Unable to find the appropriate run(Writer,XWikiContext) or run(Writer,Map,XWikiContext) method in the class.");
    }

    try {
        Object obj = klass.newInstance();
        if (setContext2 != null && (hasArgs || setContext1 == null)) {
            setContext2.invoke(obj, args, xcontext);
        } else if (setContext1 != null) {
            setContext1.invoke(obj, xcontext);
        }
        if (setContext2 != null || setContext1 != null) {
            if (getParser != null) {
                String parser = null;
                parser = (String) getParser.invoke(obj);
                if (parser != null) {
                    parameters.setParser(parser);
                }
            }
            run1.invoke(obj, stringWriter);
        } else {
            if (run3 != null && (hasArgs || run2 == null)) {
                run3.invoke(obj, stringWriter, args, xcontext);
            } else {
                run2.invoke(obj, stringWriter, xcontext);
            }
        }
    } catch (Exception e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    return (stringWriter.toString());
}

From source file:org.cloudgraph.cassandra.service.GraphDispatcher.java

/**
 * Attempts to unlock the given datastore entity, first checking if the given
 * user has an existing or expired lock. Otherwise a warning is logged. 
 * @param entity - the datastore entity/*from ww w .  j  a v a  2s .  co m*/
 * @param dataObject - the value object
 * @param lockedDateProperty - the last locked date property definition metadata 
 * @param lockedByNameProperty - the last locked by name property definition metadata
 * @param snapshotDate - the query snapshot date
 */
private void unlock(PlasmaDataObject dataObject, Map<String, PropertyPair> entity,
        PlasmaProperty lockedDateProperty, PlasmaProperty lockedByNameProperty, Timestamp snapshotDate)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (lockedDateProperty != null && lockedByNameProperty != null) {
        PropertyPair lockedDatePair = entity.get(lockedDateProperty.getName());
        PropertyPair lockedByNamePair = entity.get(lockedByNameProperty.getName());
        String lockedByName = (String) lockedByNamePair.getValue();
        Date lockedDate = (Date) lockedDatePair.getValue();
        if (username.equals(lockedByName)) {
            if (log.isDebugEnabled()) {
                log.debug("unlocking " + entity.getClass().getSimpleName() + " (" + dataObject.getUUIDAsString()
                        + ")");
            }
            entity.put(lockedByNameProperty.getName(), new PropertyPair(lockedByNameProperty, username));
            entity.put(lockedDateProperty.getName(),
                    new PropertyPair(lockedDateProperty, this.snapshotMap.getSnapshotDate()));
        } else
            log.warn("could not unlock entity " + entity.getClass().getSimpleName() + " ("
                    + dataObject.getUUIDAsString() + ") - current user '" + username
                    + "' has no existing or expired lock");
    }
}