Java Code Examples for org.springframework.util.MultiValueMap#add()
The following examples show how to use
org.springframework.util.MultiValueMap#add() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtBearerGrantRequestEntityConverter.java From oauth2-protocol-patterns with Apache License 2.0 | 6 votes |
/** * Returns a {@link MultiValueMap} of the form parameters used for the Access Token Request body. * * @param jwtBearerGrantRequest the Jwt Bearer grant request * @return a {@link MultiValueMap} of the form parameters used for the Access Token Request body */ private MultiValueMap<String, String> buildFormParameters(JwtBearerGrantRequest jwtBearerGrantRequest) { ClientRegistration clientRegistration = jwtBearerGrantRequest.getClientRegistration(); MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>(); formParameters.add(OAuth2ParameterNames.GRANT_TYPE, jwtBearerGrantRequest.getGrantType().getValue()); formParameters.add("assertion", jwtBearerGrantRequest.getJwt().getTokenValue()); if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { formParameters.add(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(jwtBearerGrantRequest.getClientRegistration().getScopes(), " ")); } if (ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) { formParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId()); formParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret()); } return formParameters; }
Example 2
Source File: ServerClient.java From agent with MIT License | 6 votes |
/** * 获取chromedriver下载地址 * * @param mobileId * @return */ public String getChromedriverDownloadUrl(String mobileId) { Assert.hasText(mobileId, "mobileId不能为空"); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("deviceId", mobileId); params.add("type", 1); // chromedriver params.add("platform", Terminal.PLATFORM); // 1.windows 2.linux 3.macos Response<Map<String, String>> response = restTemplate.exchange(driverDownloadUrl, HttpMethod.POST, new HttpEntity<>(params), new ParameterizedTypeReference<Response<Map<String, String>>>() { }).getBody(); if (response.isSuccess()) { return response.getData() != null ? response.getData().get("downloadUrl") : null; } else { throw new RuntimeException(response.getMsg()); } }
Example 3
Source File: SpringMvcIntegrationTestBase.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void ableToPostDate() throws Exception { ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS); MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); body.add("date", RestObjectMapperFactory.getRestObjectMapper().convertToString(Date.from(date.toInstant()))); HttpHeaders headers = new HttpHeaders(); headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE); int seconds = 1; Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds); assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant()))); ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate .postForEntity(codeFirstUrl + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds); ResponseEntity<Date> dateResponseEntity = listenableFuture.get(); assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant()))); }
Example 4
Source File: RequestHeaderMapMethodArgumentResolverTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void resolveMultiValueMapArgument() throws Exception { String name = "foo"; String value1 = "bar"; String value2 = "baz"; request.addHeader(name, value1); request.addHeader(name, value2); MultiValueMap<String, String> expected = new LinkedMultiValueMap<>(1); expected.add(name, value1); expected.add(name, value2); Object result = resolver.resolveArgument(paramMultiValueMap, null, webRequest, null); assertTrue(result instanceof MultiValueMap); assertEquals("Invalid result", expected, result); }
Example 5
Source File: UrlPathHelper.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Decode the given matrix variables via * {@link #decodeRequestString(HttpServletRequest, String)} 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(HttpServletRequest)}. * @param request current HTTP request * @param vars URI variables extracted from the URL path * @return the same Map or a new Map instance */ public MultiValueMap<String, String> decodeMatrixVariables(HttpServletRequest request, MultiValueMap<String, String> vars) { if (this.urlDecode) { return vars; } else { MultiValueMap<String, String> decodedVars = new LinkedMultiValueMap <String, String>(vars.size()); for (String key : vars.keySet()) { for (String value : vars.get(key)) { decodedVars.add(key, decodeInternal(request, value)); } } return decodedVars; } }
Example 6
Source File: UriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void emptyQueryParam() throws URISyntaxException { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.queryParam("baz").build(); assertEquals("baz", result.getQuery()); MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<String, String>(2); expectedQueryParams.add("baz", null); assertEquals(expectedQueryParams, result.getQueryParams()); }
Example 7
Source File: StompHeaderAccessorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void encodeConnectWithLoginAndPasscode() throws UnsupportedEncodingException { MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe"); extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123"); StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders); Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()); byte[] bytes = new StompEncoder().encode(message); assertEquals("CONNECT\nlogin:joe\npasscode:joe123\n\n\0", new String(bytes, "UTF-8")); }
Example 8
Source File: Jackson2ObjectMapperBuilder.java From spring-analysis-note with MIT License | 5 votes |
private void registerModule(Module module, MultiValueMap<Object, Module> modulesToRegister) { if (module.getTypeId() == null) { modulesToRegister.add(SimpleModule.class.getName(), module); } else { modulesToRegister.set(module.getTypeId(), module); } }
Example 9
Source File: StompHeaderAccessorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void createWithMessageFrameNativeHeaders() { MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); extHeaders.add(StompHeaderAccessor.DESTINATION_HEADER, "/d"); extHeaders.add(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER, "s1"); extHeaders.add(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER, "application/json"); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE, extHeaders); assertEquals(StompCommand.MESSAGE, headers.getCommand()); assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); assertEquals("s1", headers.getSubscriptionId()); }
Example 10
Source File: AuthoringController.java From lams with GNU General Public License v2.0 | 5 votes |
/** * This method will get necessary information from imageGallery item form and save or update into * <code>HttpSession</code> ImageGalleryItemList. Notice, this save is not persist them into database, just save * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being * persisted. */ @RequestMapping("/saveOrUpdateImage") public String saveOrUpdateImage(@ModelAttribute ImageGalleryItemForm imageGalleryItemForm, HttpServletRequest request, HttpServletResponse response) { MultiValueMap<String, String> errorMap = ImageGalleryUtils.validateImageGalleryItem(imageGalleryItemForm, true, messageService); try { if (errorMap.isEmpty()) { extractFormToImageGalleryItem(request, imageGalleryItemForm); } } catch (Exception e) { // any upload exception will display as normal error message rather then throw exception directly errorMap.add("GLOBAL", messageService.getMessage(ImageGalleryConstants.ERROR_MSG_UPLOAD_FAILED, new Object[] { e.getMessage() })); } if (!errorMap.isEmpty()) { request.setAttribute("errorMap", errorMap); return "pages/authoring/parts/addimage"; } // set session map ID so that itemlist.jsp can get sessionMAP request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, imageGalleryItemForm.getSessionMapID()); // return null to close this window return "pages/authoring/parts/itemlist"; }
Example 11
Source File: NativeMessageHeaderAccessorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void setNativeHeaderNullValue() { MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>(); nativeHeaders.add("foo", "bar"); NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); headers.setNativeHeader("foo", null); assertNull(headers.getNativeHeader("foo")); }
Example 12
Source File: PostTest.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Test public void postForexchange() { // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递 MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>(); paramMap.add("name", "longzhonghua"); paramMap.add("id", 4); RestTemplate client = restTemplateBuilder.build(); HttpHeaders headers = new HttpHeaders(); //headers.set("id", "long"); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers); ResponseEntity<String> response = client.exchange("http://localhost:8080/postuser", HttpMethod.POST,httpEntity,String.class,paramMap); System.out.println(response.getBody()); }
Example 13
Source File: JsonPathAssertionTests.java From java-technology-stack with MIT License | 5 votes |
@RequestMapping("/music/people") public MultiValueMap<String, Person> get() { MultiValueMap<String, Person> map = new LinkedMultiValueMap<>(); map.add("composers", new Person("Johann Sebastian Bach")); map.add("composers", new Person("Johannes Brahms")); map.add("composers", new Person("Edvard Grieg")); map.add("composers", new Person("Robert Schumann")); map.add("performers", new Person("Vladimir Ashkenazy")); map.add("performers", new Person("Yehudi Menuhin")); return map; }
Example 14
Source File: MatrixVariablesMapMethodArgumentResolverTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void resolveArgumentNoMatch() throws Exception { MultiValueMap<String, String> params2 = getMatrixVariables("planes"); params2.add("colors", "yellow"); params2.add("colors", "orange"); @SuppressWarnings("unchecked") Map<String, String> map = (Map<String, String>) this.resolver.resolveArgument( this.paramMapForPathVar, this.mavContainer, this.webRequest, null); assertEquals(Collections.emptyMap(), map); }
Example 15
Source File: CustomRequestEntityConverter.java From tutorials with MIT License | 5 votes |
@Override public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest req) { RequestEntity<?> entity = defaultConverter.convert(req); MultiValueMap<String, String> params = (MultiValueMap<String,String>) entity.getBody(); params.add("test2", "extra2"); System.out.println(params.entrySet()); return new RequestEntity<>(params, entity.getHeaders(), entity.getMethod(), entity.getUrl()); }
Example 16
Source File: FlashMapTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void addTargetRequestParamsNullKey() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add(" ", "abc"); params.add(null, " "); FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParams(params); assertTrue(flashMap.getTargetRequestParams().isEmpty()); }
Example 17
Source File: AuthoringConditionController.java From lams with GNU General Public License v2.0 | 5 votes |
/** * This method will get necessary information from condition form and save or update into <code>HttpSession</code> * condition list. Notice, this save is not persist them into database, just save <code>HttpSession</code> * temporarily. Only they will be persist when the entire authoring page is being persisted. * * @param mapping * @param form * @param request * @param response * @return * @throws ServletException */ @RequestMapping(value = "/saveOrUpdateCondition") public String saveOrUpdateCondition(@ModelAttribute("surveyConditionForm") SurveyConditionForm surveyConditionForm, HttpServletRequest request) { MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>(); validateSurveyCondition(surveyConditionForm, request, errorMap); if (!errorMap.isEmpty()) { populateFormWithPossibleItems(surveyConditionForm, request); request.setAttribute("errorMap", errorMap); return "pages/authoring/addCondition"; } try { extractFormToSurveyCondition(request, surveyConditionForm); } catch (Exception e) { errorMap.add("GLOBAL", messageService.getMessage("error.condition")); if (!errorMap.isEmpty()) { populateFormWithPossibleItems(surveyConditionForm, request); request.setAttribute("errorMap", errorMap); return "pages/authoring/addCondition"; } } request.setAttribute(SurveyConstants.ATTR_SESSION_MAP_ID, surveyConditionForm.getSessionMapID()); request.setAttribute("surveyConditionForm", surveyConditionForm); return "pages/authoring/conditionList"; }
Example 18
Source File: NativeMessageHeaderAccessorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void createFromMessageAndModify() { MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>(); inputNativeHeaders.add("foo", "bar"); inputNativeHeaders.add("bar", "baz"); Map<String, Object> nativeHeaders = new HashMap<String, Object>(); nativeHeaders.put("a", "b"); nativeHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders); GenericMessage<String> message = new GenericMessage<>("p", nativeHeaders); NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message); headerAccessor.setHeader("a", "B"); headerAccessor.setNativeHeader("foo", "BAR"); Map<String, Object> actual = headerAccessor.toMap(); assertEquals(2, actual.size()); assertEquals("B", actual.get("a")); @SuppressWarnings("unchecked") Map<String, List<String>> actualNativeHeaders = (Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS); assertNotNull(actualNativeHeaders); assertEquals(Arrays.asList("BAR"), actualNativeHeaders.get("foo")); assertEquals(Arrays.asList("baz"), actualNativeHeaders.get("bar")); }
Example 19
Source File: SignupManagementController.java From lams with GNU General Public License v2.0 | 4 votes |
@RequestMapping(path = "/add") public String add(@ModelAttribute("signupForm") SignupManagementForm signupForm, HttpServletRequest request) throws Exception { MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>(); // check if form submitted if (signupForm.getOrganisationId() != null && signupForm.getOrganisationId() > 0) { // validate if (!StringUtils.equals(signupForm.getCourseKey(), signupForm.getConfirmCourseKey())) { errorMap.add("courseKey", messageService.getMessage("error.course.keys.unequal")); } if (signupService.contextExists(signupForm.getSignupOrganisationId(), signupForm.getContext())) { errorMap.add("context", messageService.getMessage("error.context.exists")); } if (!errorMap.isEmpty()) { request.setAttribute("errorMap", errorMap); } else { // proceed SignupOrganisation signup; if (signupForm.getSignupOrganisationId() != null && signupForm.getSignupOrganisationId() > 0) { // form was editing existing signup = (SignupOrganisation) userManagementService.findById(SignupOrganisation.class, signupForm.getSignupOrganisationId()); } else { signup = new SignupOrganisation(); signup.setCreateDate(new Date()); } signup.setAddToLessons(signupForm.isAddToLessons()); signup.setAddAsStaff(signupForm.isAddAsStaff()); signup.setAddWithAuthor(signupForm.isAddWithAuthor()); signup.setAddWithMonitor(signupForm.isAddWithMonitor()); signup.setEmailVerify(signupForm.getEmailVerify()); signup.setDisabled(signupForm.isDisabled()); signup.setLoginTabActive(signupForm.isLoginTabActive()); signup.setOrganisation((Organisation) userManagementService.findById(Organisation.class, signupForm.getOrganisationId())); signup.setCourseKey(signupForm.getCourseKey()); signup.setBlurb(signupForm.getBlurb()); signup.setContext(signupForm.getContext()); userManagementService.save(signup); return "forward:/signupManagement/start.do"; } } else { // form not submitted, default values signupForm.setBlurb("Register your LAMS account for this group using the form below."); } List<Organisation> organisations = signupService.getOrganisationCandidates(); request.setAttribute("organisations", organisations); return "signupmanagement/add"; }
Example 20
Source File: GroupServiceImplement.java From withme3.0 with MIT License | 4 votes |
@Override public Response createGroup(String groupName, String groupIntroduction, Integer groupCreatorId) { try { Groups group = new Groups(); String groupId = String.valueOf((int) (Math.random() * 100000)); while (groupRepository.findByGroupId(groupId) != null) { groupId = String.valueOf((int) (Math.random() * 100000)); } // Response response = restTemplate.getForEntity(CONSTANT.USER_SERVICE_GET_USER_BY_USERID, Response.class, groupCreatorId).getBody(); // JSONObject user = JSONObject.parseObject((String)response.getContent()); group.setGroupId(groupId); group.setGroupCreatorId(groupCreatorId); group.setGroupIntroduction(groupIntroduction); group.setGroupName(groupName); group.setGroupCreateTime(Common.getCurrentTime()); group.setGroupUserCount(0); group.setGroupMembers(""); groupRepository.save(group); UserGroupRelation userGroupRelation = new UserGroupRelation(); //这里两个id不是一回事,一个是逻辑id,一个是业务id,要区分开 Groups groups = groupRepository.findByGroupId(groupId); userGroupRelation.setGroupId(groups.getId()); userGroupRelation.setUserId(groupCreatorId); userGroupRelation.setEnterGroupTime(Common.getCurrentTime()); userGroupRelation.setGroupUserNickName(""); userGroupRelation.setGroupLevel(10); userGroupRelationRepository.save(userGroupRelation); groups.setGroupMembers(String.valueOf(groupCreatorId)); groups.setGroupUserCount(groups.getGroupUserCount() + 1); groupRepository.save(groups); JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("groupId", groupId); MultiValueMap<String, Integer> requestEntity = new LinkedMultiValueMap<>(); requestEntity.add("userId", groupCreatorId); requestEntity.add("groupId", groups.getId()); ResponseEntity<Response> responseEntity = restTemplate.postForEntity(CONSTANT.USER_SERVICE_UPDATE_USER_GROUPS, requestEntity, Response.class); if(responseEntity.getBody().getStatus() != 1){ return new Response(-1, "远程服务异常", null); } return new Response(1, "创建群组成功", jsonObject1.toJSONString()); } catch (Exception e) { e.printStackTrace(); return new Response(-1, "创建群组异常", null); } }