Example usage for java.util Collections singletonMap

List of usage examples for java.util Collections singletonMap

Introduction

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

Prototype

public static <K, V> Map<K, V> singletonMap(K key, V value) 

Source Link

Document

Returns an immutable map, mapping only the specified key to the specified value.

Usage

From source file:Main.java

/**
 * Copies the given {@link Map} containing another {@link Map} into a new
 * {@link Map}.//from w w w  .ja v a  2 s .  c  om
 * 
 * @param <A>
 *            the type of the keys of the outer map
 * @param <B>
 *            the type of the keys of the map, that is the value of the
 *            outer map
 * @param <C>
 *            the type of the values of the map, that is the value of the
 *            outer map
 * @param data
 *            the given map
 * @return If the given map was empty, a {@link Collections#emptyMap()} is
 *         returned<br>
 *         If the given map contained only one entry, a
 *         {@link Collections#singletonMap(Object, Object)}, containing
 *         said entry, is returned <br>
 *         If the given map contained more than one element, a
 *         {@link Collections#unmodifiableMap(Map)}, containing the entries
 *         of the given map, is returned.
 */
public static <A, B, C> Map<A, Map<B, C>> copyDeep(Map<A, Map<B, C>> data) {
    final int size = data.size();

    switch (size) {
    case 0:
        return Collections.emptyMap();
    case 1:
        final A key = data.keySet().iterator().next();
        return Collections.singletonMap(key, copy(data.get(key)));
    default:
        final Map<A, Map<B, C>> newData = new HashMap<A, Map<B, C>>();
        for (Map.Entry<A, Map<B, C>> entry : data.entrySet()) {
            newData.put(entry.getKey(), copy(entry.getValue()));
        }
        return Collections.unmodifiableMap(newData);
    }
}

From source file:ch.hortis.mongodb.training.blog.oauth.BlogTokenEnhancer.java

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
    result.setAdditionalInformation(Collections.singletonMap("client_id",
            (Object) authentication.getAuthorizationRequest().getClientId()));
    return result;
}

From source file:org.neo4j.cineasts.movieimport.MovieDbApiClient.java

private Map loadJsonData(String url) {
    try {/*  w  w w . j  ava  2  s  .  co m*/
        Map value = mapper.readValue(new URL(url), Map.class);
        if (value.isEmpty()) {
            return Collections.singletonMap("not_found", System.currentTimeMillis());
        }
        return value;
    } catch (Exception e) {
        throw new RuntimeException("Failed to get data from " + url, e);
    }
}

From source file:nl.conspect.legacy.user.web.LogoutController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();//from w w w  .  j  av  a  2 s .  c o  m
    }
    return new ModelAndView("redirect:/app/index", Collections.singletonMap("msg", "Logout successful."));
}

From source file:org.cloudfoundry.identity.uaa.login.ProfileControllerTests.java

public void testGet() {
    controller.setLinks(Collections.singletonMap("foo", "http://example.com"));
    Mockito.when(restTemplate.getForObject(approvalsUri, Set.class))
            .thenReturn(Collections.singleton(Collections.singletonMap("clientId", "foo")));
    Model model = new ExtendedModelMap();
    controller.get(model);/*from  w  w w  .ja v a2  s.  c  o  m*/
    assertTrue(model.containsAttribute("links"));
    assertTrue(model.containsAttribute("approvals"));
}

From source file:com.graphaware.server.TxParticipationIntegrationTest.java

@Test
public void invalidTransactionShouldResultInException() {
    System.out.println(get(baseUrl() + "/graphaware/greeting", Collections.singletonMap("_GA_TX_ID", "invalid"),
            HttpStatus.SC_BAD_REQUEST));
}

From source file:org.elasticsearch.http.DetailedErrorsEnabledIT.java

public void testThatErrorTraceWorksByDefault() throws IOException {
    try {//from ww w.  ja v a  2s  .  c  o m
        getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"));
        fail("request should have failed");
    } catch (ResponseException e) {
        Response response = e.getResponse();
        assertThat(response.getHeader("Content-Type"), containsString("application/json"));
        assertThat(EntityUtils.toString(response.getEntity()),
                containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; "
                        + "nested: ActionRequestValidationException[Validation Failed: 1:"));
    }

    try {
        getRestClient().performRequest("DELETE", "/");
        fail("request should have failed");
    } catch (ResponseException e) {
        Response response = e.getResponse();
        assertThat(response.getHeader("Content-Type"), containsString("application/json; charset=UTF-8"));
        assertThat(EntityUtils.toString(response.getEntity()),
                not(containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; "
                        + "nested: ActionRequestValidationException[Validation Failed: 1:")));
    }
}

From source file:com.xyxy.platform.examples.showcase.demos.web.MashupServerController.java

@RequestMapping(value = "/web/mashup", produces = MediaTypes.JAVASCRIPT_UTF_8)
@ResponseBody/*from   w w  w . j  a v  a2 s  . co  m*/
public String mashup1(@RequestParam(DEFAULT_JQUERY_JSONP_CALLBACK_PARM_NAME) String callbackName) {

    // ??JSON.
    Map<String, String> map = Collections.singletonMap("content", "<p>?</p>");

    // .
    return mapper.toJsonP(callbackName, map);
}

From source file:com.graphaware.common.representation.GraphDetachedNodeTest.java

@Test
public void nodeRepresentationIsCorrectlyConvertedToJson() throws JsonProcessingException, JSONException {
    GraphDetachedNode representation = new GraphDetachedNode(0, new String[] { "Label1, Label2" },
            Collections.singletonMap("key", "value"));
    String actualStr = mapper.writeValueAsString(representation);
    System.out.println(actualStr);
    assertEquals("{\"graphId\":0,\"properties\":{\"key\":\"value\"},\"labels\":[\"Label1, Label2\"]}",
            actualStr, true);/*from  w ww  .  j  a  v  a2s . c o m*/
}

From source file:com.graphaware.common.representation.GraphDetachedRelationshipTest.java

@Test
public void relationshipRepresentationIsCorrectlyConvertedToJson()
        throws JsonProcessingException, JSONException {
    DetachedRelationship representation = new GraphDetachedRelationship(0, 1, 2, "TYPE",
            Collections.singletonMap("key", "value"));
    assertEquals(//ww w. j a  v a 2 s .co m
            "{\"graphId\":0,\"properties\":{\"key\":\"value\"},\"startNodeGraphId\":1,\"endNodeGraphId\":2,\"type\":\"TYPE\"}",
            mapper.writeValueAsString(representation), true);
}