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:Main.java

/**
 * Make the log more meanings/*w  w  w  .j  av a2s. c  o  m*/
 * 
 * @param <K>
 * @param <V>
 * @param map
 * @return
 */
public static <K, V> String toLog(Map<K, V> map) {
    // using StringBuffer instead of String because expect there are many append operation
    StringBuffer sb = new StringBuffer();

    if (map == null) {
        return null;
    }
    if (map.isEmpty()) {
        return map.toString();
    }

    sb.append("{");

    for (Iterator<K> iterator = map.keySet().iterator(); iterator.hasNext();) {
        K key = iterator.next();
        Object value = map.get(key);
        sb.append(key).append("=");
        sb.append(toString4Log(value));
        if (iterator.hasNext()) {
            sb.append(", ");
        }
    }

    sb.append("}");

    return sb.toString();
}

From source file:com.ciphertool.sentencebuilder.dao.IndexedWordMapDao.java

/**
 * Add the word to the map by reference a number of times equal to the
 * frequency value//from  w w w . java  2 s . c om
 * 
 * We can probably reduce memory utilization even more if we combine the
 * words into one ArrayList not separated by Word length, and then only
 * separate the index HashMap by length
 * 
 * @param byLength
 *            the Map of Words keyed by length
 * @return the index Map keyed by length
 */
protected static Map<Integer, int[]> buildIndexedFrequencyMapByLength(Map<Integer, ArrayList<Word>> byLength) {
    if (byLength == null || byLength.isEmpty()) {
        throw new IllegalArgumentException(
                "Error indexing Word length map.  The supplied Map of Words cannot be null or empty.");
    }

    HashMap<Integer, int[]> byFrequency = new HashMap<Integer, int[]>();

    int frequencySum;

    /*
     * Loop through each Word length, add up the frequency weights, and
     * create an int array of the resulting length
     */
    for (Map.Entry<Integer, ArrayList<Word>> length : byLength.entrySet()) {
        frequencySum = 0;

        for (Word w : byLength.get(length.getKey())) {
            frequencySum += w.getFrequencyWeight();
        }

        byFrequency.put(length.getKey(), new int[frequencySum]);
    }

    int frequencyIndex;
    int wordIndex;

    /*
     * Loop through each length and word, and add the index to the
     * frequencyMap a number of times equal to the word's frequency weight
     */
    for (Map.Entry<Integer, ArrayList<Word>> lengthEntry : byLength.entrySet()) {
        frequencyIndex = 0;
        wordIndex = 0;

        for (Word w : byLength.get(lengthEntry.getKey())) {
            for (int i = 0; i < w.getFrequencyWeight(); i++) {
                byFrequency.get(lengthEntry.getKey())[frequencyIndex] = wordIndex;

                frequencyIndex++;
            }
            wordIndex++;
        }
    }

    return byFrequency;
}

From source file:com.ingby.socbox.bischeck.cli.CacheCli.java

private static void cli(Boolean supportNull) throws IOException, ConfigurationException {

    ExecuteJEP parser = new ExecuteJEP(); // Create a new parser 

    ConsoleReader console = null;/*from  w  w w  .j a va  2s. com*/
    FileHistory history = null;

    String historyFile = System.getProperty("user.home") + File.separator + HISTORY_FILE;

    try {

        console = new ConsoleReader();
        history = new FileHistory(new File(historyFile));
        console.println("Welcome to Bischeck cache-cli");
        console.println("-----------------------------");

        console.print("- Using bischeck configuration: ");
        console.println(ConfigFileManager.initConfigDir().getAbsolutePath());

        console.print("- Cmd history: ");
        console.println(history.getFile().getAbsolutePath());
        console.print("- Null support in arrays: ");
        console.println(supportNull.toString());

        console.setHistory(history);
        console.println("Execution time is divided in parse/calculate/total time (ms)");
        console.setPrompt(PROMPT);

        // Main loop reading cli commands
        boolean first = true;
        while (true) {
            String line = null;

            try {
                line = console.readLine();
            } catch (IllegalArgumentException ie) {
                console.println(ie.getMessage());
                continue;
            }

            if (line == null || QUIT.equalsIgnoreCase(line) || EXIT.equalsIgnoreCase(line)) {
                break;
            }

            if (line.matches("^list.*")) {
                String[] patternArray = line.split("^list");
                String pattern = "*";
                if (patternArray.length == 2 && !patternArray[1].trim().isEmpty()) {
                    pattern = patternArray[1];
                }

                Map<String, Long> lists = listKeys(pattern.trim());
                if (!lists.isEmpty()) {
                    for (String key : lists.keySet()) {
                        console.print(key);
                        console.print(" : ");
                        console.println(lists.get(key).toString());
                    }
                } else {
                    console.println(NOT_FOUND);
                }

                continue;
            }

            if (HELP.equalsIgnoreCase(line)) {
                showhelp(console);
                continue;
            }

            try {
                if (first) {
                    execute(parser, line);
                    console.println(execute(parser, line));
                    first = false;
                } else {
                    console.println(execute(parser, line));
                }
            } catch (ParseException e) {
                console.println(e.getMessage());
            }
        }
    } finally {
        try {
            TerminalFactory.get().restore();
        } catch (Exception e) {
            console.println("Could not restore " + e.getMessage());
        }
        if (history != null) {
            history.flush();
        }
    }
}

From source file:com.thinkbiganalytics.nifi.feedmgr.ConfigurationPropertyReplacer.java

/**
 * @param property         the NifiProperty to replace
 * @param configProperties a Map of properties which will be looked to to match against the property key
 */// w  ww.java 2  s.  c o m
public static boolean resolveStaticConfigurationProperty(NifiProperty property,
        Map<String, Object> configProperties) {
    String value = property.getValue();
    StringBuffer sb = null;

    if (configProperties != null && !configProperties.isEmpty()) {

        if (StringUtils.isNotBlank(value)) {
            Pattern variablePattern = Pattern.compile("\\$\\{(.*?)\\}");
            Matcher matchVariablePattern = variablePattern.matcher(value);
            while (matchVariablePattern.find()) {
                if (sb == null) {
                    sb = new StringBuffer();
                }
                String group = matchVariablePattern.group();
                int groupCount = matchVariablePattern.groupCount();
                if (groupCount == 1) {

                    String variable = matchVariablePattern.group(1);
                    //lookup the variable
                    //first look at configuration properties
                    Object resolvedValue = configProperties.get(variable);
                    if (resolvedValue != null) {
                        matchVariablePattern.appendReplacement(sb, resolvedValue.toString());
                    }
                }
            }
            if (sb != null) {
                matchVariablePattern.appendTail(sb);
            }
        }
    }

    if (sb == null) {

        String updatedValue = resolveValue(property, configProperties);
        if (StringUtils.isNotBlank(updatedValue)) {
            sb = new StringBuffer();
            sb.append(updatedValue);
        }

    }
    if (sb != null) {
        property.setValue(StringUtils.trim(sb.toString()));
    }

    return sb != null;
}

From source file:com.taobao.tddl.jdbc.atom.common.TAtomConfParser.java

public static TAtomDsConfDO parserTAtomDsConfDO(String globaConfStr, String appConfStr) {
    TAtomDsConfDO pasObj = new TAtomDsConfDO();
    if (TStringUtil.isNotBlank(globaConfStr)) {
        Properties globaProp = TAtomConfParser.parserConfStr2Properties(globaConfStr);
        if (!globaProp.isEmpty()) {
            String ip = TStringUtil.trim(globaProp.getProperty(TAtomConfParser.GLOBA_IP_KEY));
            if (TStringUtil.isNotBlank(ip)) {
                pasObj.setIp(ip);//  w  ww. j  ava 2  s. com
            }
            String port = TStringUtil.trim(globaProp.getProperty(TAtomConfParser.GLOBA_PORT_KEY));
            if (TStringUtil.isNotBlank(port)) {
                pasObj.setPort(port);
            }
            String dbName = TStringUtil.trim(globaProp.getProperty(TAtomConfParser.GLOBA_DB_NAME_KEY));
            if (TStringUtil.isNotBlank(dbName)) {
                pasObj.setDbName(dbName);
            }
            String dbType = TStringUtil.trim(globaProp.getProperty(TAtomConfParser.GLOBA_DB_TYPE_KEY));
            if (TStringUtil.isNotBlank(dbType)) {
                pasObj.setDbType(dbType);
            }
            String dbStatus = TStringUtil.trim(globaProp.getProperty(TAtomConfParser.GLOBA_DB_STATUS_KEY));
            if (TStringUtil.isNotBlank(dbStatus)) {
                pasObj.setDbStatus(dbStatus);
            }
        }
    }
    if (TStringUtil.isNotBlank(appConfStr)) {
        Properties appProp = TAtomConfParser.parserConfStr2Properties(appConfStr);
        if (!appProp.isEmpty()) {
            String userName = TStringUtil.trim(appProp.getProperty(TAtomConfParser.APP_USER_NAME_KEY));
            if (TStringUtil.isNotBlank(userName)) {
                pasObj.setUserName(userName);
            }
            String oracleConType = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_ORACLE_CON_TYPE_KEY));
            if (TStringUtil.isNotBlank(oracleConType)) {
                pasObj.setOracleConType(oracleConType);
            }
            String minPoolSize = TStringUtil.trim(appProp.getProperty(TAtomConfParser.APP_MIN_POOL_SIZE_KEY));
            if (TStringUtil.isNotBlank(minPoolSize) && TStringUtil.isNumeric(minPoolSize)) {
                pasObj.setMinPoolSize(Integer.valueOf(minPoolSize));
            }
            String maxPoolSize = TStringUtil.trim(appProp.getProperty(TAtomConfParser.APP_MAX_POOL_SIZE_KEY));
            if (TStringUtil.isNotBlank(maxPoolSize) && TStringUtil.isNumeric(maxPoolSize)) {
                pasObj.setMaxPoolSize(Integer.valueOf(maxPoolSize));
            }
            String idleTimeout = TStringUtil.trim(appProp.getProperty(TAtomConfParser.APP_IDLE_TIMEOUT_KEY));
            if (TStringUtil.isNotBlank(idleTimeout) && TStringUtil.isNumeric(idleTimeout)) {
                pasObj.setIdleTimeout(Long.valueOf(idleTimeout));
            }
            String blockingTimeout = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_BLOCKING_TIMEOUT_KEY));
            if (TStringUtil.isNotBlank(blockingTimeout) && TStringUtil.isNumeric(blockingTimeout)) {
                pasObj.setBlockingTimeout(Integer.valueOf(blockingTimeout));
            }
            String preparedStatementCacheSize = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_PREPARED_STATEMENT_CACHE_SIZE_KEY));
            if (TStringUtil.isNotBlank(preparedStatementCacheSize)
                    && TStringUtil.isNumeric(preparedStatementCacheSize)) {
                pasObj.setPreparedStatementCacheSize(Integer.valueOf(preparedStatementCacheSize));
            }

            String writeRestrictTimes = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_WRITE_RESTRICT_TIMES));
            if (TStringUtil.isNotBlank(writeRestrictTimes) && TStringUtil.isNumeric(writeRestrictTimes)) {
                pasObj.setWriteRestrictTimes(Integer.valueOf(writeRestrictTimes));
            }

            String readRestrictTimes = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_READ_RESTRICT_TIMES));
            if (TStringUtil.isNotBlank(readRestrictTimes) && TStringUtil.isNumeric(readRestrictTimes)) {
                pasObj.setReadRestrictTimes(Integer.valueOf(readRestrictTimes));
            }
            String threadCountRestrict = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_THREAD_COUNT_RESTRICT));
            if (TStringUtil.isNotBlank(threadCountRestrict) && TStringUtil.isNumeric(threadCountRestrict)) {
                pasObj.setThreadCountRestrict(Integer.valueOf(threadCountRestrict));
            }
            String timeSliceInMillis = TStringUtil
                    .trim(appProp.getProperty(TAtomConfParser.APP_TIME_SLICE_IN_MILLS));
            if (TStringUtil.isNotBlank(timeSliceInMillis) && TStringUtil.isNumeric(timeSliceInMillis)) {
                pasObj.setTimeSliceInMillis(Integer.valueOf(timeSliceInMillis));
            }

            String conPropStr = TStringUtil.trim(appProp.getProperty(TAtomConfParser.APP_CON_PROP_KEY));
            Map<String, String> connectionProperties = parserConPropStr2Map(conPropStr);
            if (null != connectionProperties && !connectionProperties.isEmpty()) {
                pasObj.setConnectionProperties(connectionProperties);
            }
        }
    }
    return pasObj;
}

From source file:com.silverwrist.util.StringUtils.java

/**
 * Replaces variable substitutions in a string.  Variable substitutions are strings of the form
 * <CODE>${<EM>varname</EM>}</CODE>.  The <EM>varname</EM> names are looked up in the supplied
 * <CODE>Map</CODE>, and the values of variables in that map are substituted.<P>
 * Only variable names that exist in the <CODE>Map</CODE> are replaced; other variable strings
 * in the supplied string are left untouched.  Variable substitution values may themselves contain
 * variables; those variables are recursively replaced.  (<B><EM>Caution:</EM></B> The code cannot
 * detect variable substitutions that contain themselves, or two variables that contain each other.
 * Avoid these situations.)/*w w  w.ja va 2 s  .c  o  m*/
 *
 * @param base The string to be operated on.  If this parameter is <CODE>null</CODE>, the
 *             method will return <CODE>null</CODE>.
 * @param vars The mapping of variable name to value substitutions.  If this parameter is
 *             <CODE>null</CODE> or an empty map, no substitutions will be performed on
 *             <CODE>base</CODE>.
 * @return The <CODE>base</CODE> string with all variable substitutions made as detailed above.
 */
public static final String replaceAllVariables(String base, Map vars) {
    if ((base == null) || (vars == null) || vars.isEmpty())
        return base; // safety feature

    String work = base;
    boolean did_replace = false;
    boolean retest = true;
    do { // main loop for replacing all variables
        did_replace = false;
        Iterator it = vars.keySet().iterator();
        while (it.hasNext()) { // variable start is there...
            if (retest) { // only perform this test on the first iteration and after we know we've replaced a variable
                if (work.indexOf(VAR_START) < 0)
                    return work; // no more variables in text - all done!
                retest = false;

            } // end if

            // get variable name and see if it's present
            String vname = it.next().toString();
            String var_full = VAR_START + vname + VAR_END;
            if (work.indexOf(var_full) >= 0) { // OK, this variable is in place
                work = replace(work, var_full, vars.get(vname).toString());
                did_replace = true;
                retest = true;

            } // end if

        } // end while

    } while (did_replace); // end do

    return work; // all done!

}

From source file:de.fhg.igd.mapviewer.server.wms.capabilities.WMSUtil.java

/**
 * Get the preferred bounding box/*from   w ww .j  ava 2  s  .  c  o m*/
 * 
 * @param capabilities the WMS capabilities
 * @param preferredEpsg the preferred EPSG code
 * @return the preferred bounding box, an available bounding box or
 *         <code>null</code>
 */
private static WMSBounds getPreferredBoundingBox(WMSCapabilities capabilities, int preferredEpsg) {
    // get bounding boxes
    Map<String, WMSBounds> bbs = capabilities.getBoundingBoxes();

    WMSBounds bb = null;

    if (!bbs.isEmpty()) {
        // bounding box present
        if (preferredEpsg != 0) {
            bb = bbs.get("EPSG:" + preferredEpsg); //$NON-NLS-1$
        }

        if (bb != null) {
            // log.info("Found bounding box for preferred srs");
            // //$NON-NLS-1$
        } else {
            Iterator<WMSBounds> itBB = bbs.values().iterator();

            while (bb == null && itBB.hasNext()) {
                WMSBounds temp = itBB.next();

                if (temp.getSRS().startsWith("EPSG:") //$NON-NLS-1$
                ) {// &&
                   // capabilities.getSupportedSRS().contains(temp.getSRS()))
                   // {
                    bb = temp;
                    // log.info("Found epsg bounding box"); //$NON-NLS-1$
                }
            }
        }
    }
    return bb;
}

From source file:com.kolich.aws.services.s3.impl.KolichS3Signer.java

/**
  * Calculate the canonical string for a REST/HTTP request to S3.
  *//*from w ww  .ja va2  s. c  o m*/
private static final String getS3CanonicalString(final AwsHttpRequest request) {
    // A few standard headers we extract for conveinence.
    final String contentType = CONTENT_TYPE.toLowerCase(), contentMd5 = CONTENT_MD5.toLowerCase(),
            date = DATE.toLowerCase();
    // Start with the empty string ("").
    final StringBuilder buf = new StringBuilder();
    // Next is the HTTP verb and a newline.
    buf.append(request.getMethod() + LINE_SEPARATOR_UNIX);
    // Add all interesting headers to a list, then sort them.
    // "Interesting" is defined as Content-MD5, Content-Type, Date,
    // and x-amz-... headers.
    final Map<String, String> headersMap = getHeadersAsMap(request);
    final SortedMap<String, String> interesting = Maps.newTreeMap();
    if (!headersMap.isEmpty()) {
        Iterator<Map.Entry<String, String>> it = headersMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            final String key = entry.getKey(), value = entry.getValue();
            if (key == null) {
                continue;
            }
            final String lk = key.toLowerCase(Locale.getDefault());
            // Ignore any headers that are not interesting.
            if (lk.equals(contentType) || lk.equals(contentMd5) || lk.equals(date)
                    || lk.startsWith(AMAZON_PREFIX)) {
                interesting.put(lk, value);
            }
        }
    }
    // Remove default date timestamp if "x-amz-date" is set.
    if (interesting.containsKey(S3_ALTERNATE_DATE)) {
        interesting.put(date, "");
    }
    // These headers require that we still put a new line in after them,
    // even if they don't exist.
    if (!interesting.containsKey(contentType)) {
        interesting.put(contentType, "");
    }
    if (!interesting.containsKey(contentMd5)) {
        interesting.put(contentMd5, "");
    }
    // Add all the interesting headers
    for (Iterator<Map.Entry<String, String>> i = interesting.entrySet().iterator(); i.hasNext();) {
        final Map.Entry<String, String> entry = i.next();
        final String key = entry.getKey();
        final Object value = entry.getValue();
        if (key.startsWith(AMAZON_PREFIX)) {
            buf.append(key).append(':').append(value);
        } else {
            buf.append(value);
        }
        buf.append(LINE_SEPARATOR_UNIX);
    }
    // The CanonicalizedResource this request is working with.
    // If the request specifies a bucket using the HTTP Host header
    // (virtual hosted-style), append the bucket name preceded by a
    // "/" (e.g., "/bucketname"). For path-style requests and requests
    // that don't address a bucket, do nothing.
    if (request.getResource() != null) {
        buf.append("/" + request.getResource() + request.getURI().getRawPath());
    } else {
        buf.append(request.getURI().getRawPath());
    }
    // Amazon requires us to sort the query string parameters.
    final List<SortableBasicNameValuePair> params = sortParams(URLEncodedUtils.parse(request.getURI(), UTF_8));
    String separator = "?";
    for (final NameValuePair pair : params) {
        final String name = pair.getName(), value = pair.getValue();
        // Skip any parameters that aren't part of the
        // canonical signed string.
        if (!INTERESTING_PARAMETERS.contains(name)) {
            continue;
        }
        buf.append(separator).append(name);
        if (value != null) {
            buf.append("=").append(value);
        }
        separator = "&";
    }
    return buf.toString();
}

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

private static HttpUriRequest addHeaderParams(final HttpUriRequest request,
        final Map<String, String> headerParams) {
    // Check if the params are empty.
    if (!headerParams.isEmpty()) {
        // Iterate using the enhanced for loop synthax as the JIT will
        // optimize it away
        // See/*ww w  .  j a va2  s  .  c  o  m*/
        // http://developer.android.com/guide/practices/design/performance.html#foreach
        for (final Map.Entry<String, String> entry : headerParams.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }
    return request;
}

From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param sr              The servlet request. Must not be
 *                        {@code null}.//from  w  ww  .  jav a 2  s .c o m
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(sr);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(sr.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = sr.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, sr.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(sr.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = sr.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = sr.getReader();

            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}