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:net.opentsdb.query.filter.TagVFilter.java

/**
 * Converts the  map to a filter list. If a filter already exists for a
 * tag group by and we're told to process group bys, then the duplicate 
 * is skipped. //from ww w .  ja v a2s .com
 * @param map A set of tag keys and values. May be null or empty.
 * @param filters A set of filters to add the converted filters to. This may
 * not be null.
 * @param group_by Whether or not to set the group by flag and kick dupes
 */
public static void mapToFilters(final Map<String, String> map, final List<TagVFilter> filters,
        final boolean group_by) {
    if (map == null || map.isEmpty()) {
        return;
    }

    for (final Map.Entry<String, String> entry : map.entrySet()) {
        TagVFilter filter = getFilter(entry.getKey(), entry.getValue());

        if (filter == null && entry.getValue().equals("*")) {
            filter = new TagVWildcardFilter(entry.getKey(), "*", true);
        } else if (filter == null) {
            filter = new TagVLiteralOrFilter(entry.getKey(), entry.getValue());
        }

        if (group_by) {
            filter.setGroupBy(true);
            boolean duplicate = false;
            for (final TagVFilter existing : filters) {
                if (filter.equals(existing)) {
                    LOG.debug("Skipping duplicate filter: " + existing);
                    existing.setGroupBy(true);
                    duplicate = true;
                    break;
                }
            }

            if (!duplicate) {
                filters.add(filter);
            }
        } else {
            filters.add(filter);
        }
    }
}

From source file:org.kegbot.api.KegbotApiImpl.java

private static String getUrlParamsString(Map<String, String> params) {
    if (params == null || params.isEmpty()) {
        return "";
    }//from  w  ww .j  a v a2s  .c  o  m

    final List<String> parts = Lists.newArrayList();
    for (Map.Entry<String, String> param : params.entrySet()) {
        try {
            parts.add(String.format("%s=%s", URLEncoder.encode(param.getKey(), "utf-8"),
                    URLEncoder.encode(param.getValue(), "utf-8")));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return Joiner.on('&').join(parts);
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout,
        TimeUnit timeUnit) throws Throwable {
    QueryTask.Query selfLinkClause = new QueryTask.Query()
            .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("/photon/*")
            .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD);

    QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification();
    querySpecification.query.addBooleanClause(selfLinkClause);
    QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true);

    NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer,
            queryTask);/*from   w ww  .j  a  v  a2s .c o  m*/

    Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryDocumentLinks(queryResponse);

    if (documentLinks == null || documentLinks.size() <= 0) {
        return;
    }

    CountDownLatch latch = new CountDownLatch(1);

    OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() {
        @Override
        public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) {
            if (failures != null && !failures.isEmpty()) {
                for (Throwable e : failures.values()) {
                    logger.error("deleteAllDocuments failed", e);
                }
            }
            latch.countDown();
        }
    };

    Collection<Operation> deletes = new LinkedList<>();
    for (String documentLink : documentLinks) {
        Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}")
                .setReferer(UriUtils.buildUri(host, referrer));
        deletes.add(deleteOperation);
    }

    OperationJoin join = OperationJoin.create(deletes);
    join.setCompletion(handler);
    join.sendWith(host);
    if (!latch.await(timeout, timeUnit)) {
        throw new TimeoutException(String
                .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit));
    }
}

From source file:com.couchbase.client.java.document.json.JsonObject.java

/**
 * Constructs a {@link JsonObject} from a {@link Map Map&lt;String, ?&gt;}.
 *
 * This is only possible if the given Map is well formed, that is it contains non null
 * keys, and all values are of a supported type.
 *
 * A null input Map or null key will lead to a {@link NullPointerException} being thrown.
 * If any unsupported value is present in the Map, an {@link IllegalArgumentException}
 * will be thrown.//from  w w  w.  j  av a  2s. c o  m
 *
 * *Sub Maps and Lists*
 * If possible, Maps and Lists contained in mapData will be converted to JsonObject and
 * JsonArray respectively. However, same restrictions apply. Any non-convertible collection
 * will raise a {@link ClassCastException}. If the sub-conversion raises an exception (like an
 * IllegalArgumentException) then it is put as cause for the ClassCastException.
 *
 * @param mapData the Map to convert to a JsonObject
 * @return the resulting JsonObject
 * @throws IllegalArgumentException in case one or more unsupported values are present
 * @throws NullPointerException in case a null map is provided or if it contains a null key
 * @throws ClassCastException if map contains a sub-Map or sub-List not supported (see above)
 */
public static JsonObject from(Map<String, ?> mapData) {
    if (mapData == null) {
        throw new NullPointerException("Null input Map unsupported");
    } else if (mapData.isEmpty()) {
        return JsonObject.empty();
    }

    JsonObject result = new JsonObject(mapData.size());
    for (Map.Entry<String, ?> entry : mapData.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (value == JsonValue.NULL) {
            value = null;
        }

        if (key == null) {
            throw new NullPointerException("The key is not allowed to be null");
        } else if (value instanceof Map) {
            try {
                JsonObject sub = JsonObject.from((Map<String, ?>) value);
                result.put(key, sub);
            } catch (ClassCastException e) {
                throw e;
            } catch (Exception e) {
                ClassCastException c = new ClassCastException(
                        "Couldn't convert sub-Map " + key + " to JsonObject");
                c.initCause(e);
                throw c;
            }
        } else if (value instanceof List) {
            try {
                JsonArray sub = JsonArray.from((List<?>) value);
                result.put(key, sub);
            } catch (Exception e) {
                //no risk of a direct ClassCastException here
                ClassCastException c = new ClassCastException(
                        "Couldn't convert sub-List " + key + " to JsonArray");
                c.initCause(e);
                throw c;
            }
        } else if (!checkType(value)) {
            throw new IllegalArgumentException("Unsupported type for JsonObject: " + value.getClass());
        } else {
            result.put(key, value);
        }
    }
    return result;
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static String buildDataSourceDetails() {
    final Map<String, Map<String, Object>> dataSourcesProperties = JdbcWrapper.getBasicDataSourceProperties();
    final StringBuilder sb = new StringBuilder();
    for (final Map.Entry<String, Map<String, Object>> entry : dataSourcesProperties.entrySet()) {
        final Map<String, Object> dataSourceProperties = entry.getValue();
        if (dataSourceProperties.isEmpty()) {
            continue;
        }/*  w  w w  .j  a  v  a2s  .c  o m*/
        if (sb.length() > 0) {
            sb.append('\n');
        }
        final String name = entry.getKey();
        if (name != null) {
            sb.append(name).append(":\n");
        }
        for (final Map.Entry<String, Object> propertyEntry : dataSourceProperties.entrySet()) {
            sb.append(propertyEntry.getKey()).append(" = ").append(propertyEntry.getValue()).append('\n');
        }
    }
    if (sb.length() == 0) {
        return null;
    }
    return sb.toString();
}

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

/**
 * Returns all validation constraints that are defined by Java annotation in the core classes.
 *
 * @return a map of all core types to all core annotated constraints. See JSR-303.
 */// w w  w  .  j av  a2s. c  o  m
public static Map<String, Map<String, Map<String, Map<String, ?>>>> getCoreValidationConstraints() {
    if (coreValidationConstraints.isEmpty()) {
        for (Map.Entry<String, Class<? extends ParaObject>> e : ParaObjectUtils.getCoreClassesMap()
                .entrySet()) {
            String type = e.getKey();
            List<Field> fieldlist = Utils.getAllDeclaredFields(e.getValue());
            for (Field field : fieldlist) {
                Annotation[] annos = field.getAnnotations();
                if (annos.length > 1) {
                    Map<String, Map<String, ?>> constrMap = new HashMap<String, Map<String, ?>>();
                    for (Annotation anno : annos) {
                        if (isValidConstraintType(anno.annotationType())) {
                            Constraint c = fromAnnotation(anno);
                            if (c != null) {
                                constrMap.put(c.getName(), c.getPayload());
                            }
                        }
                    }
                    if (!constrMap.isEmpty()) {
                        if (!coreValidationConstraints.containsKey(type)) {
                            coreValidationConstraints.put(type,
                                    new HashMap<String, Map<String, Map<String, ?>>>());
                        }
                        coreValidationConstraints.get(type).put(field.getName(), constrMap);
                    }
                }
            }
        }
    }
    return Collections.unmodifiableMap(coreValidationConstraints);
}

From source file:com.tops.hotelmanager.util.CommonHttpClient.java

private static String executePOSTRequestV1(String url, Map<String, Object> requestData,
        Map<String, String> headerMap, String contentType, int timeOut, int retry) {
    PostMethod post = new PostMethod(url);
    Gson gson = new Gson();
    String errorMsg = "error~Request Failed";
    try {// www.  j  a  v  a2s . c  o  m
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
        if (requestData == null || requestData.isEmpty()) {
            throw new CustomException("Request data is null");
        }
        if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) {
            StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType,
                    "UTF-8");
            post.setRequestEntity(requestEntity);
        } else {
            // SET REQUEST PARAMETER
            for (Map.Entry<String, Object> entry : requestData.entrySet()) {
                post.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        // SET REQUEST HEADER
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addRequestHeader(entry.getKey(), entry.getValue());
            }
        }
        int status = client.executeMethod(post);
        // System.out.println("URL:" + url);
        // System.out.println("\n REQUEST HEADERS:");
        // Header[] requestHeaders = post.getRequestHeaders();
        // for (Header header : requestHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println("\n RESPONSE HEADERS:");
        // Header[] responseHeaders = post.getResponseHeaders();
        // for (Header header : responseHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println(post.getStatusText());
        // System.out.println(post.getStatusLine().getReasonPhrase());
        // System.out.println(post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            return post.getResponseBodyAsString();
        } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("Location");
            if (retry != 1) {
                errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut,
                        retry++);
            }
        } else {
            errorMsg += ",HttpStatus:" + status;
        }
    } catch (Exception ex) {
        logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex);
        errorMsg = errorMsg + ":" + ex.getMessage();
    } finally {
        post.releaseConnection();
    }
    return errorMsg;
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 *
 * @param factsheetActionBean/*ww  w.j av a 2  s.  c om*/
 * @param predicateUri
 * @return
 */
public static String predicateCollapseLink(FactsheetActionBean factsheetActionBean, String predicateUri) {

    StringBuilder link = new StringBuilder();
    link.append(FactsheetActionBean.class.getAnnotation(UrlBinding.class).value()).append("?");

    HttpServletRequest request = factsheetActionBean.getContext().getRequest();
    Map<String, String[]> paramsMap = request.getParameterMap();
    if (paramsMap != null && !paramsMap.isEmpty()) {

        for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {

            String paramName = entry.getKey();
            String[] paramValues = entry.getValue();
            if (paramValues == null || paramValues.length == 0) {
                try {
                    link.append(URLEncoder.encode(paramName, "UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    throw new CRRuntimeException("Unsupported encoding", e);
                }
            } else {
                boolean isPageParam = factsheetActionBean.isPredicatePageParam(paramName);
                for (String paramValue : paramValues) {
                    if (!isPageParam || !paramValue.equals(predicateUri)) {
                        try {
                            link.append(URLEncoder.encode(paramName, "UTF-8")).append("=")
                                    .append(URLEncoder.encode(paramValue, "UTF-8")).append("&");
                        } catch (UnsupportedEncodingException e) {
                            throw new CRRuntimeException("Unsupported encoding", e);
                        }
                    }
                }
            }
        }
    }

    return StringUtils.removeEnd(link.toString(), "&");
}

From source file:ips1ap101.lib.core.db.util.Reporter.java

private static Map getReportParametersMap(File file, String format, Long userid, String usercode,
        String username, Locale locale, Map parametros) {
    Map parameters = getReportParametersMap(file, format, userid, usercode, username, locale);
    if (parametros != null && !parametros.isEmpty()) {
        parameters.putAll(parametros);//  ww  w  . j  a va2s. co m
    }
    return parameters;
}

From source file:com.careerly.utils.HttpClientUtils.java

private static String postWithTimeoutException(String url, Map<String, String> formData, String defaultEncoding)
        throws SocketTimeoutException {
    defaultEncoding = HttpClientUtils.getDefaultEncoding(defaultEncoding);

    HttpPost post = new HttpPost(url);
    String content = null;//from w  ww  .ja  v a  2 s  . c  om
    List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
    if (formData != null && !formData.isEmpty()) {
        for (Entry<String, String> entry : formData.entrySet()) {
            nameValues.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    try {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValues, defaultEncoding);
        post.setEntity(formEntity);
        content = HttpClientUtils.client.execute(post, new CharsetableResponseHandler(defaultEncoding));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("unsupported Encoding " + defaultEncoding, e);
    } catch (SocketTimeoutException e) {
        throw e;
    } catch (Exception e) {
        HttpClientUtils.logger.error(String.format("post [%s] happens error ", url), e);
    }
    return content;
}