List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap
public LinkedMultiValueMap()
From source file:com.miserablemind.api.consumer.tradeking.api.impl.MarketTemplate.java
NewsHeadline[] getNewsList(String[] tickers, Integer limit, String[] keywords, LocalDate startDate, LocalDate endDate) {/*from ww w .j a va 2s . co m*/ MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); if (null != tickers) parameters.set("symbols", this.buildCommaSeparatedParameterValue(tickers)); if (null != limit) parameters.set("maxhits", String.valueOf(limit)); if (null != keywords) parameters.set("keywords", this.buildCommaSeparatedParameterValue(keywords)); //dates do not work. TK does not provide documentation for format /* if (null != startDate) { parameters.set("startdate", dateFormat.format(startDate.getTime())); if (null != endDate) { parameters.set("enddate", dateFormat.format(endDate.getTime())); } else { parameters.set("enddate", dateFormat.format(new Date())); } }*/ URI url = this.buildUri(URL_SEARCH_NEWS, parameters); ResponseEntity<TKNewsArticlesSearchResponse> response = this.getRestTemplate().getForEntity(url, TKNewsArticlesSearchResponse.class); if (null != response.getBody().getError()) throw new ApiException(TradeKingServiceProvider.PROVIDER_ID, response.getBody().getError()); return response.getBody().getArticles(); }
From source file:org.apigw.authserver.ServerRunning.java
public Statement apply(final Statement base, FrameworkMethod method, Object target) { // Check at the beginning, so this can be used as a static field if (assumeOnline) { Assume.assumeTrue(serverOnline.get(port)); } else {/*www. j a va 2s.co m*/ Assume.assumeTrue(serverOffline.get(port)); } RestTemplate client = new RestTemplate(); boolean followRedirects = HttpURLConnection.getFollowRedirects(); HttpURLConnection.setFollowRedirects(false); boolean online = false; try { client.getForEntity(getUrl("/apigw-auth-server-web/login.jsp").toString(), String.class); online = true; logger.info("Basic connectivity test passed"); } catch (RestClientException e) { logger.warn(String.format( "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName, port), e); if (assumeOnline) { Assume.assumeNoException(e); } } finally { HttpURLConnection.setFollowRedirects(followRedirects); if (online) { serverOffline.put(port, false); if (!assumeOnline) { Assume.assumeTrue(serverOffline.get(port)); } } else { serverOnline.put(port, false); } } return new Statement() { @Override public void evaluate() throws Throwable { postForStatus("/apigw-auth-server-web/login.jsp", new LinkedMultiValueMap<String, String>()); base.evaluate(); } }; }
From source file:org.jasig.portlet.notice.service.ssp.SSPApi.java
/** * Get the authentication token to use./*from w w w . j ava2s . c o m*/ * * @param forceUpdate if true, get a new auth token even if a cached instance exists. * @return The authentication token * @throws MalformedURLException if the authentication URL is invalid * @throws RestClientException if an error occurs when talking to SSP */ private synchronized SSPToken getAuthenticationToken(boolean forceUpdate) throws MalformedURLException, RestClientException { if (authenticationToken != null && !authenticationToken.hasExpired() && !forceUpdate) { return authenticationToken; } String authString = getClientId() + ":" + getClientSecret(); String authentication = new Base64().encodeToString(authString.getBytes()); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, BASIC + " " + authentication); // form encode the grant_type... MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(GRANT_TYPE, CLIENT_CREDENTIALS); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers); URL authURL = getAuthenticationURL(); authenticationToken = restTemplate.postForObject(authURL.toExternalForm(), request, SSPToken.class); return authenticationToken; }
From source file:com.weibo.api.Statuses.java
/** * http://open.weibo.com/wiki/2/statuses/mentions/shield * @deprecated TODO: need to added testcase. * @param id//from www.j ava 2 s . c o m * @param followUp * @param accessToken * @return */ public Result mentionsShield(String id, String followUp, String accessToken) { MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("id", id); map.add("follow_up", followUp); map.add("access_token", accessToken); return weiboHttpClient.postForm(STATUSES_MENTIONS_SHIELD_URL, map, Result.class); }
From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java
public Map<String, Object> sendPostForUpload(String url, String path, Log log) throws IOException { File file = new File(path); FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.available();// w w w . j a v a 2 s.c om fileInputStream.close(); FileSystemResource resource = new FileSystemResource(file); Map<String, Object> params = new HashMap<>(); params.put("file", resource); RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>(); postParams.setAll(params); Map<String, Object> response = new HashMap<String, Object>(); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "multipart/form-data"); headers.set("Accept", "application/json"); headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue()); org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>( postParams, headers); ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class); String body = result.getBody().toString(); MediaType contentType = result.getHeaders().getContentType(); HttpStatus statusCode = result.getStatusCode(); response.put("content-type", contentType); response.put("statusCode", statusCode); response.put("body", body); return response; }
From source file:org.cloudfoundry.identity.uaa.integration.PasswordChangeEndpointIntegrationTests.java
@Test @OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.Implicit.class, initialize = false) public void testUserChangesOthersPasswordFails() throws Exception { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("source", "credentials"); parameters.set("username", joe.getUserName()); parameters.set("password", "password"); context.getAccessTokenRequest().putAll(parameters); PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword("newpassword"); HttpHeaders headers = new HttpHeaders(); ResponseEntity<Void> result = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<PasswordChangeRequest>(change, headers), null, bob.getId()); assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s.c o m*/ */ @Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final long start = System.nanoTime(); try { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(TOKEN_NAME_KEY, accessToken); formData.add(CLIENT_ID_KEY, this.clientId); formData.add(CLIENT_SECRET_KEY, this.clientSecret); formData.add(GRANT_TYPE_KEY, GRANT_TYPE); final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData); if (map.containsKey(ERROR_KEY)) { final String error = map.get(ERROR_KEY).toString(); log.debug("Validating the token produced an error: {}", error); throw new InvalidTokenException(error); } Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server"); Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server"); this.convertScopes(map); final OAuth2Authentication authentication = this.converter.extractAuthentication(map); log.info("User {} authenticated with authorities {}", authentication.getPrincipal(), authentication.getAuthorities()); return authentication; } finally { final long finished = System.nanoTime(); this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS); } }
From source file:com.sybase365.mobiliser.custom.project.channels.HttpChannelEnd.java
@SuppressWarnings("unchecked") @Override//from w ww.jav a 2 s .c om public void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { LOG.debug("Incoming {} request", request.getMethod()); checkAndPrepare(request, response, false); final MultiValueMap<String, String> result = (MultiValueMap<String, String>) this.converter.read(null, new ServletServerHttpRequest(request)); final List<String> textList = result.get("text"); final List<String> fromList = result.get("from"); final List<String> toList = result.get("to"); final List<String> typeList = result.get("type"); if (textList == null || textList.isEmpty()) { throw new MissingServletRequestParameterException("text", "string"); } if (fromList == null || fromList.isEmpty()) { throw new MissingServletRequestParameterException("from", "string"); } if (toList == null || toList.isEmpty()) { throw new MissingServletRequestParameterException("to", "string"); } final String type; if (null == typeList || typeList.isEmpty()) { type = "sms"; } else { type = typeList.get(0); } final Message req = this.messagingEngine.parseSimpleTextMessage(type, textList.get(0)); req.setSender(fromList.get(0)); req.setRecipient(toList.get(0)); if (LOG.isDebugEnabled()) { LOG.debug("{} message received for {} from {}", new Object[] { type, req.getRecipient(), req.getSender() }); } final Future<Message> responseMessage = this.receiveCallback.receiveAndRespondMessage(req, this.channelId, this.incomingChannelId); if (LOG.isDebugEnabled()) { LOG.debug("Handed off message to {} for {} awaiting response", this.receiveCallback, this.incomingChannelId); } final Message message; try { message = responseMessage.get(); if (message == null) { LOG.warn("Timed out waiting for response from {}", responseMessage); throw new NestedServletException("Timed out waiting for message"); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); // reset flag throw new NestedServletException("Interrupted during processing", e); } catch (final ExecutionException e) { if (e.getCause() instanceof InterruptedException) { throw new NestedServletException( // NOSONAR "Interrupted during processing", e.getCause()); } throw new NestedServletException("Processing message failed", // NOSONAR e.getCause()); } LOG.debug("Writing response back to client"); final LinkedMultiValueMap<String, Object> responseMap = new LinkedMultiValueMap<String, Object>(); responseMap.add("from", message.getSender().getAddress()); responseMap.add("to", message.getRecipient().getAddress()); if (message instanceof SmsMessage) { responseMap.add("text", new String(((SmsMessage) message).getText().getContent(), ((SmsMessage) message).getText().getCharset())); } else if (message instanceof UssdTextMessage) { responseMap.add("text", new String(((UssdTextMessage) message).getText().getContent(), ((UssdTextMessage) message).getText().getCharset())); } this.converter.write(responseMap, this.mediaType, new ServletServerHttpResponse(response)); }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
@Test public void testImplicitGrant() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("client_id", "cf"); postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf"); postBody.add("response_type", "token id_token"); postBody.add("source", "credentials"); postBody.add("username", user.getUserName()); postBody.add("password", "secret"); ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class); Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode()); UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()) .build();/*w w w.j a v a2s .com*/ Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost()); Assert.assertEquals("/redirect/cf", locationComponents.getPath()); MultiValueMap<String, String> params = parseFragmentParams(locationComponents); Assert.assertThat(params.get("jti"), not(empty())); Assert.assertEquals("bearer", params.getFirst("token_type")); Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000)); String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" "); Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write", "cloud_controller.write", "openid", "cloud_controller.read")); validateToken("access_token", params.toSingleValueMap(), scopes); validateToken("id_token", params.toSingleValueMap(), scopes); }
From source file:com.example.DatastoreSampleApplicationTests.java
private String sendRequest(String url, String json, HttpMethod method) { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("Content-Type", "application/json"); HttpEntity<String> entity = new HttpEntity<>(json, map); ResponseEntity<String> response = this.restTemplate.exchange(url, method, entity, String.class); return response.getBody(); }