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:edu.northwestern.bioinformatics.studycalendar.web.admin.BaseUserProvisioningCommand.java

protected BaseUserProvisioningCommand(List<PscUser> users,
        ProvisioningSessionFactory provisioningSessionFactory,
        ApplicationSecurityManager applicationSecurityManager) {
    this.users = users;
    this.applicationSecurityManager = applicationSecurityManager;
    this.provisioningSessionFactory = provisioningSessionFactory;

    // locked down by default
    this.provisionableRoles = Collections.emptyList();
    this.provisionableSites = Collections.emptyList();
    this.provisionableRoleGroups = Collections.emptyMap();
    this.provisionableSiteIdentifiers = Collections.emptySet();
    this.provisionableManagedStudies = Collections.emptyList();
    this.provisionableManagedStudyIdentifiers = Collections.emptySet();
    this.provisionableParticipatingStudies = Collections.emptyList();
    this.provisionableParticipatingStudyIdentifiers = Collections.emptySet();
}

From source file:com.selene.volley.tool.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    // Determine if request had non-http perform.
    NetworkResponse networkResponse = request.perform();
    if (networkResponse != null) {
        return networkResponse;
    }//  w w w  .  java 2s  .  co m
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        // If the request was cancelled already,
        // do not perform the network request.
        if (request.isCanceled()) {
            request.finish("perform-discard-cancelled");
            mDelivery.postCancel(request);
            throw new NetworkError(networkResponse);
        }
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // prepare to perform this request, normally is reset the request headers.
            request.prepare();
            // 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());
            responseContents = request.handleResponse(httpResponse, mDelivery);
            // 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);
            }
            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content. We must check. alternative by handleResponse
            //            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;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                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 == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:ddf.catalog.transformer.csv.CsvQueryResponseTransformer.java

/**
 * @param upstreamResponse the SourceResponse to be converted.
 * @param arguments this transformer accepts 3 parameters in the 'arguments' map. 1) key:
 *     'hiddenFields' value: a java.util.Set containing Attribute names (as Strings) to be
 *     excluded from the output. 2) key: 'attributeOrder' value: a java.utilList containing
 *     Attribute name (as Strings) to identify the order that the columns will appear in the
 *     output. 3) key: 'aliases' value: a java.util.Map whose keys are attribute names and values
 *     are the how that attribute column should be aliased in the output. For example, if the key
 *     is 'title' and the value is 'Product' then the resulting CSV will have a column name of
 *     'Product' instead of 'title'.//from   ww w .  j  ava2  s  .  com
 * @return a BinaryContent object that contains an InputStream with the CSV content.
 * @throws CatalogTransformerException during processing, the CSV output is written to an
 *     Appendable, whose 'append()' method signature declares that it throws IOException. When
 *     that Appendable throws IOException, this class will theoretically convert that into a
 *     CatalogTransformerException and raise that. Because this implementation uses a
 *     StringBuilder which doesn't throw IOException, this will never occur.
 */
@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments)
        throws CatalogTransformerException {

    Set<String> hiddenFields = Optional.ofNullable((Set<String>) arguments.get(HIDDEN_FIELDS_KEY))
            .orElse(Collections.emptySet());

    List<String> attributeOrder = Optional.ofNullable((List<String>) arguments.get(COLUMN_ORDER_KEY))
            .orElse(Collections.emptyList());

    Map<String, String> columnAliasMap = Optional
            .ofNullable((Map<String, String>) arguments.get(COLUMN_ALIAS_KEY)).orElse(Collections.emptyMap());

    Set<AttributeDescriptor> allAttributeDescriptors = getAllRequestedAttributes(upstreamResponse.getResults(),
            hiddenFields);

    List<AttributeDescriptor> sortedAttributeDescriptors = sortAttributes(allAttributeDescriptors,
            attributeOrder);

    Appendable csv = writeSearchResultsToCsv(upstreamResponse, columnAliasMap, sortedAttributeDescriptors);

    return createResponse(csv);
}

From source file:mysql5.MySQL5PlayerDAO.java

@Override
public Map<Integer, String> getPlayerNames(Collection<Integer> playerObjectIds) {

    if (GenericValidator.isBlankOrNull(playerObjectIds)) {
        return Collections.emptyMap();
    }//from   www  .java 2s  . c  om

    Map<Integer, String> result = Maps.newHashMap();

    String sql = "SELECT id, `name` FROM players WHERE id IN(%s)";
    sql = String.format(sql, StringUtils.join(playerObjectIds, ", "));
    PreparedStatement s = DB.prepareStatement(sql);
    try {
        ResultSet rs = s.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            result.put(id, name);
        }
    } catch (SQLException e) {
        throw new RuntimeException("Failed to load player names", e);
    } finally {
        DB.close(s);
    }

    return result;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.NavigationController.java

Map<String, Object> getValues(Individual ind, OntModel displayOntModel, OntModel assertionModel,
        Map<String, Object> baseValues) {
    if (ind == null)
        return Collections.emptyMap();

    /* Figure out what ValueFactories are specified in the display ontology for this individual. */
    Set<ValueFactory> valueFactories = new HashSet<ValueFactory>();
    displayOntModel.enterCriticalSection(Model.READ);
    StmtIterator stmts = ind.listProperties(DisplayVocabulary.REQUIRES_VALUES);
    try {/*from   w  w w.j a va2  s .c  om*/
        while (stmts.hasNext()) {
            Statement stmt = stmts.nextStatement();
            RDFNode obj = stmt.getObject();
            valueFactories.addAll(getValueFactory(obj, displayOntModel));
        }
    } finally {
        stmts.close();
        displayOntModel.leaveCriticalSection();
    }

    /* Get values from the ValueFactories. */
    HashMap<String, Object> values = new HashMap<String, Object>();
    values.putAll(baseValues);
    for (ValueFactory vf : valueFactories) {
        values.putAll(vf.getValues(assertionModel, values));
    }
    return values;
}

From source file:com.arpnetworking.metrics.vertx.SinkHandlerTest.java

@Test
public void testHandleWithMessageWithoutGaugeSamples() throws JsonProcessingException {
    final String messageBody = OBJECT_MAPPER
            .writeValueAsString(ImmutableMap.of(TIMER_SAMPLES_KEY, Collections.emptyMap(), COUNTER_SAMPLES_KEY,
                    Collections.emptyMap(), ANNOTATIONS_KEY, Collections.emptyMap()));
    Mockito.doReturn(messageBody).when(_message).body();
    _handler.handle(_message);//from ww  w. j av a  2 s  .  c om
    Mockito.verifyZeroInteractions(_mockSink);
}

From source file:com.kescoode.android.yong.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  ww  . j a v  a2  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,
                            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);
            }

            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                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(request, 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);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                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 == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", 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:com.liferay.portal.template.velocity.internal.VelocityTemplateTest.java

@Before
public void setUp() throws Exception {
    VelocityEngineConfiguration velocityEngineConfiguration = ConfigurableUtil
            .createConfigurable(VelocityEngineConfiguration.class, Collections.emptyMap());

    _templateContextHelper = new MockTemplateContextHelper();

    _velocityEngine = new VelocityEngine();

    boolean cacheEnabled = false;

    ExtendedProperties extendedProperties = new FastExtendedProperties();

    extendedProperties.setProperty(VelocityEngine.DIRECTIVE_IF_TOSTRING_NULLCHECK,
            String.valueOf(velocityEngineConfiguration.directiveIfToStringNullCheck()));
    extendedProperties.setProperty(VelocityEngine.EVENTHANDLER_METHODEXCEPTION,
            LiferayMethodExceptionEventHandler.class.getName());
    extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,
            StringUtil.merge(velocityEngineConfiguration.restrictedClasses()));
    extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_PACKAGES,
            StringUtil.merge(velocityEngineConfiguration.restrictedPackages()));
    extendedProperties.setProperty(VelocityEngine.RESOURCE_LOADER, "liferay");
    extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".cache",
            String.valueOf(cacheEnabled));
    extendedProperties.setProperty(// ww w .ja  va  2  s.co  m
            "liferay." + VelocityEngine.RESOURCE_LOADER + ".resourceModificationCheckInterval",
            velocityEngineConfiguration.resourceModificationCheckInterval() + "");
    extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".class",
            LiferayResourceLoader.class.getName());
    extendedProperties.setProperty(VelocityEngine.RESOURCE_MANAGER_CLASS,
            LiferayResourceManager.class.getName());
    extendedProperties.setProperty(
            "liferay." + VelocityEngine.RESOURCE_MANAGER_CLASS + ".resourceModificationCheckInterval",
            velocityEngineConfiguration.resourceModificationCheckInterval() + "");
    extendedProperties.setProperty(VelocityTemplateResourceLoader.class.getName(), _templateResourceLoader);
    extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
            velocityEngineConfiguration.logger());
    extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
            velocityEngineConfiguration.loggerCategory());
    extendedProperties.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName());
    extendedProperties.setProperty(VelocityEngine.VM_LIBRARY,
            StringUtil.merge(velocityEngineConfiguration.velocimacroLibrary()));
    extendedProperties.setProperty(VelocityEngine.VM_LIBRARY_AUTORELOAD, String.valueOf(!cacheEnabled));
    extendedProperties.setProperty(VelocityEngine.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL,
            String.valueOf(!cacheEnabled));

    _velocityEngine.setExtendedProperties(extendedProperties);

    _velocityEngine.init();
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

@Override
public JsonObject performIO_Action() {
    return performio(url, Collections.emptyMap());
}

From source file:com.hortonworks.streamline.streams.metrics.storm.graphite.GraphiteWithStormQuerier.java

/**
 * {@inheritDoc}//w  ww  .  java  2  s .  c o m
 */
@Override
public Map<Long, Double> getMetrics(String topologyName, String componentId, String metricName,
        AggregateFunction aggrFunction, long from, long to) {
    URI targetUri = composeQueryParameters(topologyName, componentId, metricName, aggrFunction, from, to);

    log.debug("Calling {} for querying metric", targetUri.toString());

    List<Map<String, ?>> responseList = JsonClientUtil.getEntity(client.target(targetUri), List.class);
    if (responseList.isEmpty()) {
        return Collections.emptyMap();
    }

    Map<String, ?> metrics = responseList.get(0);
    List<List<Number>> dataPoints = (List<List<Number>>) metrics.get("datapoints");
    return formatDataPointsFromGraphiteToMap(dataPoints);
}