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:org.apereo.services.persondir.support.AbstractDefaultAttributePersonAttributeDao.java

/**
 * Converts the uid to a multi-valued seed Map using the value from {@link #getUsernameAttributeProvider()}
 * as the key./* w w w  .jav a2 s .co m*/
 *
 * @param uid userId
 * @return multi-valued seed Map containing the uid
 */
protected Map<String, List<Object>> toSeedMap(final String uid) {
    final List<Object> values = Collections.singletonList((Object) uid);
    final String usernameAttribute = this.usernameAttributeProvider.getUsernameAttribute();
    final Map<String, List<Object>> seed = Collections.singletonMap(usernameAttribute, values);
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Created seed map='" + seed + "' for uid='" + uid + "'");
    }
    return seed;
}

From source file:org.elasticsearch.client.documentation.StoredScriptsDocumentationIT.java

public void testGetStoredScript() throws Exception {
    RestHighLevelClient client = highLevelClient();

    final StoredScriptSource scriptSource = new StoredScriptSource("painless",
            "Math.log(_score * 2) + params.my_modifier",
            Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()));

    putStoredScript("calculate-score", scriptSource);

    {/*from   ww w .j  ava  2 s.co  m*/
        // tag::get-stored-script-request
        GetStoredScriptRequest request = new GetStoredScriptRequest("calculate-score"); // <1>
        // end::get-stored-script-request

        // tag::get-stored-script-request-masterTimeout
        request.masterNodeTimeout(TimeValue.timeValueSeconds(50)); // <1>
        request.masterNodeTimeout("50s"); // <2>
        // end::get-stored-script-request-masterTimeout

        // tag::get-stored-script-execute
        GetStoredScriptResponse getResponse = client.getScript(request, RequestOptions.DEFAULT);
        // end::get-stored-script-execute

        // tag::get-stored-script-response
        StoredScriptSource storedScriptSource = getResponse.getSource(); // <1>

        String lang = storedScriptSource.getLang(); // <2>
        String source = storedScriptSource.getSource(); // <3>
        Map<String, String> options = storedScriptSource.getOptions(); // <4>
        // end::get-stored-script-response

        assertThat(storedScriptSource, equalTo(scriptSource));

        // tag::get-stored-script-execute-listener
        ActionListener<GetStoredScriptResponse> listener = new ActionListener<GetStoredScriptResponse>() {
            @Override
            public void onResponse(GetStoredScriptResponse response) {
                // <1>
            }

            @Override
            public void onFailure(Exception e) {
                // <2>
            }
        };
        // end::get-stored-script-execute-listener

        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        listener = new LatchedActionListener<>(listener, latch);

        // tag::get-stored-script-execute-async
        client.getScriptAsync(request, RequestOptions.DEFAULT, listener); // <1>
        // end::get-stored-script-execute-async

        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }

}

From source file:org.terasoluna.gfw.common.date.jodatime.JdbcAdjustedJodaTimeDateFactoryTest.java

@Test
public void testNewDateTime04() throws Exception {

    jdbcTemplate.update("INSERT INTO system_adjusted_date(diff) VALUES (:diff)",
            Collections.singletonMap("diff", 30)); // plus 30 minute

    JdbcAdjustedJodaTimeDateFactory dateFactory = new JdbcAdjustedJodaTimeDateFactory();
    dateFactory.setDataSource(dataSource);
    dateFactory.setUseCache(true);//from   w  ww.j av  a  2s  .com
    dateFactory.setAdjustedValueQuery("SELECT diff * 60 * 1000 FROM system_adjusted_date"); // returns diff as minutes
    dateFactory.afterPropertiesSet();

    {
        DateTime now = new DateTime();
        DateTime result = dateFactory.newDateTime();

        assertThat((int) (Math.round(result.getMillis() - now.getMillis()) / 60.0 / 1000.0), is(30)); // plus 30 minute

    }
    {
        jdbcTemplate.update("UPDATE system_adjusted_date SET diff = :diff",
                Collections.singletonMap("diff", 60)); // plus 60 minute
        DateTime now = new DateTime();
        DateTime result = dateFactory.newDateTime();

        assertThat((int) (Math.round(result.getMillis() - now.getMillis()) / 60.0 / 1000.0), is(30));// still plus 30 minute
    }
    {
        DateTime now = new DateTime();
        DateTime result = dateFactory.newDateTime();

        assertThat((int) (Math.round(result.getMillis() - now.getMillis()) / 60.0 / 1000.0), is(30));// still plus 30 minute
    }
}

From source file:org.kitodo.data.elasticsearch.KitodoRestClient.java

/**
 * Get information about client server.//from   w w  w . j  av  a2 s.c o m
 *
 * @return information about the server
 */
public String getServerInformation() throws IOException {
    Response response = client.performRequest(HttpMethod.GET, "/", Collections.singletonMap("pretty", "true"));
    return EntityUtils.toString(response.getEntity());
}

From source file:org.craftercms.profile.services.impl.VerificationServiceImpl.java

@Override
@Async// ww  w .  java 2 s .c om
public void sendEmail(VerificationToken token, Profile profile, String verificationBaseUrl, String from,
        String subject, String templateName) throws ProfileException {
    String verificationUrl = createVerificationUrl(verificationBaseUrl, token.getId().toString());

    Map<String, String> templateArgs = Collections.singletonMap(VERIFICATION_LINK_TEMPLATE_ARG,
            verificationUrl);
    String[] to = new String[] { profile.getEmail() };

    try {
        emailFactory.getEmail(from, to, null, null, subject, templateName, templateArgs, true).send();

        logger.debug(LOG_KEY_EMAIL_SENT, profile.getId(), profile.getEmail());
    } catch (EmailException e) {
        throw new I10nProfileException(ERROR_KEY_EMAIL_ERROR, e, profile.getEmail());
    }
}

From source file:io.lavagna.service.SearchServiceTest.java

@Before
public void prepare() {
    userRepository.createUser("test", "test", null, null, true);
    userRepository.createUser("test", "test-no-access", null, null, true);
    user = userRepository.findUserByName("test", "test");
    userWithNoAccess = userRepository.findUserByName("test", "test-no-access");
    Role r = new Role("TEST");
    permissionService.createRole(r);/*from  ww w .  j  a  va  2 s .  co  m*/
    permissionService.updatePermissionsToRole(r, EnumSet.of(Permission.READ));
    permissionService.assignRolesToUsers(Collections.singletonMap(r, Collections.singleton(user.getId())));

    userWithPermissions = new UserWithPermission(user,
            permissionService.findBasePermissionByUserId(user.getId()),
            Collections.<String, Set<Permission>>emptyMap(), Collections.<Integer, Set<Permission>>emptyMap());

    userWithNoAccessPermission = new UserWithPermission(userWithNoAccess,
            permissionService.findBasePermissionByUserId(userWithNoAccess.getId()),
            Collections.<String, Set<Permission>>emptyMap(), Collections.<Integer, Set<Permission>>emptyMap());

    project = projectService.create("test search", "TEST-SRC", "desc");
    board = boardRepository.createNewBoard("TEST-SEARCH", "TEST-SRC", "desc", project.getId());

    List<BoardColumnDefinition> columnDefinitions = projectService
            .findColumnDefinitionsByProjectId(project.getId());
    for (BoardColumnDefinition bcd : columnDefinitions) {
        if (bcd.getValue() == ColumnDefinition.OPEN) {
            column = boardColumnRepository.addColumnToBoard("test", bcd.getId(), BoardColumnLocation.BOARD,
                    board.getId());
        } else if (bcd.getValue() == ColumnDefinition.CLOSED) {
            closedColumn = boardColumnRepository.addColumnToBoard("test", bcd.getId(),
                    BoardColumnLocation.BOARD, board.getId());
        }
    }
}

From source file:com.coinblesk.server.controller.UserController.java

@RequestMapping(value = "/login", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            loginDTO.getUsername().toLowerCase(Locale.ENGLISH), loginDTO.getPassword());

    try {// ww  w .  j  av a  2 s .c  om
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = tokenProvider.createToken(authentication);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);

        return ResponseEntity.ok(Collections.singletonMap("token", jwt));
    } catch (AuthenticationException exception) {
        return new ResponseEntity<>(
                Collections.singletonMap("AuthenticationException", exception.getLocalizedMessage()),
                HttpStatus.UNAUTHORIZED);
    }
}

From source file:io.spring.initializr.web.test.ResponseFieldSnippet.java

@Override
protected Map<String, Object> createModel(Operation operation) {
    try {//from   w ww. jav  a2s.com
        Object object = objectMapper.readValue(operation.getResponse().getContentAsString(), Object.class);
        Object field = fieldProcessor.extract(JsonFieldPath.compile(path), object);
        if (field instanceof List && index != null) {
            field = ((List<?>) field).get(index);
        }
        return Collections.singletonMap("value", objectMapper.writeValueAsString(field));
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test/*ww w  .j  a v a  2  s .c o  m*/
public void deregister() {
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));
    registrator.register();
    registrator.deregister();

    verify(restTemplate).delete("http://sba:8080/api/applications/-id-");
}