Java Examples for org.springframework.util.MultiValueMap
The following java examples will help you to understand the usage of org.springframework.util.MultiValueMap. These source code samples are taken from different open source projects.
Example 1
| Project: restler-master File: SpringMvcRequestExecutor.java View source code |
private RequestEntity<?> toRequestEntity(HttpCall call) {
MultiValueMap<String, String> headers = new HttpHeaders();
call.getHeaders().entries().stream().forEach( entry -> headers.add(entry.getKey(), entry.getValue()));
return new RequestEntity<>(call.getRequestBody(), headers, HttpMethod.valueOf(call.getHttpMethod().name()), call.getUrl());
}Example 2
| Project: cas-master File: ClickatellSmsSender.java View source code |
@Override
public boolean send(final String from, final String to, final String message) {
try {
final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", this.token);
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
final Map<String, Object> map = new HashMap<>();
map.put("content", message);
map.put("to", Arrays.asList(to));
map.put("from", from);
final StringWriter stringify = new StringWriter();
mapper.writeValue(stringify, map);
final HttpEntity<String> request = new HttpEntity<>(stringify.toString(), headers);
final ResponseEntity<Map> response = restTemplate.postForEntity(new URI(this.serverUrl), request, Map.class);
if (response.hasBody()) {
final List<Map> messages = (List<Map>) response.getBody().get("messages");
final String error = (String) response.getBody().get("error");
if (StringUtils.isNotBlank(error)) {
LOGGER.error(error);
return false;
}
final List<String> errors = messages.stream().filter( m -> m.containsKey("accepted") && !Boolean.valueOf(m.get("accepted").toString()) && m.containsKey("error")).map( m -> (String) m.get("error")).collect(Collectors.toList());
if (errors.isEmpty()) {
return true;
}
errors.forEach(LOGGER::error);
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return false;
}Example 3
| Project: spring-social-flickr-master File: TagsTemplate.java View source code |
@Override
public Photos getClusterPhotos(String tag, String clusterId) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
if (tag != null)
parameters.set("tag", tag);
if (clusterId != null)
parameters.set("cluster_id", clusterId);
return restTemplate.getForObject(buildUri("flickr.tags.getClusterPhotos", parameters), Photos.class);
}Example 4
| Project: spring-social-tumblr-master File: UserTemplate.java View source code |
public Likes likes(int offset, int limit) {
requireAuthorization();
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
params.add("offset", Integer.toString(offset));
params.add("limit", Integer.toString(limit));
return getRestTemplate().getForObject(buildUri("user/likes").toString(), Likes.class, params);
}Example 5
| Project: DistributedSystemMonitoring-master File: GlobalDefaultExceptionHandler.java View source code |
@ExceptionHandler(value = InternalErrorException.class)
public ResponseEntity<String> defaultErrorHandler(HttpServletRequest req, InternalErrorException e) throws Exception {
log.error("received error ({}) with message: {}", e.getFailureStatus(), e.getMessage());
String responseBody = objectMapper.writer().writeValueAsString(e.getErrorMessageDto());
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.put("Content-Type", Arrays.asList(MediaType.APPLICATION_JSON_VALUE));
ResponseEntity<String> response = new ResponseEntity<String>(responseBody, headers, e.getFailureStatus());
return response;
}Example 6
| Project: haogrgr-test-master File: SpringConditionImpl.java View source code |
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attr = metadata.getAllAnnotationAttributes(SpringConditionTestAnno.class.getName());
List<Object> list = attr.get("value");
Class<?> clazz = (Class<?>) list.get(0);
String beanName = Introspector.decapitalize(ClassUtils.getShortName(clazz));
if (context.getRegistry().containsBeanDefinition(beanName)) {
//context.getRegistry().removeBeanDefinition(beanName);
return false;
}
return true;
}Example 7
| Project: btpka3.github.com-master File: TestCasRESTfulApi.java View source code |
@SuppressWarnings("unchecked")
public static void test() {
String casUrlPrefix = "http://login-test.his.com/tcgroup-sso-web";
String username = "15372712873";
String password = "123456";
// GET TGT
RestTemplate rest = new RestTemplate();
rest.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(), new FormHttpMessageConverter()));
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("username", username);
params.set("password", password);
URI tgtUrl = rest.postForLocation(casUrlPrefix + "/v1/tickets", params, Collections.emptyMap());
System.out.println("[" + tgtUrl + "]");
// GET ST
String service = "http://login-test.his.com/tcgroup-his-web/client/nop.do";
params.clear();
params.set("service", service);
ResponseEntity<String> st = rest.postForEntity(tgtUrl, params, String.class);
System.out.println("[" + st.getBody() + "]");
// Using ST get data from SSO app(tcgroup-his-web).
Map<String, Object> urlParams = new HashMap<String, Object>();
urlParams.put("ticket", st.getBody());
ResponseEntity<String> html = rest.getForEntity(service + "?ticket=" + st.getBody(), String.class, urlParams);
System.out.println("[" + html.getBody() + "]");
}Example 8
| Project: capture-replay-framework-master File: CaptureReplayImportBeanDefinitionRegistrar.java View source code |
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
MultiValueMap<String, Object> attributes = importingClassMetadata.getAllAnnotationAttributes(EnableCaptureReplay.class.getName());
Mode mode = Mode.valueOf(attributes.getFirst("mode").toString());
if (!Mode.OFF.equals(mode)) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CaptureReplayAdvice.class);
builder.addPropertyValue("mode", mode);
builder.addPropertyReference("dataMapper", attributes.getFirst("dataMapper").toString());
registry.registerBeanDefinition(DEFAULT_CAPTURE_REPLAY_ADVICE_BEAN_ID, builder.getBeanDefinition());
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
}
}Example 9
| Project: compose-idm-master File: CORSController.java View source code |
@RequestMapping(value = "/**", method = RequestMethod.OPTIONS) public ResponseEntity<Object> greetingOP(@RequestHeader(required = false) MultiValueMap<String, String> head, @RequestBody(required = false) MultiValueMap<String, String> body) { LOG.info("executing OPTIONS request for CORS"); HttpHeaders headers = new HttpHeaders(); //This is located in the CORS filter //headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); headers.add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); headers.add("Access-Control-Max-Age", "3600"); headers.add("Access-Control-Allow-Headers", "x-requested-with"); return new ResponseEntity<Object>(null, headers, HttpStatus.NO_CONTENT); }
Example 10
| Project: easylocate-master File: FormOAuth2ExceptionHttpMessageConverter.java View source code |
public void write(OAuth2Exception t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
data.add(OAuth2Exception.ERROR, t.getOAuth2ErrorCode());
data.add(OAuth2Exception.DESCRIPTION, t.getMessage());
Map<String, String> additionalInformation = t.getAdditionalInformation();
if (additionalInformation != null) {
for (Map.Entry<String, String> entry : additionalInformation.entrySet()) {
data.add(entry.getKey(), entry.getValue());
}
}
delegateMessageConverter.write(data, contentType, outputMessage);
}Example 11
| Project: identity-sample-apps-master File: CompositeAccessTokenProvider.java View source code |
private MultiValueMap<String, String> getParametersForTokenRequest(ResourceOwnerPasswordResourceDetails resource, AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("grant_type", "password"); form.set("response_type", "id_token"); form.set("username", resource.getUsername()); form.set("password", resource.getPassword()); form.putAll(request); if (resource.isScoped()) { StringBuilder builder = new StringBuilder(); List<String> scope = resource.getScope(); if (scope != null) { Iterator<String> scopeIt = scope.iterator(); while (scopeIt.hasNext()) { builder.append(scopeIt.next()); if (scopeIt.hasNext()) { builder.append(' '); } } } form.set("scope", builder.toString()); } return form; }
Example 12
| Project: intermine-android-master File: FetchListResultsRequest.java View source code |
@Override public MultiValueMap<String, String> getPost() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add(FORMAT_PARAM, JSON); params.add(QUERY_PARAM, mQuery); if (mSize > 0) { params.add(START_PARAM, Integer.toString(mStart)); params.add(SIZE_PARAM, Integer.toString(mSize)); } return params; }
Example 13
| Project: jnrain-android-master File: NewPostRequest.java View source code |
@Override
public SimpleReturnCode loadDataFromNetwork() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("Content", _content);
params.set("board", _brd);
params.set("signature", Integer.toString(_signid));
params.set("subject", _title);
if (_is_new_thread) {
params.set("ID", "");
params.set("groupID", "");
params.set("reID", "0");
} else {
params.set("ID", Long.toString(_tid));
params.set("groupID", Long.toString(_tid));
params.set("reID", Long.toString(_reid));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(params, headers);
return getRestTemplate().postForObject(/* "http://rhymin.jnrain.com/api/post/new/", */
"http://bbs.jnrain.com/rainstyle/apipost.php", req, SimpleReturnCode.class);
}Example 14
| Project: linkshortener-master File: PhishTankUrlVerifier.java View source code |
@Override
public final boolean isSafe(final String url) {
boolean safe = true;
try {
final MultiValueMap<String, String> formParameters = this.config.getParameters();
formParameters.add(PARAMETER_URL, url);
final ResponseEntity<String> response = this.client.postForEntity(this.config.getApiUrl(), formParameters, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
final boolean phish = JsonPath.parse(response.getBody()).read(IN_DATABASE_PARSE_EXPRESSION);
if (phish) {
LOGGER.warn("Possible malicious link posted: {}", url);
LOGGER.debug("PhishTank response: {}", response);
safe = false;
}
} else {
LOGGER.warn("Request for PhishTank API failed with status: {} - : {}", response.getStatusCode(), response);
}
} catch (final RestClientExceptionPathNotFoundException | exception) {
LOGGER.warn("Something went wrong while processing PhishTank API: {}", exception);
}
return safe;
}Example 15
| Project: login-server-master File: TestClient.java View source code |
public String getOAuthAccessToken(String username, String password, String grantType, String scope) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", getBasicAuthHeaderValue(username, password));
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("grant_type", grantType);
postParameters.add("client_id", username);
postParameters.add("scope", scope);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ResponseEntity<Map> exchange = restTemplate.exchange(baseUrl + "/oauth/token", HttpMethod.POST, requestEntity, Map.class);
return exchange.getBody().get("access_token").toString();
}Example 16
| Project: mbit-cloud-platform-master File: StreamTemplate.java View source code |
@Override
public StreamDefinitionResource createStream(String name, String defintion, boolean deploy) {
MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
values.add("name", name);
values.add("definition", defintion);
values.add("deploy", Boolean.toString(deploy));
StreamDefinitionResource stream = restTemplate.postForObject(resources.get("streams/definitions").expand(), values, StreamDefinitionResource.class);
return stream;
}Example 17
| Project: microservices-hackathon-february-2015-master File: CollisionDetectionService.java View source code |
public BotPositionsMessage detectCollisions(BotPositionsMessage input) {
System.out.println("----------- received message");
System.out.println(input);
List<BotPosition> botPositions = new LinkedList<>();
MultiValueMap<Coordinates, String> playersOnPosition = new LinkedMultiValueMap<>();
for (BotPosition botPosition : input.getPositions()) {
BotPosition validBotPosition = validateInsideArena(botPosition);
botPositions.add(validBotPosition);
playersOnPosition.add(new Coordinates(validBotPosition.getCoordinates()), validBotPosition.getId());
}
BotPositionsMessage output = new BotPositionsMessage(botPositions);
// System.out.println("send message");
// System.out.println(output);
detectCollisions(playersOnPosition);
return output;
}Example 18
| Project: snomed-content-service-master File: OTFServiceAuthenticationTest.java View source code |
@Test
public void test() {
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "pnema");
params.add("password", "a5c527de-c77d-4b74-9186-efc3f29d65ef");
params.add("queryName", "getUserByNameAuth");
final User user = new User();
try {
JsonNode obj = rt.postForObject(OTF_SERVICE_URL, params, JsonNode.class);
JsonNode userObj = obj.get("user");
String userName = userObj.findValue("name").asText();
String status = userObj.findValue("status").asText();
Assert.notNull(status, "Status can not be empty");
user.setUsername(userName);
assertNotNull(user);
//now check if user has access to Refset app.
params = new LinkedMultiValueMap<String, String>();
params.add("username", "pnema");
params.add("queryName", "getUserApps");
JsonNode appJson = rt.postForObject(OTF_SERVICE_URL, params, JsonNode.class);
assertNotNull(appJson);
JsonNode apps = appJson.get("apps");
if (apps.isArray()) {
for (Object object : apps) {
System.out.println(object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 19
| Project: spring-boot-sample-master File: HttpClientUtils.java View source code |
/**
* post请求
* @param url
* @param formParams
* @return
*/
public static String doPost(String url, Map<String, String> formParams) {
if (MapUtils.isEmpty(formParams)) {
return doPost(url);
}
try {
MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
formParams.keySet().stream().forEach( key -> requestEntity.add(key, MapUtils.getString(formParams, key, "")));
return RestClient.getClient().postForObject(url, requestEntity, String.class);
} catch (Exception e) {
LOGGER.error("POST请求出错:{}", url, e);
}
return null;
}Example 20
| Project: spring-cloud-aws-master File: OnMissingAmazonClientCondition.java View source code |
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnMissingAmazonClient.class.getName(), true);
for (Object amazonClientClass : attributes.get("value")) {
if (isAmazonClientMissing(context, (String) amazonClientClass)) {
return true;
}
}
return false;
}Example 21
| Project: spring-cloud-config-master File: CompositePropertyPathNotificationExtractor.java View source code |
@Override
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) {
Object object = request.get("path");
if (object instanceof String) {
return new PropertyPathNotification((String) object);
}
if (object instanceof Collection) {
@SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>) object;
return new PropertyPathNotification(collection.toArray(new String[0]));
}
return null;
}Example 22
| Project: spring-cloud-netflix-master File: RetryableZuulProxyApplicationTests.java View source code |
@Test
public void postWithForm() {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("foo", "bar");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
ResponseEntity<String> result = testRestTemplate.exchange("/simple", HttpMethod.POST, new HttpEntity<>(form, headers), String.class);
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals("Posted! {foo=[bar]}", result.getBody());
}Example 23
| Project: spring-data-examples-master File: UserController.java View source code |
@RequestMapping(value = "/", method = RequestMethod.GET)
//
String index(//
Model model, //
@QuerydslPredicate(root = User.class) //
Predicate //
predicate, //
@PageableDefault(sort = { "lastname", "firstname" }) //
Pageable //
pageable, @RequestParam MultiValueMap<String, String> parameters) {
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
builder.replaceQueryParam("page", new Object[0]);
model.addAttribute("baseUri", builder.build().toUri());
model.addAttribute("users", repository.findAll(predicate, pageable));
return "index";
}Example 24
| Project: spring-framework-issues-master File: WitcherResourceTest.java View source code |
private void shouldAcceptContract(final boolean sendWithParamsInUrl) {
// given
String url = "/witcher/contract/validate";
final String contract = "The Apiarian Phantom";
final String beast = "Wild Hunt Hound";
final String reward = "120 crowns";
final MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
if (sendWithParamsInUrl) {
url += "?contract=" + contract + "&beast=" + beast + "&reward=" + reward;
} else {
parameters.add("contract", contract);
parameters.add("beast", beast);
parameters.add("reward", reward);
}
// when
final WitcherResponse witcherResponse = restOperations.postForObject(url, parameters, WitcherResponse.class);
// then
assertThat(witcherResponse.isAccepted()).isTrue();
}Example 25
| Project: spring-framework-master File: MatrixVariableMethodArgumentResolver.java View source code |
@Override
@SuppressWarnings("unchecked")
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
Map<String, MultiValueMap<String, String>> pathParameters = (Map<String, MultiValueMap<String, String>>) request.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
if (CollectionUtils.isEmpty(pathParameters)) {
return null;
}
String pathVar = parameter.getParameterAnnotation(MatrixVariable.class).pathVar();
List<String> paramValues = null;
if (!pathVar.equals(ValueConstants.DEFAULT_NONE)) {
if (pathParameters.containsKey(pathVar)) {
paramValues = pathParameters.get(pathVar).get(name);
}
} else {
boolean found = false;
paramValues = new ArrayList<>();
for (MultiValueMap<String, String> params : pathParameters.values()) {
if (params.containsKey(name)) {
if (found) {
String paramType = parameter.getNestedParameterType().getName();
throw new ServletRequestBindingException("Found more than one match for URI path parameter '" + name + "' for parameter type [" + paramType + "]. Use 'pathVar' attribute to disambiguate.");
}
paramValues.addAll(params.get(name));
found = true;
}
}
}
if (CollectionUtils.isEmpty(paramValues)) {
return null;
} else if (paramValues.size() == 1) {
return paramValues.get(0);
} else {
return paramValues;
}
}Example 26
| Project: spring-integration-master File: XPathSplitterParserTests.java View source code |
@Test
public void testXpathSplitterConfig() {
assertTrue(TestUtils.getPropertyValue(this.xpathSplitter, "createDocuments", Boolean.class));
assertFalse(TestUtils.getPropertyValue(this.xpathSplitter, "applySequence", Boolean.class));
assertFalse(TestUtils.getPropertyValue(this.xpathSplitter, "iterator", Boolean.class));
assertSame(this.outputProperties, TestUtils.getPropertyValue(this.xpathSplitter, "outputProperties"));
assertEquals("/orders/order", TestUtils.getPropertyValue(this.xpathSplitter, "xpathExpression.xpathExpression.xpath.m_patternString", String.class));
assertEquals(2, TestUtils.getPropertyValue(xpathSplitter, "order"));
assertEquals(123L, TestUtils.getPropertyValue(xpathSplitter, "messagingTemplate.sendTimeout"));
assertEquals(-1, TestUtils.getPropertyValue(consumer, "phase"));
assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class));
@SuppressWarnings("unchecked") List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles", MultiValueMap.class).get("foo");
assertThat(list, contains((SmartLifecycle) consumer));
}Example 27
| Project: spring-restdocs-master File: AtomLinkExtractor.java View source code |
@Override
public Map<String, List<Link>> extractLinks(Map<String, Object> json) {
MultiValueMap<String, Link> extractedLinks = new LinkedMultiValueMap<>();
Object possibleLinks = json.get("links");
if (possibleLinks instanceof Collection) {
Collection<Object> linksCollection = (Collection<Object>) possibleLinks;
for (Object linkObject : linksCollection) {
if (linkObject instanceof Map) {
Link link = maybeCreateLink((Map<String, Object>) linkObject);
maybeStoreLink(link, extractedLinks);
}
}
}
return extractedLinks;
}Example 28
| Project: spring-security-oauth-master File: AbstractRefreshTokenSupportTests.java View source code |
private OAuth2AccessToken refreshAccessToken(String refreshToken) {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "refresh_token");
formData.add("client_id", "my-trusted-client");
formData.add("refresh_token", refreshToken);
formData.add("scope", "read");
HttpHeaders headers = getTokenHeaders("my-trusted-client");
@SuppressWarnings("rawtypes") ResponseEntity<Map> response = http.postForMap(tokenPath(), headers, formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue("Wrong cache control: " + response.getHeaders().getFirst("Cache-Control"), response.getHeaders().getFirst("Cache-Control").contains("no-store"));
@SuppressWarnings("unchecked") OAuth2AccessToken newAccessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
return newAccessToken;
}Example 29
| Project: spring-social-evernote-master File: EvernoteOAuth1TemplateTest.java View source code |
@Test
public void testCreateOAuthToken() {
EvernoteOAuth1Template template = new EvernoteOAuth1Template("key", "secret", EvernoteService.SANDBOX);
MultiValueMap<String, String> response = new OAuth1Parameters();
response.add("oauth_token", "test_token");
response.add("oauth_token_secret", "test_secret");
response.add("edam_shard", "test_shard");
response.add("edam_userId", "test_userId");
response.add("edam_expires", "test_expires");
response.add("edam_noteStoreUrl", "test_noteStoreUrl");
response.add("edam_webApiUrlPrefix", "test_webApiUrlPrefix");
OAuthToken token = template.createOAuthToken("tokenValue", "tokenSecret", response);
assertThat(token, instanceOf(EvernoteOAuthToken.class));
EvernoteOAuthToken eToken = (EvernoteOAuthToken) token;
assertThat(eToken.getValue(), is("test_token"));
assertThat(eToken.getSecret(), is("test_secret"));
assertThat(eToken.getEdamShard(), is("test_shard"));
assertThat(eToken.getEdamUserId(), is("test_userId"));
assertThat(eToken.getEdamExpires(), is("test_expires"));
assertThat(eToken.getEdamNoteStoreUrl(), is("test_noteStoreUrl"));
assertThat(eToken.getEdamWebApiUrlPrefix(), is("test_webApiUrlPrefix"));
}Example 30
| Project: spring-social-instagram-master File: InstagramOAuth2Template.java View source code |
@Override
@SuppressWarnings("unchecked")
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
// TODO: Look into weird JSON response bug.
Map<String, Object> response = getRestTemplate().postForObject(accessTokenUrl, parameters, Map.class);
Entry<String, Object> entry = response.entrySet().iterator().next();
String jsonString = entry.getKey();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> response2 = null;
try {
response2 = mapper.readValue(jsonString, Map.class);
} catch (Exception e) {
}
String accessToken = response2.get("access_token");
return new AccessGrant(accessToken, null, null, null);
}Example 31
| Project: spring-social-strava-master File: SegmentEffortTemplate.java View source code |
public List<StravaSegmentEffort> getAllSegmentEfforts(String segmentId, String startTime, String endTime) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.set("start_date_local", startTime);
parameters.set("end_date_local", endTime);
parameters.set("per_page", "200");
return restTemplate.getForObject(buildUri("/segments/" + segmentId + "/all_efforts", parameters), StravaSegmentEffortList.class);
}Example 32
| Project: spring-social-twitter-master File: TweetData.java View source code |
/**
* Produce request parameters for a Tweet.
* @return a {@link MultiValueMap} of request parameters.
*/
public MultiValueMap<String, Object> toTweetParameters() {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
params.set("status", message);
if (inReplyToStatusId != null) {
params.set("in_reply_to_status_id", inReplyToStatusId.toString());
}
if (latitude != null && longitude != null) {
params.set("lat", latitude.toString());
params.set("long", longitude.toString());
}
if (displayCoordinates) {
params.set("display_coordinates", "true");
}
if (placeId != null) {
params.set("place_id", placeId);
}
return params;
}Example 33
| Project: spring-social-yammer-master File: UserTemplate.java View source code |
public List<YammerProfile> getUsers(int page, String sortBy, boolean reverse, Character letter) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("page", String.valueOf(page));
if (sortBy != null) {
params.set("sort_by", sortBy);
}
params.set("reverse", String.valueOf(reverse));
if (letter != null) {
params.set("letter", String.valueOf(letter));
}
return restTemplate.getForObject(buildUri("users.json", params), YammerProfileList.class);
}Example 34
| Project: spring-twitter-master File: TweetData.java View source code |
/**
* Produce request parameters for a Tweet.
* @return a {@link MultiValueMap} of request parameters.
*/
public MultiValueMap<String, Object> toTweetParameters() {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
params.set("status", message);
if (inReplyToStatusId != null) {
params.set("in_reply_to_status_id", inReplyToStatusId.toString());
}
if (latitude != null && longitude != null) {
params.set("lat", latitude.toString());
params.set("long", longitude.toString());
}
if (displayCoordinates) {
params.set("display_coordinates", "true");
}
if (placeId != null) {
params.set("place_id", placeId);
}
return params;
}Example 35
| Project: spring-xd-master File: RuntimeTemplate.java View source code |
@Override
public ModuleMetadataResource listDeployedModule(String containerId, String moduleId) {
Assert.isTrue(StringUtils.hasText(containerId));
Assert.isTrue(StringUtils.hasText(moduleId));
String url = resources.get("runtime/modules").toString();
MultiValueMap<String, String> values = new LinkedMultiValueMap<String, String>();
values.add("containerId", containerId);
values.add("moduleId", moduleId);
String uriString = UriComponentsBuilder.fromUriString(url).queryParams(values).build().toUriString();
return restTemplate.getForObject(uriString, ModuleMetadataResource.class);
}Example 36
| Project: springrest-angularjs-master File: SendGridEmailService.java View source code |
@Override
public StatusResponse send(Message message) {
try {
MultiValueMap<String, Object> vars = new LinkedMultiValueMap<String, Object>();
vars.add(SendGridParameter.API_USER, sendgridApiUser);
vars.add(SendGridParameter.API_KEY, sendgridApiKey);
vars.add(SendGridParameter.SENDER_NAME, message.getSenderName());
vars.add(SendGridParameter.SENDER_EMAIL, message.getSenderEmail());
vars.add(SendGridParameter.BLIND_COPY_EMAIL, message.getCcEmail());
vars.add(SendGridParameter.SUBJECT, message.getSubject());
vars.add(SendGridParameter.TEXT, "");
vars.add(SendGridParameter.HTML, message.getBody());
vars.add(SendGridParameter.RECEIVER_EMAIL, message.getReceiverEmail());
vars.add(SendGridParameter.RECEIVER_NAME, message.getReceiverName());
restTemplate.postForLocation(SendGridParameter.URL, vars);
} catch (Exception ex) {
logger.error(ex);
return new StatusResponse(false, "An error has occurred!");
}
return new StatusResponse(true, "Message sent");
}Example 37
| Project: tut-bookmarks-master File: ApplicationTests.java View source code |
@Test
public void passwordGrant() {
MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
request.set("username", "jlong");
request.set("password", "password");
request.set("grant_type", "password");
Map<String, Object> token = testRestTemplate.postForObject("/oauth/token", request, Map.class);
assertNotNull("Wrong response: " + token, token.get("access_token"));
}Example 38
| Project: acheron-master File: IntrospectionOperation.java View source code |
@Override
public IntrospectionResult result() throws TechnicalException {
final IntrospectionResult result;
final RestTemplate restTemplate = buildRestTemplate();
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Bearer " + ownAccessToken);
final MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("token", introspectedAccessToken);
final HttpEntity<MultiValueMap<String, String>> introspectionRequestHttpEntity = new HttpEntity<>(map, headers);
try {
final JSONResponse jsonResponse = restTemplate.postForObject(introspectionEndpointURL, introspectionRequestHttpEntity, JSONResponse.class);
// NPE is possible, caught below
result = new IntrospectionResult(jsonResponse);
} catch (Exception e) {
log.error("Could not introspect access token via authorisation server", e);
throw new TechnicalException();
}
return result;
}Example 39
| Project: akanke-master File: FacebookStatsServiceImpl.java View source code |
@Override
@Cacheable("facebook-stats")
public FacebookStats get(String documentId) {
LOGGER.debug("Getting facebook stats for document id={}", documentId);
checkArgument(documentId != null, "Document id cannot be null");
try {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("fields", Collections.singletonList("share"));
params.put("id", Collections.singletonList(baseUrl + documentId));
JsonNode ogObjectNode = facebookTemplate.fetchObject("/", JsonNode.class, params);
JsonNode shareNode = ogObjectNode.get("share");
if (shareNode == null) {
return new FacebookStats();
} else {
int commentCount = (shareNode.has(COMMENT_COUNT)) ? shareNode.get(COMMENT_COUNT).asInt() : 0;
int shareCount = (shareNode.has(SHARE_COUNT)) ? shareNode.get(SHARE_COUNT).asInt() : 0;
return new FacebookStats(commentCount, shareCount);
}
} catch (SocialExceptionResourceAccessException | e) {
LOGGER.warn("Ignoring exception while fetching stats for document id={} from Facebook", documentId, e);
return new FacebookStats();
}
}Example 40
| Project: blog-social-login-with-spring-social-master File: MainController.java View source code |
@RequestMapping(value = "/updateStatus", method = POST)
public String updateStatus(WebRequest webRequest, HttpServletRequest request, Principal currentUser, Model model, @RequestParam(value = "status", required = true) String status) {
MultiValueMap<String, Connection<?>> cmap = connectionRepository.findAllConnections();
LOG.error("cs.size = {}", cmap.size());
Set<Map.Entry<String, List<Connection<?>>>> entries = cmap.entrySet();
for (Map.Entry<String, List<Connection<?>>> entry : entries) {
for (Connection<?> c : entry.getValue()) {
LOG.debug("Updates {} with the status '{}'", entry.getKey(), status);
c.updateStatus(status);
}
}
return "home";
}Example 41
| Project: cf-java-client-master File: FilterBuilderTest.java View source code |
@Test
public void test() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
FilterBuilder.augment(builder, new StubFilterParamsSubClass());
MultiValueMap<String, String> queryParams = builder.build().encode().getQueryParams();
List<String> q = queryParams.get("q");
assertThat(q).hasSize(8).containsOnly("test-greater-than%3Etest-value-1", "test-greater-than-or-equal-to%3E%3Dtest-value-2", "test-in%20IN%20test-value-3,test-value-4", "test-is:test-value-5", "test-less-than%3Ctest-value-6", "test-less-than-or-equal-to%3C%3Dtest-value-7", "test-default%20IN%20test-value-8,test-value-9", "test-override:test-value-10");
}Example 42
| Project: cloud-rest-service-master File: UserServiceTest.java View source code |
public static void requestRestApi(String access_token) {
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("method", "user.get");
form.add("version", "1.0.0");
form.add("locale", "zh_CN");
form.add("format", "json");
//-Dexcludes.appkey=Hb0YhmOo
form.add("appkey", "Hb0YhmOo");
form.add("access_token", access_token);
form.add("id", "10001");
String result = restTemplate.postForObject("http://localhost:8090/api", form, String.class);
System.out.println(result);
}Example 43
| Project: convergent-ui-master File: ContentFetchCommand.java View source code |
@Override
protected ContentResponse run() throws Exception {
log.debug("Getting live content from [ " + location + " ]");
try {
HttpServletRequest request = requestContext.getRequest();
MultiValueMap<String, String> headers = this.helper.buildZuulRequestHeaders(request);
if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
MultiValueMap<String, String> params = this.helper.buildZuulRequestQueryParams(request);
}
HttpHeaders requestHeaders = new HttpHeaders();
for (String key : headers.keySet()) {
for (String s : headers.get(key)) {
requestHeaders.add(key, s);
}
}
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity<Object> exchange = this.restTemplate.exchange(location, HttpMethod.GET, requestEntity, Object.class);
ContentResponse response = new ContentResponse();
response.setContent(exchange.getBody());
response.setContentType(exchange.getHeaders().getContentType());
response.setError(false);
return response;
} catch (Exception e) {
log.debug("Error fetching live content from [ " + location + " ]", e);
throw e;
}
}Example 44
| Project: enhanced-pet-clinic-master File: MessageControllerWebTests.java View source code |
@Test
public void testCreate() throws Exception {
ResponseEntity<String> page = executeLogin("user", "user");
page = getPage("http://localhost:" + this.port + "/messages?form");
String body = page.getBody();
assertNotNull("Body was null", body);
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("summary", "summary");
form.set("messageText", "messageText");
form.set("_csrf", csrfValue);
String formAction = getFormAction(page);
page = postPage(formAction, form);
body = page.getBody();
assertTrue("Error creating message.", body == null || body.contains("alert alert-danger"));
assertTrue("Status was not FOUND (redirect), means message was not created properly.", page.getStatusCode() == HttpStatus.FOUND);
page = getPage(page.getHeaders().getLocation());
body = page.getBody();
assertTrue("Error creating message.", body.contains("Successfully created a new message"));
}Example 45
| Project: FFC-Android-App-master File: FormBasedAuthentication.java View source code |
/**
* Authentication via username and password.
* @return True if the authentication succeeded, otherwise false is returned.
*/
public boolean authenticate() {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("authentication[username]", username);
formData.add("authentication[password]", password);
formData.add("authentication[remember_me]", "1");
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.postForLocation(getUrl(), formData);
if (CookiePreserveHttpRequestInterceptor.getInstance().hasCookieWithName("user_credentials")) {
return true;
// Try with another method
} else {
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(baseUri, HttpMethod.GET, requestEntity, String.class);
return !responseEntity.getBody().toString().contains("authentication[username]");
}
}Example 46
| Project: hdiv-master File: OnFrameworkCondition.java View source code |
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnFramework.class.getName(), true);
List<Object> values = attributes.get("value");
Assert.notEmpty(values);
SupportedFramework frwk = (SupportedFramework) values.get(0);
if (frwk == SupportedFramework.SPRING_MVC) {
return springMvcModulePresent;
} else if (frwk == SupportedFramework.THYMELEAF) {
return thymeleafModulePresent;
} else if (frwk == SupportedFramework.GRAILS) {
return grailsPresent && grailsModulePresent;
} else if (frwk == SupportedFramework.JSF) {
return jsfPresent && jsfModulePresent;
} else if (frwk == SupportedFramework.STRUTS1) {
return struts1ModulePresent;
} else {
return false;
}
}Example 47
| Project: keemto-master File: LoginWebIT.java View source code |
@Test
public void shouldRejectInvalidUsername() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add(USERNAME_PARAM, "invalid-login");
params.add(PASSWORD_PARAM, "fake");
LoginStatus status = template.postForObject(URL, params, LoginStatus.class);
assertThat(status.isLoggedIn(), is(false));
assertThat(status.getUsername(), equalTo("invalid-login"));
}Example 48
| Project: levelup-java-examples-master File: TransformMapToQueryString.java View source code |
@Test
public void convert_map_to_uri_spring() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
for (Entry<String, String> entry : mapToConvert.entrySet()) {
params.add(entry.getKey(), entry.getValue());
}
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.leveluplunch.com").queryParams(params).build();
assertEquals("http://www.leveluplunch.com?end-date=2014-11-26&itemsPerPage=25", uriComponents.toUriString());
}Example 49
| Project: milonga-master File: JsUserFileListener.java View source code |
@SuppressWarnings("unchecked")
private void reRegisterHandlerMethods() {
AtmosRequestMappingHandlerMapping handlerMapping = getApplicationContext().getBean(AtmosRequestMappingHandlerMapping.class);
try {
Field fieldHandlerMethods = AbstractHandlerMethodMapping.class.getDeclaredField("handlerMethods");
fieldHandlerMethods.setAccessible(true);
Map<RequestMappingInfo, HandlerMethod> map = (Map<RequestMappingInfo, HandlerMethod>) fieldHandlerMethods.get(handlerMapping);
map.clear();
Field fieldUrlMap = AbstractHandlerMethodMapping.class.getDeclaredField("urlMap");
fieldUrlMap.setAccessible(true);
MultiValueMap<String, RequestMappingInfo> urlMap = (MultiValueMap<String, RequestMappingInfo>) fieldUrlMap.get(handlerMapping);
urlMap.clear();
handlerMapping.getHandlerMappingInfoStorage().getHandlerMappingInfos().clear();
handlerMapping.getHandlerMappingInfoStorage().getHandlerWithViewMappingInfos().clear();
handlerMapping.reInitHandlerMethods();
} catch (Exception e) {
logger.error("[Milonga] Refreshing Javascript is failed.", e);
}
}Example 50
| Project: profile-master File: AuthenticationServiceRestClient.java View source code |
@Override
public Ticket authenticate(String tenantName, String username, String password) throws ProfileException {
MultiValueMap<String, String> params = createBaseParams();
RestClientUtils.addValue(PARAM_TENANT_NAME, tenantName, params);
RestClientUtils.addValue(PARAM_USERNAME, username, params);
RestClientUtils.addValue(PARAM_PASSWORD, password, params);
String url = getAbsoluteUrl(BASE_URL_AUTHENTICATION + URL_AUTH_AUTHENTICATE);
return doPostForObject(url, params, Ticket.class);
}Example 51
| Project: reactor-master File: FilterBuilderTest.java View source code |
@Test
public void test() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
FilterBuilder.augment(builder, new StubFilterParamsSubClass());
MultiValueMap<String, String> queryParams = builder.build().encode().getQueryParams();
List<String> q = queryParams.get("q");
assertThat(q).hasSize(8).containsOnly("test-greater-than%3Etest-value-1", "test-greater-than-or-equal-to%3E%3Dtest-value-2", "test-in%20IN%20test-value-3,test-value-4", "test-is:test-value-5", "test-less-than%3Ctest-value-6", "test-less-than-or-equal-to%3C%3Dtest-value-7", "test-default%20IN%20test-value-8,test-value-9", "test-override:test-value-10");
}Example 52
| Project: report-cockpit-birt-web-master File: ParameterFormBinder.java View source code |
private MutablePropertyValues createPropertyValues(ParameterForm parameterForm, final MultiValueMap<String, String> requestParameters) {
final MutablePropertyValues mpvs = new MutablePropertyValues();
parameterForm.accept(new AbstractParameterVisitor() {
@Override
public <V, T> void visit(ScalarParameter<V, T> parameter) {
String name = parameter.getName();
String propertyPath = ParameterUtils.nameToTextPath(name);
Class<T> textType = parameter.getTextType();
if (requestParameters.containsKey(name)) {
addText(name, propertyPath, textType);
} else if (requestParameters.containsKey('_' + name)) {
addText('_' + name, propertyPath, textType);
}
}
private <T> void addText(String name, String propertyPath, Class<T> textType) {
List<String> values = requestParameters.get(name);
if (textType.isArray()) {
mpvs.add(propertyPath, values.toArray());
} else {
for (String requestValue : values) {
mpvs.add(propertyPath, requestValue);
}
}
}
});
return mpvs;
}Example 53
| Project: riptide-master File: RequestArguments.java View source code |
default RequestArguments withRequestUri() {
@Nullable final URI uri = getUri();
@Nullable final URI unresolvedUri;
if (uri == null) {
final String uriTemplate = getUriTemplate();
if (uriTemplate == null || uriTemplate.isEmpty()) {
unresolvedUri = null;
} else {
// expand uri template
unresolvedUri = fromUriString(uriTemplate).buildAndExpand(getUriVariables().toArray()).encode().toUri();
}
} else {
unresolvedUri = uri;
}
@Nullable final URI baseUrl = getBaseUrl();
@Nonnull final URI resolvedUri;
if (unresolvedUri == null) {
checkArgument(baseUrl != null, "Either Base URL or absolute Request URI is required");
resolvedUri = baseUrl;
} else if (baseUrl == null || unresolvedUri.isAbsolute()) {
resolvedUri = unresolvedUri;
} else {
resolvedUri = getUrlResolution().resolve(baseUrl, unresolvedUri);
}
// encode query params
final MultiValueMap<String, String> queryParams;
{
final UriComponentsBuilder components = UriComponentsBuilder.newInstance();
getQueryParams().entries().forEach( entry -> components.queryParam(entry.getKey(), entry.getValue()));
queryParams = components.build().encode().getQueryParams();
}
// build request uri
final URI requestUri = fromUri(resolvedUri).queryParams(queryParams).build(true).normalize().toUri();
checkArgument(requestUri.isAbsolute(), "Request URI is not absolute");
return withRequestUri(requestUri);
}Example 54
| Project: spring-boot-master File: CachePublicMetrics.java View source code |
private MultiValueMap<String, CacheManagerBean> getCacheManagerBeans() { MultiValueMap<String, CacheManagerBean> cacheManagerNamesByCacheName = new LinkedMultiValueMap<>(); for (Map.Entry<String, CacheManager> entry : this.cacheManagers.entrySet()) { for (String cacheName : entry.getValue().getCacheNames()) { cacheManagerNamesByCacheName.add(cacheName, new CacheManagerBean(entry.getKey(), entry.getValue())); } } return cacheManagerNamesByCacheName; }
Example 55
| Project: spring-boot-starter-batch-web-master File: BatchMetricsExporterIntegrationTest.java View source code |
@Test
public void testRunJob() throws InterruptedException {
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
requestMap.add("jobParameters", "run=2");
Long executionId = restTemplate.postForObject("http://localhost:" + port + "/batch/operations/jobs/simpleBatchMetricsJob", requestMap, Long.class);
while (!restTemplate.getForObject("http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}", String.class, executionId).equals("COMPLETED")) {
Thread.sleep(1000);
}
String log = restTemplate.getForObject("http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}/log", String.class, executionId);
assertThat(log.length() > 20, is(true));
JobExecution jobExecution = jobExplorer.getJobExecution(executionId);
assertThat(jobExecution.getStatus(), is(BatchStatus.COMPLETED));
String jobExecutionString = restTemplate.getForObject("http://localhost:" + port + "/batch/monitoring/jobs/executions/{executionId}", String.class, executionId);
assertThat(jobExecutionString.contains("COMPLETED"), is(true));
Metric<?> metric = metricReader.findOne("gauge.batch.simpleBatchMetricsJob.simpleBatchMetricsStep.processor");
assertThat(metric, is(notNullValue()));
assertThat((Double) metric.getValue(), is(notNullValue()));
assertThat((Double) metric.getValue(), is(7.0));
}Example 56
| Project: spring-data-commons-master File: HateoasPageableHandlerMethodArgumentResolverUnitTests.java View source code |
// DATACMNS-343
@Test
public void replacesExistingPaginationInformation() throws Exception {
MethodParameter parameter = new MethodParameter(Sample.class.getMethod("supportedMethod", Pageable.class), 0);
UriComponentsContributor resolver = new HateoasPageableHandlerMethodArgumentResolver();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080?page=0&size=10");
resolver.enhance(builder, parameter, PageRequest.of(1, 20));
MultiValueMap<String, String> params = builder.build().getQueryParams();
List<String> page = params.get("page");
assertThat(page).hasSize(1);
assertThat(page.get(0)).isEqualTo("1");
List<String> size = params.get("size");
assertThat(size).hasSize(1);
assertThat(size.get(0)).isEqualTo("20");
}Example 57
| Project: spring-hadoop-samples-old-master File: JobsCommand.java View source code |
/**
* launch job
*
* @param jobName
*/
@CliCommand(value = "job launch", help = "execute job")
public void executeJob(@CliOption(key = { "jobName" }, mandatory = true, help = "Job Name") final String jobName, @CliOption(key = { "jobParameters" }, mandatory = false, help = "Job Parameters") final String jobParameters) {
String url = "jobs/";
url += jobName;
url += ".json";
setCommandURL(url);
MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
if (jobParameters == null) {
mvm.add("jobParameters", "fail=false, id=" + count++);
} else {
mvm.add("jobParameters", jobParameters);
}
callPostService(mvm);
}Example 58
| Project: spring-integration-samples-master File: MultipartRestClient.java View source code |
/**
* @param args
*/
public static void main(String[] args) throws Exception {
RestTemplate template = new RestTemplate();
Resource s2logo = new ClassPathResource(resourcePath);
MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();
multipartMap.add("company", "SpringSource");
multipartMap.add("company-logo", s2logo);
logger.info("Created multipart request: " + multipartMap);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("multipart", "form-data"));
HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);
logger.info("Posting request to: " + uri);
ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, Object.class);
if (!httpResponse.getStatusCode().equals(HttpStatus.OK)) {
logger.error("Problems with the request. Http status: " + httpResponse.getStatusCode());
}
}Example 59
| Project: spring-reactive-master File: HttpRequestPathHelper.java View source code |
/**
* Decode the given matrix variables unless {@link #setUrlDecode(boolean)}
* is set to {@code true} in which case it is assumed the URL path from
* which the variables were extracted is already decoded through a call to
* {@link #getLookupPathForRequest(ServerWebExchange)}.
* @param exchange current exchange
* @param vars URI variables extracted from the URL path
* @return the same Map or a new Map instance
*/
public MultiValueMap<String, String> decodeMatrixVariables(ServerWebExchange exchange, MultiValueMap<String, String> vars) {
if (this.urlDecode) {
return vars;
}
MultiValueMap<String, String> decodedVars = new LinkedMultiValueMap<>(vars.size());
for (String key : vars.keySet()) {
for (String value : vars.get(key)) {
decodedVars.add(key, decode(exchange, value));
}
}
return decodedVars;
}Example 60
| Project: spring-security-master File: MethodSecurityMetadataSourceAdvisorRegistrar.java View source code |
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableGlobalMethodSecurity#proxyTargetClass()} attribute on the
* importing {@code @Configuration} class.
*/
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder advisor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
advisor.addConstructorArgValue("methodSecurityInterceptor");
advisor.addConstructorArgReference("methodSecurityMetadataSource");
advisor.addConstructorArgValue("methodSecurityMetadataSource");
MultiValueMap<String, Object> attributes = importingClassMetadata.getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
Integer order = (Integer) attributes.getFirst("order");
if (order != null) {
advisor.addPropertyValue("order", order);
}
registry.registerBeanDefinition("metaDataSourceAdvisor", advisor.getBeanDefinition());
}Example 61
| Project: spring-social-facebook-master File: SignedRequestArgumentResolver.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {
SignedRequest annotation = parameter.getParameterAnnotation(SignedRequest.class);
if (annotation == null) {
return WebArgumentResolver.UNRESOLVED;
}
String signedRequest = request.getParameter("signed_request");
if (signedRequest == null && annotation.required()) {
throw new IllegalStateException("Required signed_request parameter is missing.");
}
if (signedRequest == null) {
return null;
}
Class<?> parameterType = parameter.getParameterType();
if (MultiValueMap.class.isAssignableFrom(parameterType)) {
Map map = signedRequestDecoder.decodeSignedRequest(signedRequest, Map.class);
LinkedMultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>(map.size());
mvm.setAll((Map<String, Object>) map);
return mvm;
}
return signedRequestDecoder.decodeSignedRequest(signedRequest, parameterType);
}Example 62
| Project: spring-social-google-master File: GoogleOAuth2Template.java View source code |
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
ResponseEntity<Map> responseEntity = getRestTemplate().exchange(accessTokenUrl, HttpMethod.POST, requestEntity, Map.class);
Map<String, Object> responseMap = responseEntity.getBody();
return extractAccessGrant(responseMap);
}Example 63
| Project: spring-social-intuit-master File: AccountTemplate.java View source code |
public List<Account> getAccounts() {
requireAuthorization();
List<Account> accounts = new ArrayList<Account>();
boolean hasMore = true;
Integer pageNum = 1;
while (hasMore) {
MultiValueMap<String, String> criteria = new LinkedMultiValueMap<String, String>();
criteria.add("ResultsPerPage", pageSize.toString());
criteria.add("PageNum", pageNum.toString());
SearchResults response = restTemplate.postForObject("{baseURL}/resource/accounts/v2/{companyId}", criteria, SearchResults.class, baseUrl, companyId);
if (response == null)
break;
List<Account> returnedAccounts = ((Accounts) response.getCdmCollections()).getAccounts();
if (pageSize != returnedAccounts.size())
hasMore = false;
accounts.addAll(returnedAccounts);
pageNum = response.getCurrentPage() + 1;
}
return accounts;
}Example 64
| Project: spring-social-wunderlist-master File: WunderlistOAuth2Template.java View source code |
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUri, MultiValueMap<String, String> additionalParameters) {
AccessTokenRequest request = new AccessTokenRequest(clientId, clientSecret, authorizationCode);
Map<String, String> response = getRestTemplate().postForObject(ACCESS_TOKEN_URL, request, Map.class);
String accessToken = response.get("access_token");
return new AccessGrant(accessToken, null, null, null);
}Example 65
| Project: Stage-master File: ConfigurationOptionsMarkdownExporter.java View source code |
public static void main(String[] args) throws IOException {
StringBuilder markdown = new StringBuilder();
final Map<String, List<ConfigurationOption<?>>> configurationOptionsByPlugin = new ConfigurationRegistry(StagemonitorPlugin.class).getConfigurationOptionsByCategory();
MultiValueMap<String, ConfigurationOption<?>> configurationOptionsByTags = new LinkedMultiValueMap<>();
configurationOptionsByPlugin.values().stream().flatMap(Collection::stream).filter( opt -> !opt.getTags().isEmpty()).forEach( opt -> opt.getTags().forEach( tag -> configurationOptionsByTags.add(tag, opt)));
markdown.append("# Overview\n");
markdown.append("## All Plugins\n");
for (String plugin : configurationOptionsByPlugin.keySet()) {
markdown.append("* ").append(linkToHeadline(plugin)).append('\n');
}
markdown.append("\n");
markdown.append("## Available Tags\n");
for (String tag : configurationOptionsByTags.keySet()) {
markdown.append("`").append(tag).append("` ");
}
markdown.append("\n");
markdown.append("# Options by Plugin\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) {
final String pluginName = entry.getKey();
markdown.append("* ").append(linkToHeadline(pluginName)).append('\n');
for (ConfigurationOption<?> option : entry.getValue()) {
markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n');
}
}
markdown.append("\n");
markdown.append("# Options by Tag\n");
markdown.append("\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByTags.entrySet()) {
markdown.append("* `").append(entry.getKey()).append("` \n");
for (ConfigurationOption<?> option : entry.getValue()) {
markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n');
}
}
markdown.append("\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) {
markdown.append("# ").append(entry.getKey()).append("\n\n");
for (ConfigurationOption<?> configurationOption : entry.getValue()) {
markdown.append("## ").append(configurationOption.getLabel()).append("\n\n");
markdown.append(configurationOption.getDescription()).append("\n\n");
markdown.append("Key: `").append(configurationOption.getKey()).append("`\n\n");
markdown.append("Default Value: ");
markdown.append('`').append(configurationOption.getDefaultValueAsString()).append("`\n\n");
if (!configurationOption.getTags().isEmpty()) {
markdown.append("Tags: ");
for (String tag : configurationOption.getTags()) {
markdown.append('`').append(tag).append("` ");
}
markdown.append("\n\n");
}
}
markdown.append("***\n\n");
}
System.out.println(markdown);
}Example 66
| Project: stagemonitor-master File: ConfigurationOptionsMarkdownExporter.java View source code |
public static void main(String[] args) throws IOException {
StringBuilder markdown = new StringBuilder();
final Map<String, List<ConfigurationOption<?>>> configurationOptionsByPlugin = new ConfigurationRegistry(StagemonitorPlugin.class).getConfigurationOptionsByCategory();
MultiValueMap<String, ConfigurationOption<?>> configurationOptionsByTags = new LinkedMultiValueMap<>();
configurationOptionsByPlugin.values().stream().flatMap(Collection::stream).filter( opt -> !opt.getTags().isEmpty()).forEach( opt -> opt.getTags().forEach( tag -> configurationOptionsByTags.add(tag, opt)));
markdown.append("# Overview\n");
markdown.append("## All Plugins\n");
for (String plugin : configurationOptionsByPlugin.keySet()) {
markdown.append("* ").append(linkToHeadline(plugin)).append('\n');
}
markdown.append("\n");
markdown.append("## Available Tags\n");
for (String tag : configurationOptionsByTags.keySet()) {
markdown.append("`").append(tag).append("` ");
}
markdown.append("\n");
markdown.append("# Options by Plugin\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) {
final String pluginName = entry.getKey();
markdown.append("* ").append(linkToHeadline(pluginName)).append('\n');
for (ConfigurationOption<?> option : entry.getValue()) {
markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n');
}
}
markdown.append("\n");
markdown.append("# Options by Tag\n");
markdown.append("\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByTags.entrySet()) {
markdown.append("* `").append(entry.getKey()).append("` \n");
for (ConfigurationOption<?> option : entry.getValue()) {
markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n');
}
}
markdown.append("\n");
for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) {
markdown.append("# ").append(entry.getKey()).append("\n\n");
for (ConfigurationOption<?> configurationOption : entry.getValue()) {
markdown.append("## ").append(configurationOption.getLabel()).append("\n\n");
markdown.append(configurationOption.getDescription()).append("\n\n");
markdown.append("Key: `").append(configurationOption.getKey()).append("`\n\n");
markdown.append("Default Value: ");
markdown.append('`').append(configurationOption.getDefaultValueAsString()).append("`\n\n");
if (!configurationOption.getTags().isEmpty()) {
markdown.append("Tags: ");
for (String tag : configurationOption.getTags()) {
markdown.append('`').append(tag).append("` ");
}
markdown.append("\n\n");
}
}
markdown.append("***\n\n");
}
System.out.println(markdown);
}Example 67
| Project: tut-spring-security-and-angular-js-master File: ApplicationTests.java View source code |
@Test
public void loginSucceeds() {
ResponseEntity<String> response = template.getForEntity("http://localhost:" + port + "/uaa/login", String.class);
String csrf = getCsrf(response.getBody());
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("username", "user");
form.set("password", "password");
form.set("_csrf", csrf);
HttpHeaders headers = new HttpHeaders();
headers.put("COOKIE", response.getHeaders().get("Set-Cookie"));
RequestEntity<MultiValueMap<String, String>> request = new RequestEntity<MultiValueMap<String, String>>(form, headers, HttpMethod.POST, URI.create("http://localhost:" + port + "/uaa/login"));
ResponseEntity<Void> location = template.exchange(request, Void.class);
assertEquals("http://localhost:" + port + "/uaa/", location.getHeaders().getFirst("Location"));
}Example 68
| Project: uaa-master File: AutologinRequestConverter.java View source code |
@Override
protected AutologinRequest readInternal(Class<? extends AutologinRequest> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
String username, password;
if (isJsonContent(inputMessage.getHeaders().get(HttpHeaders.CONTENT_TYPE))) {
Map<String, String> map = JsonUtils.readValue(stringConverter.read(String.class, inputMessage), new TypeReference<Map<String, String>>() {
});
username = map.get("username");
password = map.get("password");
} else {
MultiValueMap<String, String> map = formConverter.read(null, inputMessage);
username = map.getFirst("username");
password = map.getFirst("password");
}
AutologinRequest result = new AutologinRequest();
result.setUsername(username);
result.setPassword(password);
return result;
}Example 69
| Project: geode-master File: ClientHttpRequest.java View source code |
/**
* Gets the HTTP request entity encapsulating the headers and body of the HTTP message. The body
* of the HTTP request message will consist of an URL encoded application form (a mapping of
* key-value pairs) for POST/PUT HTTP requests.
* <p/>
*
* @return an HttpEntity with the headers and body for the HTTP request message.
* @see #getParameters()
* @see org.springframework.http.HttpEntity
* @see org.springframework.http.HttpHeaders
*/
public HttpEntity<?> createRequestEntity() {
if (isPost() || isPut()) {
// NOTE HTTP request parameters take precedence over HTTP message body content/media
if (!getParameters().isEmpty()) {
getHeaders().setContentType(determineContentType(MediaType.APPLICATION_FORM_URLENCODED));
return new HttpEntity<MultiValueMap<String, Object>>(getParameters(), getHeaders());
} else {
// based on the Class type of the "content".
return new HttpEntity<Object>(getContent(), getHeaders());
}
} else {
return new HttpEntity<Object>(getHeaders());
}
}Example 70
| Project: Activiti-master File: ModelSaveRestResource.java View source code |
@RequestMapping(value = "/model/{modelId}/save", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)
public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
try {
Model model = repositoryService.getModel(modelId);
ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
modelJson.put(MODEL_NAME, values.getFirst("name"));
modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
model.setMetaInfo(modelJson.toString());
model.setName(values.getFirst("name"));
repositoryService.saveModel(model);
repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes("utf-8"));
InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
TranscoderInput input = new TranscoderInput(svgStream);
PNGTranscoder transcoder = new PNGTranscoder();
// Setup output
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(outStream);
// Do the transformation
transcoder.transcode(input, output);
final byte[] result = outStream.toByteArray();
repositoryService.addModelEditorSourceExtra(model.getId(), result);
outStream.close();
} catch (Exception e) {
LOGGER.error("Error saving model", e);
throw new ActivitiException("Error saving model", e);
}
}Example 71
| Project: AIDR-master File: SpringSocialUserDetailService.java View source code |
private List<Connection<?>> getConnections(ConnectionRepository connectionRepository) {
MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
List<Connection<?>> allConnections = new ArrayList<Connection<?>>();
if (connections.size() > 0) {
for (List<Connection<?>> connectionList : connections.values()) {
for (Connection<?> connection : connectionList) {
allConnections.add(connection);
}
}
}
return allConnections;
}Example 72
| Project: alien4cloud-master File: AlienUserConnectionRepository.java View source code |
@Override
public ConnectionRepository createConnectionRepository(String userId) {
if (userId == null) {
throw new IllegalArgumentException("userId cannot be null");
}
return new ConnectionRepository() {
@Override
public void updateConnection(Connection<?> connection) {
log.info("Update a connection", connection);
}
@Override
public void removeConnections(String providerId) {
log.info("Remove all provider connection's", providerId);
}
@Override
public void removeConnection(ConnectionKey connectionKey) {
log.info("Remove connection by key ", connectionKey);
}
@Override
public <A> Connection<A> getPrimaryConnection(Class<A> apiType) {
log.info("Request primary connection by api ", apiType);
return null;
}
@Override
public <A> Connection<A> getConnection(Class<A> apiType, String providerUserId) {
log.info("Request connection by api and user ", apiType, providerUserId);
return null;
}
@Override
public Connection<?> getConnection(ConnectionKey connectionKey) {
log.info("Request connection by key ", connectionKey);
return null;
}
@Override
public <A> Connection<A> findPrimaryConnection(Class<A> apiType) {
log.info("Request all connections for api", apiType);
return null;
}
@Override
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUserIds) {
log.info("Request all connections for users", providerUserIds);
return null;
}
@Override
public <A> List<Connection<A>> findConnections(Class<A> apiType) {
log.info("Request all connections api", apiType);
return null;
}
@Override
public List<Connection<?>> findConnections(String providerId) {
log.info("Request all connections for provider", providerId);
return null;
}
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
log.info("Request all connections");
return null;
}
@Override
public void addConnection(Connection<?> connection) {
log.info("Add connection ", connection);
}
};
}Example 73
| Project: comsat-master File: SampleWebUiApplicationTests.java View source code |
@Test
public void testCreate() throws Exception {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("text", "FOO text");
map.set("summary", "FOO");
URI location = new TestRestTemplate().postForLocation("http://localhost:" + this.port, map);
assertTrue("Wrong location:\n" + location, location.toString().contains("localhost:" + this.port));
}Example 74
| Project: egovframe.rte.3.5-master File: MatrixVariableTest.java View source code |
@Before
public void setUp() throws Exception {
this.resolver = new MatrixVariableMethodArgumentResolver();
Method method = getClass().getMethod("handle", String.class, List.class, int.class);
this.paramString = new MethodParameter(method, 0);
this.paramColors = new MethodParameter(method, 1);
this.paramYear = new MethodParameter(method, 2);
this.paramColors.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
this.mavContainer = new ModelAndViewContainer();
this.request = new MockHttpServletRequest();
this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>();
this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params);
}Example 75
| Project: funiture-master File: FileController.java View source code |
/**
* 文件上ä¼
* è¦?求:å‰?ç«¯ä¸Šä¼ æ–‡ä»¶çš„input框name属性必须为file,如果多个使用多个name="file"一起æ??交
*
* @param request
* @return 实际图片的地�
*/
@RequestMapping("/upload.json")
public JsonData upload(HttpServletRequest request) {
String operator = LoginUtil.getUserNameCookie();
try {
List<FileUploadBo> uploadFileList = Lists.newArrayList();
//创建一个通用的多部分解�器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//åˆ¤æ– request 是å?¦æœ‰æ–‡ä»¶ä¸Šä¼ ,å?³å¤šéƒ¨åˆ†è¯·æ±‚
if (multipartResolver.isMultipart(request)) {
//转��多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
MultiValueMap<String, MultipartFile> multiValueMap = multiRequest.getMultiFileMap();
List<MultipartFile> fileList = multiValueMap.get("file");
uploadFileList = fileInfoService.handleUploadFiles(fileList, operator);
}
log.info("æ–‡ä»¶ä¸Šä¼ ç»“æžœ:{}", JsonMapper.obj2String(uploadFileList));
return JsonData.success(uploadFileList);
} catch (Throwable e) {
return JsonData.error("æ–‡ä»¶ä¸Šä¼ å¤±è´¥");
}
}Example 76
| Project: geoserver-master File: GoogleTokenServices.java View source code |
private Map<String, Object> checkToken(String accessToken) {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("token", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
String accessTokenUrl = new StringBuilder(checkTokenEndpointUrl).append("?access_token=").append(accessToken).toString();
return postForMap(accessTokenUrl, formData, headers);
}Example 77
| Project: GNDMS-master File: GORFXClient.java View source code |
@SuppressWarnings("unchecked")
public final ResponseEntity<Specifier<Facets>> createTaskFlow(final String type, final Order order, final String dn, final String wid, MultiValueMap<String, String> context) {
GNDMSResponseHeader requestHeaders = new GNDMSResponseHeader();
if (dn != null) {
requestHeaders.setDN(dn);
}
if (wid != null) {
requestHeaders.setWId(wid);
}
requestHeaders.putAll(context);
HttpEntity<Order> requestEntity = new HttpEntity<Order>(order, requestHeaders);
RestOperations restTemplate = getRestTemplate();
if (null == restTemplate) {
throw new IllegalStateException("No RestTemplate set in GORFXClient.");
}
return (ResponseEntity<Specifier<Facets>>) (Object) restTemplate.exchange(getServiceURL() + "/gorfx/_" + type, HttpMethod.POST, requestEntity, Specifier.class);
}Example 78
| Project: greenhouse-android-master File: SessionTemplate.java View source code |
public float rateSession(long eventId, long sessionId, int rating, String comment) {
requireAuthorization();
String url = new StringBuilder().append("events/").append(eventId).append("/sessions/").append(sessionId).append("/rating").toString();
MultiValueMap<String, String> postData = new LinkedMultiValueMap<String, String>();
postData.add("value", String.valueOf(rating));
postData.add("comment", comment);
return restTemplate.exchange(buildUri(url), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(postData, null), Float.class).getBody();
}Example 79
| Project: hello-world-master File: TcHttpxServiceTest.java View source code |
@Test
public void testGetText4Entity() throws UnsupportedEncodingException {
int id = RandomUtils.nextInt();
Date now = new Date();
TcStubController.TcStubs tcStubs = new TcStubController.TcStubs(id, now);
MultiValueMap<String, String> multiValueMap = tcHttpxService.copy2MultiValueMap(tcStubs);
Assert.assertEquals(String.valueOf(id), multiValueMap.getFirst("id"));
Assert.assertEquals(TcDateUtils.format(now), URLDecoder.decode(multiValueMap.getFirst("now"), StandardCharsets.UTF_8.name()));
ResponseEntity<TcStubController.TcStubs> response = tcHttpxService.getText4Entity("http://localhost:13006/getText", null, null, multiValueMap, new ParameterizedTypeReference<TcStubController.TcStubs>() {
});
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals(tcStubs, response.getBody());
}Example 80
| Project: microservice-master File: OrderWebIntegrationTest.java View source code |
@Test
@Transactional
public void IsSubmittedOrderSaved() {
long before = orderRepository.count();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("submit", "");
map.add("customerId", Long.toString(customer.getCustomerId()));
map.add("orderLine[0].itemId", Long.toString(item.getItemId()));
map.add("orderLine[0].count", "42");
URI uri = restTemplate.postForLocation(orderURL(), map, String.class);
UriTemplate uriTemplate = new UriTemplate(orderURL() + "/{id}");
assertEquals(before + 1, orderRepository.count());
}Example 81
| Project: monitoring-master File: HttpRemoteService.java View source code |
private HttpGet createGet(String url, MultiValueMap<String, String> params) throws URISyntaxException {
URIBuilder uri = new URIBuilder(url);
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
uri.addParameter(key, value);
}
}
return new HttpGet(uri.build());
}Example 82
| Project: myconsumption-android-master File: CreateAccountActivity.java View source code |
private int createAccount() {
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new FormHttpMessageConverter());
template.getMessageConverters().add(new StringHttpMessageConverter());
MultiValueMap<String, String> postParams = new LinkedMultiValueMap<>();
postParams.add("password", CryptoUtils.sha256(editTextPassword.getText().toString()));
try {
String result = template.postForObject(SingleInstance.getServerUrl() + "users/" + editTextUsername.getText().toString(), postParams, String.class);
LOGD(TAG, result);
SimpleResponseDTO response = new ObjectMapper().readValue(result, SimpleResponseDTO.class);
return response.getStatus();
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}Example 83
| Project: PerformanceHat-master File: FeedbackHandlerMonitoringClient.java View source code |
/**
* Sends monitoring data (i.e. the call trace) and its attached metrics to the Feedback Handler.
*
* @param executions
* the {@link RunningProcedureExecution}'s (i.e. the call trace)
* @return <code>true</code> if the data has been successfully sent to the Feedback Handler, <code>false</code>
* otherwise
*/
public boolean postData(final RunningProcedureExecution rootProcedureExecution) {
final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(Headers.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headers.add(Headers.ACCESS_TOKEN, accessToken());
headers.add(Headers.APPLICATION_ID, applicationId());
final HttpEntity<MetricContainingProcedureExecutionDto> httpEntity = new HttpEntity<MetricContainingProcedureExecutionDto>(rootProcedureExecution, headers);
final ResponseEntity<Boolean> result = new RestTemplate().exchange(url(), HttpMethod.POST, httpEntity, Boolean.class);
return result.getBody();
}Example 84
| Project: pinpoint-master File: HttpRemoteService.java View source code |
private HttpGet createGet(String url, MultiValueMap<String, String> params) throws URISyntaxException {
URIBuilder uri = new URIBuilder(url);
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
uri.addParameter(key, value);
}
}
return new HttpGet(uri.build());
}Example 85
| Project: saltedhashed-master File: AuthenticationController.java View source code |
@RequestMapping("/persona/auth")
@ResponseBody
public String authenticateWithPersona(@RequestParam String assertion, @RequestParam boolean userRequestedAuthentication, HttpServletRequest request, HttpServletResponse httpResponse, Model model) throws IOException {
if (context.getUser() != null) {
return "";
}
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("assertion", assertion);
params.add("audience", request.getScheme() + "://" + request.getServerName() + ":" + (request.getServerPort() == 80 ? "" : request.getServerPort()));
PersonaVerificationResponse response = restTemplate.postForObject("https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);
if (response.getStatus().equals("okay")) {
User user = userDao.find(response.getEmail());
if (user == null && userRequestedAuthentication) {
return "/signup?email=" + response.getEmail();
} else if (user != null) {
if (userRequestedAuthentication) {
context.setUser(user);
return "/";
} else {
return "";
}
} else {
//in case this is not a user-requested operation, do nothing
return "";
}
} else {
logger.warn("Persona authentication failed due to reason: " + response.getReason());
throw new IllegalStateException("Authentication failed");
}
}Example 86
| Project: spring-android-master File: HttpEntityTests.java View source code |
public void testMultiValueMap() {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("Content-Type", "text/plain");
String body = "foo";
HttpEntity<String> entity = new HttpEntity<String>(body, map);
assertEquals(body, entity.getBody());
assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType());
assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
}Example 87
| Project: spring-batch-admin-master File: BindingHttpMessageConverter.java View source code |
public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
MultiValueMap<String, ?> map = delegate.read(null, inputMessage);
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(targetType);
initBeanWrapper(beanWrapper);
Map<String, Object> props = new HashMap<String, Object>();
for (String key : map.keySet()) {
if (beanWrapper.isWritableProperty(key)) {
List<?> list = map.get(key);
props.put(key, map.get(key).size() > 1 ? list : map.getFirst(key));
}
}
beanWrapper.setPropertyValues(props);
@SuppressWarnings("unchecked") T result = (T) beanWrapper.getWrappedInstance();
return result;
}Example 88
| Project: spring-cloud-commons-master File: RefreshEndpointIntegrationTests.java View source code |
private RequestEntity<?> getUrlEncodedEntity(String uri, String key, String value) throws URISyntaxException {
MultiValueMap<String, String> env = new LinkedMultiValueMap<String, String>(Collections.singletonMap(key, Arrays.asList(value)));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
RequestEntity<MultiValueMap<String, String>> entity = new RequestEntity<MultiValueMap<String, String>>(env, headers, HttpMethod.POST, new URI(uri));
return entity;
}Example 89
| Project: spring-cloud-dataflow-master File: WhitelistProperties.java View source code |
/**
* Return a copy of app properties where shorthand form have been expanded to their
* long form (amongst the whitelisted supported properties of the app) if applicable.
*
* @param properties the application properties in shorthand form
* @param metadataResource the metadata that can be used to expand shorthand property
* names to long form names
* @return the application properties with expanded long form property names
*/
public Map<String, String> qualifyProperties(Map<String, String> properties, Resource metadataResource) {
MultiValueMap<String, ConfigurationMetadataProperty> whiteList = new LinkedMultiValueMap<>();
Set<String> allProps = new HashSet<>();
for (ConfigurationMetadataProperty property : this.metadataResolver.listProperties(metadataResource, false)) {
// Use names here
whiteList.add(property.getName(), property);
}
for (ConfigurationMetadataProperty property : this.metadataResolver.listProperties(metadataResource, true)) {
// But full ids here
allProps.add(property.getId());
}
Map<String, String> mutatedProps = new HashMap<>(properties.size());
for (Map.Entry<String, String> entry : properties.entrySet()) {
String provided = entry.getKey();
if (!allProps.contains(provided)) {
List<ConfigurationMetadataProperty> longForms = null;
for (String relaxed : new RelaxedNames(provided)) {
longForms = whiteList.get(relaxed);
if (longForms != null) {
break;
}
}
if (longForms != null) {
assertNoAmbiguity(longForms);
mutatedProps.put(longForms.iterator().next().getId(), entry.getValue());
} else {
mutatedProps.put(provided, entry.getValue());
}
} else {
mutatedProps.put(provided, entry.getValue());
}
}
return mutatedProps;
}Example 90
| Project: spring-oauth2-integration-tests-master File: AbstractRefreshTokenSupportTests.java View source code |
private OAuth2AccessToken refreshAccessToken(String refreshToken) {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "refresh_token");
formData.add("client_id", "my-trusted-client");
formData.add("refresh_token", refreshToken);
formData.add("scope", "read");
HttpHeaders headers = getTokenHeaders("my-trusted-client");
@SuppressWarnings("rawtypes") ResponseEntity<Map> response = http.postForMap(tokenPath(), headers, formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue("Wrong cache control: " + response.getHeaders().getFirst("Cache-Control"), response.getHeaders().getFirst("Cache-Control").contains("no-store"));
@SuppressWarnings("unchecked") OAuth2AccessToken newAccessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
return newAccessToken;
}Example 91
| Project: spring-social-lastfm-master File: LastFmPseudoOAuth2Template.java View source code |
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUrl, MultiValueMap<String, String> parameters) {
if (parameters == null) {
parameters = new LinkedMultiValueMap<String, String>();
}
parameters.add("api_key", apiKey);
org.springframework.social.lastfm.auth.LastFmAccessGrant lastFmAccessGrant = lastFmAuthTemplate.exchangeForAccess(authorizationCode, parameters);
LastFmPseudoOAuth2AccessGrant lastFmAccessToken = new LastFmPseudoOAuth2AccessGrant(lastFmAccessGrant.getToken(), lastFmAccessGrant.getSessionKey());
AccessGrant accessGrant = new AccessGrant(lastFmAccessToken.toAccessToken(), null, null, null);
return accessGrant;
}Example 92
| Project: spring-social-master File: FormMapHttpMessageConverter.java View source code |
public Map<String, String> read(Class<? extends Map<String, String>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
LinkedMultiValueMap<String, String> lmvm = new LinkedMultiValueMap<String, String>();
@SuppressWarnings("unchecked") Class<LinkedMultiValueMap<String, String>> mvmClazz = (Class<LinkedMultiValueMap<String, String>>) lmvm.getClass();
MultiValueMap<String, String> mvm = delegate.read(mvmClazz, inputMessage);
return mvm.toSingleValueMap();
}Example 93
| Project: spring-social-weibo-master File: WeiboOAuth2Template.java View source code |
@Override public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { TypeReference<Map<String, ?>> mapType = new TypeReference<Map<String, ?>>() { }; LinkedHashMap<String, ?> readValue = objectMapper.readValue(inputMessage.getBody(), mapType); LinkedMultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(); for (Entry<String, ?> currentEntry : readValue.entrySet()) { result.add(currentEntry.getKey(), currentEntry.getValue().toString()); } return result; }
Example 94
| Project: tradeking-api-consumer-master File: WatchlistTemplate.java View source code |
@Override
public String[] addList(String watchlistName, String[] tickers) {
Assert.notNull(tickers);
URI url = this.buildUri(URL_WATCHLIST_LIST);
MultiValueMap<String, Object> requestObject = new LinkedMultiValueMap<>();
requestObject.add("id", watchlistName);
requestObject.add("symbols", this.buildCommaSeparatedParameterValue(tickers));
ResponseEntity<TKAllWatchListsResponse> response = this.getRestTemplate().postForEntity(url, requestObject, TKAllWatchListsResponse.class);
if (response.getBody().getError() != null)
throw new ApiException(TradeKingServiceProvider.PROVIDER_ID, response.getBody().getError());
return response.getBody().getWatchLists();
}Example 95
| Project: Yarrn-master File: PhotoUploadRequest.java View source code |
@Override
public String loadDataFromNetwork() throws Exception {
final OAuthRequest request = new OAuthRequest(Verb.POST, application.getString(R.string.ravelry_url) + "/upload/request_token.json");
Response requestTokenResponse = executeRequest(request);
final String token = new JSONObject(requestTokenResponse.getBody()).getString("upload_token");
try {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("upload_token", token);
parts.add("access_key", application.getString(R.string.api_key));
final InputStream inputStream = application.getContentResolver().openInputStream(photoUri);
parts.add("file0", new InputStreamResource(inputStream) {
@Override
public long contentLength() throws IOException {
return inputStream.available();
}
@Override
public String getFilename() throws IllegalStateException {
return photoUri.getLastPathSegment();
}
});
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("Content-Type", "multipart/form-data");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
RestTemplate restTemplate = getRestTemplate();
restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
UploadResult uploadResult = restTemplate.postForObject(application.getString(R.string.ravelry_url) + "/upload/image.json", requestEntity, UploadResult.class);
Integer imageId = uploadResult.get("uploads").get("file0").get("image_id");
return addPhotoToProject(imageId, projectId);
} catch (final FileNotFoundException e) {
onError(e);
throw e;
}
}Example 96
| Project: apollo-master File: ReleaseControllerTest.java View source code |
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testReleaseBuild() {
String appId = "someAppId";
AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);
ClusterDTO cluster = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class);
NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);
Assert.assertEquals("someAppId", app.getAppId());
Assert.assertEquals("default", cluster.getName());
Assert.assertEquals("application", namespace.getNamespaceName());
ItemDTO[] items = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class);
Assert.assertEquals(3, items.length);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("name", "someReleaseName");
parameters.add("comment", "someComment");
parameters.add("operator", "test");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
ResponseEntity<ReleaseDTO> response = restTemplate.postForEntity("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/releases", entity, ReleaseDTO.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
ReleaseDTO release = response.getBody();
Assert.assertEquals("someReleaseName", release.getName());
Assert.assertEquals("someComment", release.getComment());
Assert.assertEquals("someAppId", release.getAppId());
Assert.assertEquals("default", release.getClusterName());
Assert.assertEquals("application", release.getNamespaceName());
Map<String, String> configurations = new HashMap<String, String>();
configurations.put("k1", "v1");
configurations.put("k2", "v2");
configurations.put("k3", "v3");
Gson gson = new Gson();
Assert.assertEquals(gson.toJson(configurations), release.getConfigurations());
}Example 97
| Project: be-worktajm-master File: CustomSocialConnectionRepository.java View source code |
@Override public MultiValueMap<String, Connection<?>> findAllConnections() { List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdOrderByProviderIdAscRankAsc(userId); List<Connection<?>> connections = socialUserConnectionsToConnections(socialUserConnections); MultiValueMap<String, Connection<?>> connectionsByProviderId = new LinkedMultiValueMap<>(); Set<String> registeredProviderIds = connectionFactoryLocator.registeredProviderIds(); for (String registeredProviderId : registeredProviderIds) { connectionsByProviderId.put(registeredProviderId, Collections.emptyList()); } for (Connection<?> connection : connections) { String providerId = connection.getKey().getProviderId(); if (connectionsByProviderId.get(providerId).size() == 0) { connectionsByProviderId.put(providerId, new LinkedList<>()); } connectionsByProviderId.add(providerId, connection); } return connectionsByProviderId; }
Example 98
| Project: Broadleaf-eCommerce-master File: AdminAssetController.java View source code |
@Override
@SuppressWarnings("unchecked")
@RequestMapping(value = "", method = RequestMethod.GET)
public String viewEntityList(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @RequestParam MultiValueMap<String, String> requestParams) throws Exception {
String returnPath = super.viewEntityList(request, response, model, pathVars, requestParams);
// Remove the default add button and replace it with an upload asset button
List<EntityFormAction> mainActions = (List<EntityFormAction>) model.asMap().get("mainActions");
Iterator<EntityFormAction> actions = mainActions.iterator();
while (actions.hasNext()) {
EntityFormAction action = actions.next();
if (EntityFormAction.ADD.equals(action.getId())) {
actions.remove();
break;
}
}
mainActions.add(0, new EntityFormAction("UPLOAD_ASSET").withButtonClass("upload-asset").withIconClass("icon-camera").withDisplayText("Upload_Asset"));
// Change the listGrid view to one that has a hidden form for uploading the image.
model.addAttribute("viewType", "entityListWithUploadForm");
ListGrid listGrid = (ListGrid) model.asMap().get("listGrid");
formService.addImageThumbnailField(listGrid, "fullUrl");
return returnPath;
}Example 99
| Project: BroadleafCommerce-master File: AdminAssetController.java View source code |
@Override
@SuppressWarnings("unchecked")
@RequestMapping(value = "", method = RequestMethod.GET)
public String viewEntityList(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @RequestParam MultiValueMap<String, String> requestParams) throws Exception {
String returnPath = super.viewEntityList(request, response, model, pathVars, requestParams);
// Remove the default add button and replace it with an upload asset button
List<EntityFormAction> mainActions = (List<EntityFormAction>) model.asMap().get("mainActions");
Iterator<EntityFormAction> actions = mainActions.iterator();
while (actions.hasNext()) {
EntityFormAction action = actions.next();
if (EntityFormAction.ADD.equals(action.getId())) {
actions.remove();
break;
}
}
mainActions.add(0, new EntityFormAction("UPLOAD_ASSET").withButtonClass("upload-asset").withIconClass("icon-camera").withDisplayText("Upload_Asset"));
// Change the listGrid view to one that has a hidden form for uploading the image.
model.addAttribute("viewType", "entityListWithUploadForm");
ListGrid listGrid = (ListGrid) model.asMap().get("listGrid");
formService.addImageThumbnailField(listGrid, "fullUrl");
return returnPath;
}Example 100
| Project: categolj2-backend-master File: AuthenticationController.java View source code |
@RequestMapping(value = "login", method = RequestMethod.POST)
String login(@RequestParam("username") String username, @RequestParam("password") String password, UriComponentsBuilder builder, RedirectAttributes attributes, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.info("attempt to login (username={})", username);
String tokenEndpoint = builder.path("oauth/token").build().toUriString();
HttpEntity<MultiValueMap<String, Object>> ropRequest = authenticationHelper.createRopRequest(username, password);
try {
ResponseEntity<OAuth2AccessToken> result = restTemplate.postForEntity(tokenEndpoint, ropRequest, OAuth2AccessToken.class);
OAuth2AccessToken accessToken = result.getBody();
authenticationHelper.saveAccessTokenInCookie(accessToken, response);
authenticationHelper.writeLoginHistory(accessToken, request, response);
} catch (HttpStatusCodeException e) {
authenticationHelper.handleHttpStatusCodeException(e, attributes);
return "redirect:/login";
} catch (ResourceAccessException e) {
if (e.getCause() instanceof SSLException) {
UriComponentsBuilder b = builder.replacePath("").port(httpsPort);
return login(username, password, b, attributes, request, response);
} else {
throw e;
}
}
return "redirect:/admin";
}Example 101
| Project: cf-java-component-master File: CfComponentConfiguration.java View source code |
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
final MultiValueMap<String, Object> attributes = importMetadata.getAllAnnotationAttributes(CfComponent.class.getName());
type = evaluate(attributes, "type");
index = Integer.valueOf(evaluate(attributes, "index"));
uuid = evaluate(attributes, "uuid");
if (StringUtils.isEmpty(uuid)) {
uuid = UUID.randomUUID().toString();
}
host = evaluate(attributes, "host");
port = Integer.valueOf(evaluate(attributes, "port"));
username = evaluate(attributes, "username");
password = evaluate(attributes, "password");
if (StringUtils.isEmpty(password)) {
password = new BigInteger(256, ThreadLocalRandom.current()).toString(32);
}
}