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.aitangba.volley.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 {/*  w  ww.  jav  a 2  s  .  co  m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            int statusCode = httpResponse.getStatusCode();

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

                Cache.Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpURLConnection.HTTP_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(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data,
                        entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }

            // Handle moved resources
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // 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, httpResponse.getStatusCode());

            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.getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                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 == HttpURLConnection.HTTP_UNAUTHORIZED
                        || statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                        || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}

From source file:mtsar.processors.answer.KOSAggregator.java

@Override
@Nonnull//ww  w . jav a2s . c o m
public Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks) {
    requireNonNull(stage, "the stage provider should not provide null");
    checkArgument(tasks.stream().allMatch(SINGLE_BINARY_TYPE),
            "tasks should be of the type single and have only two possible answers");
    if (tasks.isEmpty())
        return Collections.emptyMap();

    final List<Answer> answers = answerDAO.listForStage(stage.getId());
    if (answers.isEmpty())
        return Collections.emptyMap();

    final Map<Integer, Task> taskMap = taskDAO.listForStage(stage.getId()).stream().filter(SINGLE_BINARY_TYPE)
            .collect(Collectors.toMap(Task::getId, Function.identity()));

    final Map<Integer, BiMap<String, Short>> answerIndex = taskMap.values().stream()
            .collect(Collectors.toMap(Task::getId, task -> {
                final BiMap<String, Short> map = HashBiMap.create(2);
                map.put(task.getAnswers().get(0), (short) -1);
                map.put(task.getAnswers().get(1), (short) +1);
                return map;
            }));

    /* rows are tasks IDs, columns are worker IDs, values are answers */
    final Table<Integer, Integer, Short> graph = HashBasedTable.create();

    for (final Answer answer : answers) {
        if (!answer.getType().equalsIgnoreCase(AnswerDAO.ANSWER_TYPE_ANSWER))
            continue;
        graph.put(answer.getTaskId(), answer.getWorkerId(),
                answerIndex.get(answer.getTaskId()).get(answer.getAnswers().get(0)));
    }

    final Map<Integer, Double> estimations = converge(graph, getKMax());
    return estimations.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, estimation -> {
        final String answer = answerIndex.get(estimation.getKey()).inverse()
                .get(estimation.getValue() < 0 ? (short) -1 : (short) +1);
        return new AnswerAggregation.Builder().setTask(taskMap.get(estimation.getKey())).addAnswers(answer)
                .build();
    }));
}

From source file:com.cloudmine.api.rest.response.CMObjectResponse.java

/**
 * Internal use only//  w  ww.  java 2s  . c om
 * @param response
 * @param code
 */
public CMObjectResponse(String response, int code) {
    super(response, code); //TODO this is copy pasta code from above :( thats bad
    if (hasSuccess()) {
        String success = JsonUtilities.jsonMapToKeyMap(getMessageBody()).get(SUCCESS);
        Map<String, ? extends CMObject> tempMap;
        try {
            tempMap = JsonUtilities.jsonToClassMap(success);
        } catch (ConversionException jce) {
            tempMap = Collections.emptyMap();
            LOG.error("Trouble converting: " + success + ", using empty map");
        }
        objectMap = tempMap;
    } else {
        objectMap = Collections.emptyMap();
    }
}

From source file:eu.itesla_project.histodb.client.impl.OfflineDbImpl.java

@Override
public List<String> listWorkflows() {
    List<String> ls = new ArrayList<>();
    HistoDbConfig config = new HistoDbConfig(connectParams, null, storeName, null);
    try (HistoDbHttpClientImpl httpClient = new HistoDbHttpClientImpl(null)) {
        try (InputStream is = httpClient
                .getHttpRequest(new HistoDbUrl(config, ".json", Collections.emptyMap()))) {
            String json = new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8);
            JSONObject jsonObj = JSONObject.fromObject(json);
            for (Object name : jsonObj.names()) {
                if (((String) name).startsWith(SIMULATIONS_PREFIX)) {
                    String workflowId = ((String) name).substring(SIMULATIONS_PREFIX.length());
                    ls.add(workflowId);//  ww w.  j  a  v a  2s.c  om
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return ls;
}

From source file:jef.tools.collection.CollectionUtils.java

/**
 * ?MapMap????/*from  w ww.  j av  a2s . c  o  m*/
 * 
 * @param array
 *            
 * @param keyExtractor
 *            ???
 * @return ??????Map?key?
 *         {@linkplain #group(Collection, Function)}
 */
public static <K, V> Map<K, V> group(V[] array, Function<V, K> keyExtractor) {
    if (array == null || array.length == 0)
        return Collections.emptyMap();
    Map<K, V> result = new HashMap<K, V>(array.length);
    for (V value : array) {
        K key = keyExtractor.apply(value);
        result.put(key, value);
    }
    return result;
}

From source file:eu.nubomedia.tutorial.repository.UserSession.java

public String startRecording(WebSocketSession session, String sdpOffer) {
    // KurentoClient
    kurentoClient = KurentoClient.create();
    log.info("Created kurentoClient (session {})", sessionId);

    // Media pipeline
    mediaPipeline = kurentoClient.createMediaPipeline();
    log.info("Created Media Pipeline for recording {} (session {})", mediaPipeline.getId(), sessionId);

    // Repository item (recorder)
    try {/*from w ww  .  j  a  va2 s . c  o m*/
        Map<String, String> metadata = Collections.emptyMap();
        repositoryItemRecorder = repositoryClient.createRepositoryItem(metadata);

    } catch (Exception e) {
        log.warn("Exception creating repositoryItemRecorder", e);

        // This code allows to run the demo in local without a repository server
        repositoryItemRecorder = new RepositoryItemRecorder();
        String id = String.valueOf(System.currentTimeMillis());
        repositoryItemRecorder.setId(id);
        repositoryItemRecorder.setUrl("file:///tmp/" + id + ".webm");
    }

    log.info("Repository item id={}, url={}", repositoryItemRecorder.getId(), repositoryItemRecorder.getUrl());

    // Media elements and connectivity
    webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();
    recorderEndpoint = new RecorderEndpoint.Builder(mediaPipeline, repositoryItemRecorder.getUrl())
            .withMediaProfile(MediaProfileSpecType.WEBM).build();
    webRtcEndpoint.connect(webRtcEndpoint);
    webRtcEndpoint.connect(recorderEndpoint);

    // WebRTC negotiation
    String sdpAnswer = performWebRtcNegotiation(session, sdpOffer);

    // Start recording
    recorderEndpoint.record();

    return sdpAnswer;
}

From source file:com.threewks.thundr.http.URLEncoder.java

/**
 * Encodes the given query parameters into the query string such that it returns <code>?param1=value1&param2=value2&....</code>.
 * /*from   w w w.  java2s.  c  o m*/
 * Uses the given {@link TransformerManager} on parameters to determine their string representation.
 * Returns an empty string if no parameters are provided.
 * 
 * @param parameters
 * @return
 */
@SuppressWarnings("unchecked")
public static final String encodeQueryString(Map<String, Object> parameters,
        TransformerManager transformerManager) {
    if (parameters == null) {
        parameters = Collections.emptyMap();
    }
    Map<String, Object> delegate = new LinkedHashMap<>();
    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        Object valueObj = entry.getValue();
        String value = "";
        if (valueObj != null) {
            Class<Object> type = (Class<Object>) entry.getValue().getClass();
            ETransformer<Object, String> transformer = transformerManager.getTransformerSafe(type,
                    String.class);
            value = transformer.from(entry.getValue());
        }
        delegate.put(entry.getKey(), value);
    }
    return encodeQueryString(delegate);
}

From source file:com.ejisto.core.classloading.scan.ScanAction.java

@Override
protected void compute() {
    if (groupedFields.isEmpty()) {
        log.debug("done. Exiting");
        return;/* w  w w  .  ja v  a2 s .  co m*/
    }
    int classesSize = groupedFields.size();
    Map<String, List<MockedField>> toBeScanned;
    Map<String, List<MockedField>> toBeForked;
    if (classesSize > SIZE_THRESHOLD) {
        log.debug("forking...");
        toBeScanned = groupedFields.entrySet().stream().limit(SIZE_THRESHOLD)
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        toBeForked = groupedFields.entrySet().stream().filter(e -> !toBeScanned.containsKey(e.getKey()))
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
    } else {
        toBeScanned = groupedFields;
        toBeForked = Collections.emptyMap();
    }
    invokeAll(new ScanAction(baseDirectory, contextPath, toBeForked, mockedFieldsRepository));
    scanGroups(toBeScanned);
}

From source file:com.github.nmorel.gwtjackson.client.ser.bean.AbstractBeanJsonSerializer.java

/**
 * Initialize the {@link Map} containing the {@link SubtypeSerializer}. Returns an empty map if the bean has no subtypes.
 *//*w  ww  . ja va2s .  com*/
protected Map<Class, SubtypeSerializer> initMapSubtypeClassToSerializer() {
    return Collections.emptyMap();
}

From source file:eu.stratosphere.nephele.plugins.PluginManager.java

private PluginManager(final String configDir, final PluginLookupService pluginLookupService) {

    // Check if the configuration file exists
    final File configFile = new File(configDir + File.separator + PLUGIN_CONFIG_FILE);
    if (configFile.exists()) {
        this.plugins = loadPlugins(configFile, pluginLookupService);
    } else {/*ww  w  . j av  a 2 s.  c  o m*/
        this.plugins = Collections.emptyMap();
        LOG.warn("Unable to load plugins: configuration file " + configFile.getAbsolutePath() + " not found");
    }
}