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:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java

public final BasicDBObject resolveToBasicDBObject() {

    BasicDBObject bDBObject = new BasicDBObject();
    try {//from w w w. j  a  v a2s.com
        Class<? extends AbstractDocument> currClass = getClass();
        while (currClass != null) {

            for (Method method : currClass.getMethods()) {
                IDocumentKeyValue dkv = method.getAnnotation(IDocumentKeyValue.class);
                String mName = method.getName();
                if (dkv != null && mName.startsWith(JPAConstants.GETTER_PREFIX)) {

                    try {
                        Object returnValue = method.invoke(this, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST);
                        char[] propertyChars = mName.substring(3).toCharArray();
                        String property = String.valueOf(propertyChars[0]).toLowerCase()
                                + String.valueOf(propertyChars, 1, propertyChars.length - 1);

                        if (returnValue == null) {
                            continue;
                        }

                        if (returnValue instanceof AbstractDocument) {

                            Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD.invoke(returnValue,
                                    JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST);
                            bDBObject.put(property, subReturnValue);

                        } else if (returnValue instanceof Enum) {

                            Enum<?> enumClass = Enum.class.cast(returnValue);
                            BasicDBObject enumObject = new BasicDBObject();

                            enumObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(),
                                    enumClass.getClass().getName());
                            enumObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), enumClass.name());

                            bDBObject.put(property, enumObject);

                        } else if (returnValue instanceof Collection) {

                            Collection<?> collectionContent = (Collection<?>) returnValue;
                            BasicDBObject collectionObject = new BasicDBObject();
                            collectionObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(),
                                    collectionContent.getClass().getName());

                            BasicDBList bDBList = new BasicDBList();
                            if (collectionContent.iterator().next() instanceof AbstractDocument) {
                                for (Object content : collectionContent) {
                                    if (content instanceof AbstractDocument) {
                                        Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD
                                                .invoke(returnValue, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST);
                                        bDBList.add(subReturnValue);
                                    }
                                }
                            } else {
                                bDBList.addAll(collectionContent);
                            }

                            collectionObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), bDBList);
                            bDBObject.put(property, collectionObject);

                        } else if (returnValue instanceof Map) {

                            Map<?, ?> mapContent = (Map<?, ?>) returnValue;
                            BasicDBObject mapObject = new BasicDBObject();
                            mapObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(),
                                    mapContent.getClass().getName());

                            Set<?> keys = mapContent.keySet();
                            if (keys.iterator().next() instanceof AbstractDocument) {

                                Map<Object, Object> convertedMap = new HashMap<Object, Object>();
                                for (Object key : keys) {
                                    Object value = mapContent.get(key);
                                    Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD.invoke(value,
                                            JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST);

                                    convertedMap.put(key, subReturnValue);
                                }

                                mapContent = convertedMap;
                            }

                            mapObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), mapContent);
                            bDBObject.put(property, mapObject);

                        } else {
                            bDBObject.put(property, returnValue);
                        }

                    } catch (Exception e) {

                    }

                }
            }

            currClass = currClass.getSuperclass().asSubclass(AbstractDocument.class);
        }

    } catch (ClassCastException castException) {

    }

    bDBObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(), getClass().getName());
    _log.info("BdBObject " + bDBObject);
    return bDBObject;
}

From source file:org.dcm4che3.conf.core.adapters.ReflectiveAdapter.java

@Override
public T fromConfigNode(Map<String, Object> configNode, AnnotatedConfigurableProperty property,
        BeanVitalizer vitalizer, Object parent) throws ConfigurationException {

    if (configNode == null)
        return null;
    Class<T> clazz = (Class<T>) property.getType();

    if (!Map.class.isAssignableFrom(configNode.getClass()))
        throw new ConfigurationException(
                "Provided configuration node is not a map (type " + clazz.getName() + ")");

    T confObj;//from   w w w.j  a  va2  s  .com
    // create instance or use provided when it was created for us
    if (providedConfObj != null)
        confObj = providedConfObj;
    else
        confObj = getRelevantConfigurableInstance(configNode, vitalizer, clazz);

    // iterate and populate annotated fields
    for (AnnotatedConfigurableProperty fieldProperty : ConfigIterators.getAllConfigurableFields(clazz))
        try {
            Object fieldValue = DefaultConfigTypeAdapters.delegateGetChildFromConfigNode(configNode,
                    fieldProperty, vitalizer, confObj);
            PropertyUtils.setSimpleProperty(confObj, fieldProperty.getName(), fieldValue);
        } catch (Exception e) {
            throw new ConfigurationException(
                    "Error while reading configuration property '" + fieldProperty.getAnnotatedName()
                            + "' (field " + fieldProperty.getName() + ") in class " + clazz.getSimpleName(),
                    e);
        }

    // iterate over setters
    for (ConfigIterators.AnnotatedSetter setter : ConfigIterators.getAllConfigurableSetters(clazz)) {
        try {
            // populate parameters for the setter
            Object[] args = new Object[setter.getParameters().size()];
            int i = 0;
            for (AnnotatedConfigurableProperty paramProperty : setter.getParameters())
                args[i++] = DefaultConfigTypeAdapters.delegateGetChildFromConfigNode(configNode, paramProperty,
                        vitalizer, confObj);

            // invoke setter
            setter.getMethod().invoke(confObj, args);
        } catch (Exception e) {
            throw new ConfigurationException("Error while trying to initialize the object with method '"
                    + setter.getMethod().getName() + "'", e);
        }
    }

    return confObj;
}

From source file:org.apache.openaz.xacml.std.json.JSONRequest.java

/**
 * Handle a List of Attributes for a Category
 *
 * @param categoryID//from  w ww  .  java2s .c  om
 * @param attributes
 * @param stdMutableRequest
 * @throws JSONStructureException
 */
private static List<Attribute> parseAttribute(Identifier categoryID, ArrayList<?> attributes)
        throws JSONStructureException {
    Iterator<?> iterAttributes = attributes.iterator();

    List<Attribute> collectedAttributes = new ArrayList<Attribute>();

    while (iterAttributes.hasNext()) {
        Map<?, ?> attributeMap = (Map<?, ?>) iterAttributes.next();
        if (!(attributeMap instanceof Map)) {
            throw new JSONStructureException(
                    "Expect Attribute content to be Map got " + attributeMap.getClass());
        }
        Attribute attribute = parseAttribute(categoryID, attributeMap);
        collectedAttributes.add(attribute);
    }

    // return list of all attributes for this Category
    return collectedAttributes;
}

From source file:com.wavemaker.tools.spring.ComplexReturnBean.java

@SuppressWarnings("rawtypes")
public String takesUntypedMap(Map foo) {

    if (!(foo instanceof JSONObject)) {
        return "fail: " + foo + ", " + foo.getClass();
    } else if (!foo.get("a").equals("b")) {
        return "fail: " + foo + ", " + foo.getClass();
    } else {//ww w . ja v a2  s.  c om
        return "pass";
    }
}

From source file:org.apache.ranger.tagsync.source.atlas.AtlasUtility.java

private Map<String, Object> atlasAPI(String endpoint) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> TagAtlasSource.atlasAPI(" + endpoint + ")");
    }/* ww w.ja v  a2  s .co  m*/
    // Create a REST client and perform a get on it
    Map<String, Object> ret = new HashMap<String, Object>();

    WebResource webResource = restClient.getResource(endpoint);

    ClientResponse response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);

    if (response != null && response.getStatus() == 200) {
        ret = response.getEntity(ret.getClass());
    } else {
        LOG.error("Atlas REST call returned with response={" + response + "}");

        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.error("Error getting Atlas Entity. request=" + webResource.toString() + ", response="
                + resp.toString());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== TagAtlasSource.atlasAPI(" + endpoint + ")");
    }
    return ret;
}

From source file:org.apache.ranger.tagsync.source.atlasrest.AtlasRESTUtil.java

private Map<String, Object> executeAtlasAPI(final String endpoint) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("==> executeAtlasAPI(" + endpoint + ")");
    }//  ww  w.j a va 2s  . com

    Map<String, Object> ret = new HashMap<String, Object>();

    try {
        final WebResource webResource = atlasRESTClient.getResource(endpoint);

        ClientResponse response = webResource.accept(REST_MIME_TYPE_JSON).type(REST_MIME_TYPE_JSON)
                .get(ClientResponse.class);

        if (response != null && response.getStatus() == 200) {
            ret = response.getEntity(ret.getClass());
        } else {
            RESTResponse resp = RESTResponse.fromClientResponse(response);
            LOG.error("Error getting atlas data request=" + webResource.toString() + ", response="
                    + resp.toString());
        }
    } catch (Exception exception) {
        LOG.error("Exception when fetching Atlas objects.", exception);
        ret = null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== executeAtlasAPI(" + endpoint + ")");
    }

    return ret;
}

From source file:com.cloudseal.spring.client.namespace.CloudSealBeanDefinitionParserInstance.java

private ManagedList getMapValueAsManagedList(Map map, String key) {
    Object item = map.get(key);//from  ww w  . j a v a  2  s.  co m
    if (item == null) {
        throw new IllegalStateException(
                "No value for key " + key + " in map: " + map.getClass().getCanonicalName());
    }
    if (!ManagedList.class.isInstance(item)) {
        throw new IllegalStateException(
                "Value for key " + key + " in map is not ManagedList: " + item.getClass().getCanonicalName());
    }
    return (ManagedList) item;
}

From source file:com.laxser.blitz.lama.core.SelectOperation.java

@Override
public Object execute(Map<String, Object> parameters) {
    // /*from  ww w .  j  av  a 2  s.  co m*/
    List<?> listResult = dataAccess.select(sql, modifier, parameters, rowMapper);
    final int sizeResult = listResult.size();

    //  Result ?
    if (returnType.isAssignableFrom(List.class)) {

        //   List ?
        return listResult;

    } else if (returnType.isArray() && byte[].class != returnType) {
        Object array = Array.newInstance(returnType.getComponentType(), sizeResult);
        if (returnType.getComponentType().isPrimitive()) {
            int len = listResult.size();
            for (int i = 0; i < len; i++) {
                Array.set(array, i, listResult.get(i));
            }
        } else {
            listResult.toArray((Object[]) array);
        }
        return array;

    } else if (Map.class.isAssignableFrom(returnType)) {
        //   KeyValuePair ??  Map 
        // entry.key?nullHashMap
        Map<Object, Object> map;
        if (returnType.isAssignableFrom(HashMap.class)) {

            map = new HashMap<Object, Object>(listResult.size() * 2);

        } else if (returnType.isAssignableFrom(Hashtable.class)) {

            map = new Hashtable<Object, Object>(listResult.size() * 2);

        } else {

            throw new Error(returnType.toString());
        }
        for (Object obj : listResult) {
            if (obj == null) {
                continue;
            }

            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) obj;

            if (map.getClass() == Hashtable.class && entry.getKey() == null) {
                continue;
            }

            map.put(entry.getKey(), entry.getValue());
        }

        return map;

    } else if (returnType.isAssignableFrom(HashSet.class)) {

        //   Set ?
        return new HashSet<Object>(listResult);

    } else {

        if (sizeResult == 1) {
            // ?  Bean?Boolean
            return listResult.get(0);

        } else if (sizeResult == 0) {

            // null
            if (returnType.isPrimitive()) {
                String msg = "Incorrect result size: expected 1, actual " + sizeResult + ": "
                        + modifier.toString();
                throw new EmptyResultDataAccessException(msg, 1);
            } else {
                return null;
            }

        } else {
            // IncorrectResultSizeDataAccessException
            String msg = "Incorrect result size: expected 0 or 1, actual " + sizeResult + ": "
                    + modifier.toString();
            throw new IncorrectResultSizeDataAccessException(msg, 1, sizeResult);
        }
    }
}

From source file:io.dockstore.webservice.resources.DockerRepoResource.java

@GET
@Timed//w  ww.  j  av  a2 s  .  c o m
@UnitOfWork
@Path("/builds")
@ApiOperation(value = "Get the list of repository builds.", notes = "For TESTING purposes. Also useful for getting more information about the repository.\n Enter full path without quay.io", response = String.class, hidden = true)
public String builds(@ApiParam(hidden = true) @Auth User user, @QueryParam("repository") String repo,
        @QueryParam("userId") long userId) {
    Helper.checkUser(user, userId);

    List<Token> tokens = tokenDAO.findByUserId(userId);
    StringBuilder builder = new StringBuilder();
    for (Token token : tokens) {
        if (token.getTokenSource().equals(TokenType.QUAY_IO.toString())) {
            String url = TARGET_URL + "repository/" + repo + "/build/";
            Optional<String> asString = ResourceUtilities.asString(url, token.getContent(), client);

            if (asString.isPresent()) {
                String json = asString.get();
                LOG.info(user.getUsername() + ": RESOURCE CALL: {}", url);

                Gson gson = new Gson();
                Map<String, ArrayList> map = new HashMap<>();
                map = (Map<String, ArrayList>) gson.fromJson(json, map.getClass());

                Map<String, Map<String, String>> map2;

                if (!map.get("builds").isEmpty()) {
                    map2 = (Map<String, Map<String, String>>) map.get("builds").get(0);

                    String gitURL = map2.get("trigger_metadata").get("git_url");
                    LOG.info(user.getUsername() + ": " + gitURL);

                    ArrayList<String> tags = (ArrayList<String>) map2.get("tags");
                    for (String tag : tags) {
                        LOG.info(user.getUsername() + ": " + tag);
                    }
                }

                builder.append(asString.get());
            }
            builder.append('\n');
        }
    }

    return builder.toString();
}

From source file:com.intuit.wasabi.tests.service.IntegrationExperiment.java

/**
 * Tries to PUT invalid experiments./* w ww .  j  a  va 2  s. c  o m*/
 *
 * @param experiment         the experiment
 * @param expectedError      the expected error
 * @param expectedStatusCode the expected HTTP status code
 */
@SuppressWarnings("unchecked")
@Test(dependsOnMethods = { "t_createAndValidateExperiment" }, dataProvider = "badExperimentsPUT")
public void t_failPutExperiments(String experiment, String expectedError, int expectedStatusCode) {
    Map<String, Object> mapping = new HashMap<>();
    mapping = new GsonBuilder().create().fromJson(experiment, mapping.getClass());
    doPut("experiments/" + mapping.get("id"), null, experiment, expectedStatusCode, apiServerConnector);
    // FIXME: jwtodd
    if (expectedError.startsWith("An unique constraint")) {
        Assert.assertTrue(lastError().startsWith("An unique constraint"));
    } else if (expectedError.startsWith("Can not construct instance of java.util.Date")) {
        Assert.assertTrue(lastError().startsWith("Can not construct instance of java.util.Date"));
    } else if (expectedError.startsWith("Can not construct instance of java.lang.Double")) {
        Assert.assertTrue(lastError().startsWith("Can not construct instance of java.lang.Double"));
    } else {
        Assert.assertEquals(lastError(), expectedError, "Error message not as expected.");
    }
}