Example usage for java.util Collections emptyMap

List of usage examples for java.util Collections emptyMap

Introduction

In this page you can find the example usage for java.util Collections emptyMap.

Prototype

@SuppressWarnings("unchecked")
public static final <K, V> Map<K, V> emptyMap() 

Source Link

Document

Returns an empty map (immutable).

Usage

From source file:com.common.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {/*from  w w  w  .  java  2 s  . c o  m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());

            //??
            responseHeaders = convertMaxAge(responseHeaders, request);

            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {

                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true,
                        SystemClock.elapsedRealtime() - requestStart);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}

From source file:alfio.extension.ExtensionService.java

private static ExtensionMetadata getMetadata(String name, String script) {
    return ScriptingExecutionService.executeScript(name,
            script + "\n;GSON.fromJson(JSON.stringify(getScriptMetadata()), returnClass);", //<- ugly hack, but the interop java<->js is simpler that way...
            Collections.emptyMap(), ExtensionMetadata.class, new NoopExtensionLogger());
}

From source file:com.intuit.elves.network.CustomNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {//w ww .ja v  a 2  s. c o m
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {

                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true);
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                // Dump the response in debug mode
                if (CustomLog.mDebugLogEnabled && httpResponse.getEntity() != null
                        && request instanceof CustomRequest) {
                    NetworkUtil.getResponsePayloadAsString(httpResponse.getEntity());
                }
                throw new IOException();
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                return new CustomNetworkResponse(statusCode, httpResponse.getEntity(), responseHeaders, false);
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (UnknownHostException e) {
            attemptRetryOnException("connection", request, new ServerError(e));
        } catch (ClientProtocolException e) {
            attemptRetryOnException("connection", request, new ServerError(e));
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                if (e.getCause() instanceof CustomError) {
                    throw (CustomError) e.getCause();
                }
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (httpResponse.getEntity() != null) {
                networkResponse = new CustomNetworkResponse(statusCode, httpResponse.getEntity(),
                        responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
                        || statusCode == HttpStatus.SC_BAD_GATEWAY) {
                    attemptRetryOnException("server", request, new ServerError(networkResponse));
                } else {
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError();
            }
        }
    }
}

From source file:com.machinepublishers.jbrowserdriver.CookieStore.java

/**
 * {@inheritDoc}/*from   w w w. j  a  v a 2s.  c  om*/
 */
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
    final String reqHost = canonicalHost(uri.getHost());
    final String reqPath = canonicalPath(uri.getPath());
    final boolean reqSecure = isSecure(uri.getScheme());
    final boolean reqJavascript = isJavascript(uri.getScheme());
    StringBuilder builder = new StringBuilder();
    if (reqJavascript) {
        List<Cookie> list;
        synchronized (store) {
            store.clearExpired(new Date());
            list = store.getCookies();
        }
        for (Cookie cookie : list) {
            if ((!cookie.isSecure() || reqSecure) && reqHost.endsWith(canonicalHost(cookie.getDomain()))
                    && reqPath.startsWith(canonicalPath(cookie.getPath()))) {
                if (builder.length() > 0) {
                    builder.append(';');
                }
                builder.append(cookie.getName());
                builder.append('=');
                builder.append(cookie.getValue());
            }
        }
    }
    String cookies = builder.length() == 0 ? null : builder.toString();
    Map<String, List<String>> map;
    if (cookies != null) {
        map = new HashMap<String, List<String>>();
        map.put("Cookie", Arrays.asList(cookies));
    } else {
        map = Collections.emptyMap();
    }
    return map;
}

From source file:com.sunchenbin.store.feilong.core.lang.ArrayUtil.java

/**
 * array ./*from   w  w  w.j  a  va  2 s  .  co m*/
 * 
 * <code>
 * <pre>
 * 
 * Example 1:
 * if Integer[] array = { 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8 };
 * 
 * will return 
 *      {
 *         "1":         [
 *             1,
 *             1,
 *             1
 *         ],
 *         "2":         [
 *             2,
 *             2
 *         ],
 *         "3": [3],
 *         "4": [4],
 *         "5":         [
 *             5,
 *             5
 *         ],
 *         "6": [6],
 *         "7": [7],
 *         "8":         [
 *             8,
 *             8
 *         ]
 *     }
 * }
 * </pre></code>
 *
 * @param <T>
 *            the generic type
 * @param array
 *            the array
 * @return the map< t, list< t>>
 * @since 1.0.8
 */
public static <T> Map<T, List<T>> group(T[] array) {
    if (null == array) {
        return Collections.emptyMap();
    }
    //  ??? HashMap TreeMap
    Map<T, List<T>> map = new WeakHashMap<T, List<T>>(array.length);
    for (T t : array) {
        List<T> valueList = map.get(t);
        if (null == valueList) {
            valueList = new ArrayList<T>();
        }
        valueList.add(t);
        map.put(t, valueList);
    }
    return map;
}

From source file:com.playonlinux.core.config.CompatibleConfigFileFormat.java

private Map<String, String> getMap() {
    try {//from w w  w  . j  a  v a  2 s.  c  o m
        final Map<String, String> results = new HashMap<>();
        final Map<?, ?> tmpResults = mapper.readValue(configFile, Map.class);
        for (Entry<?, ?> entry : tmpResults.entrySet()) {
            if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
                results.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        return results;
    } catch (JsonParseException | JsonMappingException e) {
        LOGGER.debug("The file does not seems to be a JSON format. Trying legacy PlayOnLinux config file", e);
        return getLegacyMap();
    } catch (IOException e) {
        LOGGER.debug("Error while reading the file. Will assume that the config file is EMPTY", e);
        return Collections.emptyMap();
    }
}

From source file:mtsar.processors.meta.ZenCrowd.java

@Nonnull
@Override//from   w w w  .  j a va 2 s . c o  m
public Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers) {
    requireNonNull(stage, "the stage provider should not provide null");
    if (workers.isEmpty())
        return Collections.emptyMap();
    final Map<Integer, Worker> workerIds = workers.stream()
            .collect(Collectors.toMap(Worker::getId, Function.identity()));
    final Models.ZenModel<Integer, Integer, String> zenModel = compute(stage, answerDAO, getTaskMap())
            .getZenModel();
    final ZenCrowdEM<Integer, Integer, String> zenCrowd = new ZenCrowdEM<>(zenModel);
    zenCrowd.computeLabelEstimates();
    try {
        @SuppressWarnings("unchecked")
        final Map<Integer, Double> reliability = (Map<Integer, Double>) FieldUtils.readField(zenCrowd,
                "workerReliabilityMap", true);
        final Map<Integer, WorkerRanking> rankings = reliability.entrySet().stream()
                .filter(entry -> workerIds.containsKey(entry.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> new WorkerRanking.Builder()
                        .setWorker(workerIds.get(entry.getKey())).setReputation(entry.getValue()).build()));
        return rankings;
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.elasticsearch.backwards.IndexingIT.java

private void updateIndexSetting(String name, Settings settings) throws IOException {
    assertOK(client().performRequest("PUT", name + "/_settings", Collections.emptyMap(),
            new StringEntity(Strings.toString(settings), ContentType.APPLICATION_JSON)));
}

From source file:com.android.volley1.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        //            byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {//from  ww w.  jav a  2  s .c  o m
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);

            int statusCode = httpResponse.getResponseCode();

            Log.e(TAG, statusCode + "");

            //                int statusCode = statusLine.getStatusCode();
            //                StatusLine statusLine = httpResponse.getStatusLine();

            responseHeaders = httpResponse.getHeaders();
            // Handle cache validation.

            if (statusCode == HttpCodeDef.SC_NOT_MODIFIED) {

                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpCodeDef.SC_NOT_MODIFIED, responseHeaders, null, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpCodeDef.SC_NOT_MODIFIED, entry.responseHeaders,
                        Okio.source(new ByteArrayInputStream(entry.data)), true,
                        SystemClock.elapsedRealtime() - requestStart);
            }

            // Some responses such as 204s do not have content.  We must check.
            /*      if (httpResponse.getInputStream() != null) {
                    
            responseContents = streamToBytes(httpResponse);
                    
                    
                  } else {
            // Add 0 byte response as a way of honestly representing a
            // no-content request.
            responseContents = new byte[0];
                  }
            */
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, /* responseContents,*/ statusCode);

            // FIXME: 4/13/16 ????
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }

            return new NetworkResponse(statusCode, responseHeaders, Okio.source(httpResponse.getInputStream()),
                    false, SystemClock.elapsedRealtime() - requestStart);

            /*        if (responseContents != null) {
            return new NetworkResponse(statusCode, responseHeaders, responseContents, false,
                    SystemClock.elapsedRealtime() - requestStart);
                    } else {
                    
                    
            return new NetworkResponse(statusCode, responseHeaders, httpResponse.getInputStream(), false,
                    SystemClock.elapsedRealtime() - requestStart);
                    
                    
                    }*/

        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getResponseCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (httpResponse.getInputStream() != null) {
                networkResponse = new NetworkResponse(statusCode, responseHeaders,
                        Okio.source(httpResponse.getInputStream()), false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpCodeDef.SC_UNAUTHORIZED || statusCode == HttpCodeDef.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:mp.platform.cyclone.webservices.utils.server.FieldHelper.java

/**
 * Builds a map with field values//from   www  .j ava 2s . c o  m
 */
public Map<String, String> toMap(final Collection<? extends CustomField> fields,
        final Collection<? extends CustomFieldValue> customValues) {
    if (CollectionUtils.isEmpty(fields) || CollectionUtils.isEmpty(customValues)) {
        return Collections.emptyMap();
    }
    final Map<String, String> values = new LinkedHashMap<String, String>();
    for (final CustomField field : fields) {
        final String valueAsString = getFieldValue(field, customValues);
        if (valueAsString != null) {
            values.put(field.getInternalName(), valueAsString);
        }
    }
    return values;
}