Example usage for java.util Map isEmpty

List of usage examples for java.util Map isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:org.bigtester.ate.GlobalUtils.java

/**
 * Find step data logger bean./*ww  w . ja va  2 s .  c  o m*/
 *
 * @param appCtx the app ctx
 * @return the step data logger
 * @throws NoSuchBeanDefinitionException the no such bean definition exception
 */
public static StepDataLogger findStepDataLoggerBean(ApplicationContext appCtx)
        throws NoSuchBeanDefinitionException {
    Map<String, StepDataLogger> loggers = appCtx.getBeansOfType(StepDataLogger.class);

    if (loggers.isEmpty()) {
        throw new NoSuchBeanDefinitionException(TestCase.class);
    } else {
        StepDataLogger retVal = loggers.values().iterator().next();
        if (null == retVal) {
            throw new NoSuchBeanDefinitionException(TestCase.class);
        } else {
            return retVal;
        }
    }
}

From source file:com.erudika.para.utils.ValidationUtils.java

/**
 * Returns the JSON Node representation of all validation constraints for a single type.
 * @param app the app//  w w w.  java2s  . com
 * @param type a valid Para data type
 * @return a JSON Node object
 */
public static Map<String, Map<String, Map<String, Object>>> getValidationConstraints(App app, String type) {
    Map<String, Map<String, Map<String, Object>>> fieldsMap = new HashMap<String, Map<String, Map<String, Object>>>();
    if (app != null && !StringUtils.isBlank(type)) {
        try {
            List<Field> fieldlist = Utils.getAllDeclaredFields(Utils.toClass(type));
            for (Field field : fieldlist) {
                Annotation[] annos = field.getAnnotations();
                if (annos.length > 1) {
                    Map<String, Map<String, Object>> consMap = new HashMap<String, Map<String, Object>>();
                    for (Annotation anno : annos) {
                        if (isValidConstraintType(anno.annotationType())) {
                            Constraint c = fromAnnotation(anno);
                            if (c != null) {
                                consMap.put(c.getName(), c.getPayload());
                            }
                        }
                    }
                    if (consMap.size() > 0) {
                        fieldsMap.put(field.getName(), consMap);
                    }
                }
            }
            Map<String, Map<String, Map<String, Object>>> appConstraints = app.getValidationConstraints()
                    .get(type);
            if (appConstraints != null && !appConstraints.isEmpty()) {
                fieldsMap.putAll(appConstraints);
            }
        } catch (Exception ex) {
            logger.error(null, ex);
        }
    }
    return fieldsMap;
}

From source file:com.microsoft.Malmo.Utils.TextureHelper.java

public static void setMobColours(Map<String, Integer> mobColours) {
    if (mobColours == null || mobColours.isEmpty())
        idealMobColours = null;/*www.  j  a  va  2 s  .  c  o m*/
    else {
        idealMobColours = new HashMap<String, Integer>();
        // Convert the names from our XML entity type into recognisable entity names:
        String id = null;
        for (String oldname : mobColours.keySet()) {
            for (EntityEntry ent : net.minecraftforge.fml.common.registry.ForgeRegistries.ENTITIES) {
                if (ent.getName().equals(oldname)) {
                    id = ent.getRegistryName().toString();
                    break;
                }
            }
            if (id != null) {
                idealMobColours.put(id, mobColours.get(oldname));
            }
        }
    }
    texturesToColours.clear();
}

From source file:org.wrml.runtime.rest.RestUtils.java

public static final Set<Header> extractRequestHeaders(final Context context,
        final Dimensions requestedDimensions) {

    final Set<Header> headers = new LinkedHashSet<>();
    final String acceptHeaderValue = RestUtils.extractMediaTypeFromDimensions(context, requestedDimensions)
            .toString();/*from   w ww . ja v a 2s .c om*/
    final Header acceptHeader = new BasicHeader(CommonHeader.ACCEPT.getName(), acceptHeaderValue);
    headers.add(acceptHeader);

    final URI referrerUri = requestedDimensions.getReferrerUri();
    if (referrerUri != null) {
        headers.add(new BasicHeader(CommonHeader.REFERER.getName(), referrerUri.toString()));
    }

    final Locale locale = requestedDimensions.getLocale();
    if (locale != null) {
        final SyntaxLoader syntaxLoader = context.getSyntaxLoader();
        final String languageHeaderValue = syntaxLoader.formatSyntaxValue(locale);
        headers.add(new BasicHeader(CommonHeader.ACCEPT_LANGUAGE.getName(), languageHeaderValue));
    }

    final Map<String, String> metadataMap = requestedDimensions.getMetadata();
    if (metadataMap != null && !metadataMap.isEmpty()) {
        for (final String metadataName : metadataMap.keySet()) {
            final String metadataValue = metadataMap.get(metadataName);
            final Header additionalHeader = new BasicHeader(metadataName, metadataValue);
            headers.add(additionalHeader);
        }
    }

    return headers;
}

From source file:com.gson.util.HttpKit.java

/**
 * ??: ?//from   w w  w . ja  va2  s.c  o m
 * @return       : 
 * @throws UnsupportedEncodingException 
 */
public static String initParams(String url, Map<String, String> params) throws UnsupportedEncodingException {
    if (null == params || params.isEmpty()) {
        return url;
    }
    StringBuilder sb = new StringBuilder(url);
    if (url.indexOf("?") == -1) {
        sb.append("?");
    }
    sb.append(map2Url(params));
    return sb.toString();
}

From source file:com.lxht.emos.data.cache.intf.HessianUtil.java

/**
 * ?map,??K,V = [k,v,k,v]/*www  .  j  a  v a 2  s.c  o m*/
 *
 * @param map
 * @return
 * @throws IOException
 */
public static final byte[][] mapToByteArray(Map<String, Serializable> map) throws IOException {
    if (map == null || map.isEmpty()) {
        throw new NullPointerException("mapToByteArray is null.");
    }

    byte[][] bytes = new byte[map.size() * 2][];

    int i = 0;
    for (Entry<String, Serializable> entry : map.entrySet()) {
        bytes[i] = entry.getKey().getBytes();
        bytes[i + 1] = serialize(entry.getValue());
        i = i + 2;
    }

    return bytes;

}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

private static DataType getDataType(Object value) {
    Class cls = value.getClass();
    DataType dataType;//from ww  w  . j  ava2  s.  co m
    if (cls.equals(String.class)) {
        dataType = DataType.StringType;
    } else if (cls.equals(Byte[].class)) {
        dataType = DataType.BinaryType;
    } else if (cls.equals(Boolean.class)) {
        dataType = DataType.BooleanType;
    } else if (cls.equals(Timestamp.class)) {
        dataType = DataType.TimestampType;
    } else if (cls.equals(Double.class)) {
        dataType = DataType.DoubleType;
    } else if (cls.equals(Float.class)) {
        dataType = DataType.FloatType;
    } else if (cls.equals(Byte.class)) {
        dataType = DataType.ByteType;
    } else if (cls.equals(Integer.class)) {
        dataType = DataType.IntegerType;
    } else if (cls.equals(Long.class)) {
        dataType = DataType.LongType;
    } else if (cls.equals(Short.class)) {
        dataType = DataType.ShortType;
    } else if (value instanceof List) {
        List listValue = (List) value;
        if (listValue.isEmpty()) {
            dataType = DataType.createArrayType(DataType.StringType);
        } else {
            dataType = DataType.createArrayType(getDataType(listValue.get(0)));
        }
    } else if (value instanceof Map) {
        Map mapValue = (Map) value;
        if (mapValue.isEmpty()) {
            dataType = DataType.createMapType(DataType.StringType, DataType.StringType);
        } else {
            Map.Entry entry = (Map.Entry) mapValue.entrySet().iterator().next();
            dataType = DataType.createMapType(getDataType(entry.getKey()), getDataType(entry.getValue()));
        }
    } else {
        dataType = DataType.StringType;
    }
    return dataType;
}

From source file:com.erudika.para.utils.ValidationUtils.java

/**
 * Validates objects./*from   w  w  w .j  av a 2  s. c  o m*/
 * @param content an object to be validated
 * @param app the current app
 * @return a list of error messages or empty if object is valid
 */
public static String[] validateObject(App app, ParaObject content) {
    if (content == null || app == null) {
        return new String[] { "Object cannot be null." };
    }
    try {
        String type = content.getType();
        boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class));
        // Validate custom types and user-defined properties
        if (!app.getValidationConstraints().isEmpty() && isCustomType) {
            Map<String, Map<String, Map<String, Object>>> fieldsMap = app.getValidationConstraints().get(type);
            if (fieldsMap != null && !fieldsMap.isEmpty()) {
                ArrayList<String> errors = new ArrayList<String>();
                for (Map.Entry<String, Map<String, Map<String, Object>>> e : fieldsMap.entrySet()) {
                    String field = e.getKey();
                    Object actualValue = ((Sysprop) content).getProperty(field);
                    // overriding core property validation rules is allowed
                    if (actualValue == null && PropertyUtils.isReadable(content, field)) {
                        actualValue = PropertyUtils.getProperty(content, field);
                    }
                    Map<String, Map<String, Object>> consMap = e.getValue();
                    for (Map.Entry<String, Map<String, Object>> constraint : consMap.entrySet()) {
                        String consName = constraint.getKey();
                        Map<String, Object> vals = constraint.getValue();
                        if (vals == null) {
                            vals = Collections.emptyMap();
                        }

                        Object val = vals.get("value");
                        Object min = vals.get("min");
                        Object max = vals.get("max");
                        Object in = vals.get("integer");
                        Object fr = vals.get("fraction");

                        if ("required".equals(consName) && !required().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is required.", field));
                        } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number larger than {1}.", field, val));
                        } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number smaller than {1}.", field, val));
                        } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max));
                        } else if (matches(Email.class, consName) && !email().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid email.", field));
                        } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} is not a valid number or within range.", field));
                        } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val));
                        } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be false.", field));
                        } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be true.", field));
                        } else if (matches(Future.class, consName) && !future().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the future.", field));
                        } else if (matches(Past.class, consName) && !past().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the past.", field));
                        } else if (matches(URL.class, consName) && !url().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid URL.", field));
                        }
                    }
                }
                if (!errors.isEmpty()) {
                    return errors.toArray(new String[0]);
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }
    return validateObject(content);
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * get/*from ww  w .j  a v  a  2 s.  c  o  m*/
 * 
 * @param url
 *            URL
 * @param params
 *            getkey-value
 * @return JSON
 * @throws ClientProtocolException
 * @throws IOException
 * @throws URISyntaxException 
 */
public static String get(String url, Map<String, ?> params)
        throws ClientProtocolException, IOException, URISyntaxException {
    DefaultHttpClient httpclient = getHttpClient();
    try {
        if (params != null && !(params.isEmpty())) {
            List<NameValuePair> values = new ArrayList<NameValuePair>();
            for (Map.Entry<String, ?> entity : params.entrySet()) {
                BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString());
                values.add(pare);

            }
            String str = URLEncodedUtils.format(values, "UTF-8");
            if (url.indexOf("?") > -1) {
                url += "&" + str;
            } else {
                url += "?" + str;
            }
        }
        URL pageURL = new URL(url);
        //pageUrl?httpget
        URI uri = new URI(pageURL.getProtocol(), pageURL.getHost(), pageURL.getPath(), pageURL.getQuery(),
                null);
        HttpGet httpget = createHttpUriRequest(HttpMethod.GET, uri);
        httpget.setHeader("Pragma", "no-cache");
        httpget.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        httpget.setHeader("Accept-Charset", "gbk,utf-8;q=0.7,*;q=0.7");
        httpget.setHeader("Referer", url);
        /*httpget.setHeader("Content-Encoding", "gzip");
        httpget.setHeader("Accept-Encoding", "gzip, deflate");*/
        //httpget.setHeader("Host", "s.taobao.com");
        /*int temp = Integer.parseInt(Math.round(Math.random()*(MingSpiderService.UserAgent.length-1))+"");//???
        httpget.setHeader("User-Agent", MingSpiderService.UserAgent[temp]);*/
        HttpResponse response = httpclient.execute(httpget);
        httpclient.getCookieStore().clear();
        int resStatu = response.getStatusLine().getStatusCode();
        String html = "";
        if (resStatu == HttpStatus.SC_OK) {//200 
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                html = EntityUtils.toString(entity, "GBK");
                EntityUtils.consume(entity);
            }
        }
        return html;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:Main.java

/**
 * Removes the value from the set of values mapped by key. If this value was the last value in the set of values
 * mapped by key, the complete key/values entry is removed.
 * /*from   ww w .  j  av a 2s  . co  m*/
 * @param key
 *            The key for which to remove a value.
 * @param value
 *            The value for which to remove the key.
 * @param map
 *            The object that maps the key to a set of values, on which the operation should occur.
 */
public static <K, V> void deleteAndRemove(final K key, final V value, final Map<K, Set<V>> map) {
    if (key == null) {
        throw new IllegalArgumentException("Argument 'key' cannot be null.");
    }
    if (value == null) {
        throw new IllegalArgumentException("Argument 'value' cannot be null.");
    }
    if (map == null) {
        throw new IllegalArgumentException("Argument 'map' cannot be null.");
    }

    if (map.isEmpty() || !map.containsKey(key)) {
        return;
    }

    final Set<V> values = map.get(key);
    values.remove(value);

    if (values.isEmpty()) {
        map.remove(key);
    }
}