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:com.amazonaws.sample.entitlement.rs.JaxRsAdministrationService.java

/**
 * Add user/*  ww  w . ja  v  a  2s.  c o  m*/
 * @param authorization string that is associated to the identity of the requester
 * @return prettified JSON
 */
@POST
@Path("/users/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addUser(String user, @HeaderParam("Authorization") String authorization) {
    try {
        administrationService.getUserFromAuthorization(authorization);
        String response = administrationService.addUser(user);
        return response(Status.OK, response);
    } catch (AuthorizationException e) {
        String authenticateHeader = e.getAuthenticateHeader();

        if (authenticateHeader == null) {
            return response(Status.UNAUTHORIZED, e.getMessage());
        } else {
            return response(Status.UNAUTHORIZED, e.getMessage(),
                    Collections.singletonMap("WWW-Authenticate", authenticateHeader));
        }
    } catch (ApplicationBadStateException e) {
        return response(Status.CONFLICT, e.getMessage());
    } catch (UserBadIdentifierException e) {
        return response(Status.CONFLICT, e.getMessage());
    }
}

From source file:com.amazonaws.auth.profile.ProfilesConfigFileWriter.java

/**
 * Modify one profile in the existing credentials file by in-place
 * modification. This method will rename the existing profile if the
 * specified Profile has a different name.
 *
 * @param destination/*from   ww  w .ja v  a 2 s.  c  o  m*/
 *            The destination file to modify
 * @param profileName
 *            The name of the existing profile to be modified
 * @param newProfile
 *            The new Profile object.
 */
public static void modifyOneProfile(File destination, String profileName, Profile newProfile) {
    final Map<String, Profile> modifications = Collections.singletonMap(profileName, newProfile);

    modifyProfiles(destination, modifications);
}

From source file:org.atomserver.core.dbstore.dao.impl.rwimpl.AbstractDAOiBatisImpl.java

public Date selectSysDate() {
    if (testingForceFailure) {
        throw new RuntimeException("THIS IS A FAKE FAILURE FROM AbstractDAOiBatisImpl.testingForceFailure");
    }/*  ww  w  .j a  v a2 s . c o  m*/

    return (Date) (getSqlMapClientTemplate().queryForObject("selectSysDate",
            Collections.singletonMap("dbType", getDatabaseType())));
}

From source file:org.cloudfoundry.identity.uaa.integration.VmcUserIdTranslationEndpointIntegrationTests.java

@BeforeOAuth2Context
@OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
public void setUpUserAccounts() {

    // If running against vcap we don't want to run these tests because they create new user accounts
    // Assume.assumeTrue(!testAccounts.isProfileActive("vcap"));

    RestOperations client = serverRunning.getRestTemplate();

    ScimUser user = new ScimUser();
    user.setUserName(JOE);/*ww  w  .jav a 2  s.c om*/
    user.setName(new ScimUser.Name("Joe", "User"));
    user.addEmail("joe@blah.com");
    user.setGroups(Arrays.asList(new Group(null, "uaa.user"), new Group(null, "orgs.foo")));

    ResponseEntity<ScimUser> newuser = client.postForEntity(serverRunning.getUrl(userEndpoint), user,
            ScimUser.class);

    joe = newuser.getBody();
    assertEquals(JOE, joe.getUserName());

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("password");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT, new HttpEntity<PasswordChangeRequest>(change, headers), null, joe.getId());
    assertEquals(HttpStatus.OK, result.getStatusCode());

    // The implicit grant for vmc requires extra parameters in the authorization request
    context.setParameters(Collections.singletonMap("credentials",
            testAccounts.getJsonCredentials(joe.getUserName(), "password")));

}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientImplIntegrationTest.java

@Before
public void setUp() {
    ArchaiusConfig.initialize();/*from  w w w .  j  av a 2 s  .  c  o  m*/
    ArchaiusConfig.getConfiguration()
            .setProperty(SERVICE_NAME + CaravanHttpServiceConfig.THROW_EXCEPTION_FOR_STATUS_500, true);
    wireMockHost = "localhost:" + wireMock.port();

    context.registerInjectActivateService(new SimpleLoadBalancerFactory());
    serviceConfig = context.registerInjectActivateService(new CaravanHttpServiceConfig(),
            getServiceConfigProperties(wireMockHost, "auto"));
    context.registerInjectActivateService(new CaravanHttpThreadPoolConfig(),
            ImmutableMap.of(CaravanHttpThreadPoolConfig.THREAD_POOL_NAME_PROPERTY, "default"));

    context.registerInjectActivateService(new LoadBalancerCommandFactory());
    context.registerInjectActivateService(new HttpClientFactoryImpl());

    context.registerInjectActivateService(new CaravanHttpClientConfig(),
            Collections.singletonMap(CaravanHttpClientConfig.SERVLET_CLIENT_ENABLED, true));
    context.registerInjectActivateService(new ServletHttpClient());
    context.registerInjectActivateService(new ApacheHttpClient());
    context.registerInjectActivateService(new RibbonHttpClient());

    client = context.registerInjectActivateService(new CaravanHttpClientImpl());

    // setup wiremock
    wireMock.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
    wireMock.stubFor(get(urlEqualTo(HTTP_500_URI))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
    wireMock.stubFor(get(urlEqualTo(CONNECT_TIMEOUT_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(get(urlEqualTo(RESPONSE_TIMEOUT_URI))
            .willReturn(aResponse().withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8)
                    .withBody(DUMMY_CONTENT).withFixedDelay(1000)));

    assertTrue(client.hasValidConfiguration(SERVICE_NAME));

}

From source file:org.terasoluna.gfw.web.logging.TraceLoggingInterceptorTest.java

/**
 * PreHandleHttpServletRequestHttpServletResponseObject<br>
 * Log output//w ww  .j  av  a  2 s .c o  m
 * @throws Exception
 * @throws NoSuchMethodException
 */
@Test
public void testPreHandle_LogOutput() throws Exception {

    // parameter create
    HandlerMethod paramHandler = new HandlerMethod(controller,
            TraceLoggingInterceptorController.class.getMethod("createForm"));

    try {
        // run
        interceptor.preHandle(request, response, paramHandler);
    } catch (Exception e) {
        fail("illegal case");
    }

    String logMessage = jdbcTemplate.queryForObject(
            "SELECT FORMATTED_MESSAGE FROM LOGGING_EVENT WHERE EVENT_ID=:id", Collections.singletonMap("id", 1),
            String.class);
    Long startTime = (Long) request.getAttribute(TraceLoggingInterceptor.class.getName() + ".startTime");

    assertThat(logMessage, is("[START CONTROLLER] TraceLoggingInterceptorController.createForm()"));
    assertThat(startTime, notNullValue());
}

From source file:org.cloudfoundry.identity.uaa.oauth.approval.ApprovalsAdminEndpointsTests.java

@Before
public void createDatasource() {

    template = new JdbcTemplate(dataSource);
    marissa = userDao.retrieveUserByName("marissa");

    dao = new JdbcApprovalStore(template, new JdbcPagingListFactory(template, limitSqlAdapter),
            new SimpleSearchQueryConverter());
    endpoints = new ApprovalsAdminEndpoints();
    endpoints.setApprovalStore(dao);//from   www.j ava 2 s . c  o  m
    endpoints.setUaaUserDatabase(userDao);
    InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();
    BaseClientDetails details = new BaseClientDetails("c1", "scim,clients", "read,write",
            "authorization_code, password, implicit, client_credentials", "update");
    details.addAdditionalInformation("autoapprove", "true");
    clientDetailsService.setClientDetailsStore(Collections.singletonMap("c1", details));
    endpoints.setClientDetailsService(clientDetailsService);

    endpoints.setSecurityContextAccessor(mockSecurityContextAccessor(marissa.getUsername()));
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> handleDataAccessException(Exception ex) {
    _logger.error(ex);//from   w  ww . j  a  v a  2s .co  m
    return Collections.singletonMap("message", ex.getMessage());
}

From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

@Override
protected Map<String, String> getPayloadToPost() throws Exception {
    return Collections.singletonMap("people", readFileFromClasspath("person.json"));
}

From source file:com.logsniffer.reader.grok.GrokTest.java

@Test(expected = GrokException.class)
public void testExceptionInCaseOfCycles() throws GrokException {
    GroksRegistry r = new GroksRegistry();
    r.registerPatternBlocks(Collections.singletonMap("base",
            new String[] { "USERNAME %{USER}[a-zA-Z0-9_-]+", "USER (%{USERNAME:a}-)" }));
}