private void send(String subject, String to, String toEmail, String body) { final String url = "https://api.mailgun.net/v3/" + env.getProperty("mailgun.domain") + "/messages"; final MultiValueMap<String, String> args = new LinkedMultiValueMap<>(); args.put("subject", singletonList(subject)); args.put("from", singletonList(env.getProperty("service.email.sitename") + " <" + env.getProperty("service.email.sender") + ">")); args.put("to", singletonList(to + " <" + toEmail + ">")); args.put("html", singletonList(body)); final ResponseEntity<MailGunResponse> response = mailgun.postForEntity(url, args, MailGunResponse.class); if (!response.getStatusCode().is2xxSuccessful()) { throw new RuntimeException( "Error delivering mail. Message: " + response.getBody().getMessage() ); } }
public static String getAnswer(RestTemplate restTemplate, String question) { String url = "http://www.tuling123.com/openapi/api"; HttpHeaders headers = new HttpHeaders(); headers.add("Ocp-Apim-Subscription-Key", "3f5a37d9698744f3b40c89e2f0c94fb1"); headers.add("Content-Type", "application/x-www-form-urlencoded"); MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>(); bodyMap.add("key", "e2e33efb4efb4e5794b48a18578384ee"); bodyMap.add("info", question); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headers); String result = restTemplate.postForObject(url, requestEntity, String.class); return JsonPath.read(result, "$.text"); }
@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) == null || connectionsByProviderId.get(providerId).size() == 0) { connectionsByProviderId.put(providerId, new LinkedList<>()); } connectionsByProviderId.add(providerId, connection); } return connectionsByProviderId; }
@Override public MultiValueMap<String, Connection<?>> findConnectionsToUsers( MultiValueMap<String, String> providerUserIdsByProviderId) { if (providerUserIdsByProviderId == null || providerUserIdsByProviderId.isEmpty()) { throw new IllegalArgumentException("Unable to execute find: no providerUsers provided"); } MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<>(); for (Map.Entry<String, List<String>> entry : providerUserIdsByProviderId.entrySet()) { String providerId = entry.getKey(); List<String> providerUserIds = entry.getValue(); List<Connection<?>> connections = providerUserIdsToConnections(providerId, providerUserIds); connections.forEach(connection -> connectionsForUsers.add(providerId, connection)); } return connectionsForUsers; }
@Test @SuppressWarnings("unchecked") public void findConnectionsToUsers() { connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory()); insertTwitterConnection(); insertFacebookConnection(); insertFacebookConnection2(); MultiValueMap<String, String> providerUsers = new LinkedMultiValueMap<>(); providerUsers.add("facebook", "10"); providerUsers.add("facebook", "9"); providerUsers.add("twitter", "1"); MultiValueMap<String, Connection<?>> connectionsForUsers = connectionRepository.findConnectionsToUsers(providerUsers); assertEquals(2, connectionsForUsers.size()); String providerId=connectionsForUsers.getFirst("facebook").getKey().getProviderUserId(); assertTrue("10".equals(providerId) || "9".equals(providerId) ); assertFacebookConnection((Connection<TestFacebookApi>) connectionRepository.getConnection(new ConnectionKey("facebook", "9"))); assertTwitterConnection((Connection<TestTwitterApi>) connectionsForUsers.getFirst("twitter")); }
@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; }
@Test public void ableToUploadFileWithoutAnnotation() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; String username = "mike"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.add("file2", new FileSystemResource(newFile(file2Content).getAbsolutePath())); map.add("name", username); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); String result = restTemplate.postForObject( codeFirstUrl + "uploadWithoutAnnotation", new HttpEntity<>(map, headers), String.class); assertThat(result, is(file1Content + file2Content + username)); }
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity( Submission submission, HttpHeaders headers) { logger.debug("Building response entity"); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); try { map.add("test_output", new ObjectMapper().writeValueAsString( submission.getTestOutput())); } catch (JsonProcessingException ex) { logger.debug("POJO deserialization failed"); } map.add("stdout", submission.getStdout()); map.add("stderr", submission.getStderr()); map.add("validations", submission.getValidations()); map.add("vm_log", submission.getVmLog()); map.add("token", submission.getId().toString()); map.add("status", submission.getStatus().toString()); map.add("exit_code", submission.getExitCode().toString()); return new HttpEntity<>(map, headers); }
@Test public void ableToPostDate() throws Exception { ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS); MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); body.add("date", RestObjectMapper.INSTANCE.convertToString(Date.from(date.toInstant()))); HttpHeaders headers = new HttpHeaders(); headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE); int seconds = 1; for (String url : urls) { Date result = restTemplate.postForObject(url + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds); assertEquals(Date.from(date.plusSeconds(seconds).toInstant()), result); } }
private void send(String subject, String to, String toEmail, String body) { final String url = "https://api.mailgun.net/v3/" + env.getProperty("mailgun.domain") + "/messages"; final MultiValueMap<String, String> args = new LinkedMultiValueMap<>(); args.put("subject", singletonList(subject)); args.put("from", singletonList(env.getProperty("service.email.sitename") + " <" + env.getProperty("service.email.sender") + ">")); args.put("to", singletonList(to + " <" + toEmail + ">")); args.put("html", singletonList(body)); final ResponseEntity<MailGunResponse> response = mailgun.postForEntity(url, args, MailGunResponse.class); if (!response.getStatusCode().is2xxSuccessful()) { throw new MailDeliveryException( "Error delivering mail. Message: " + response.getBody().getMessage() ); } }
public static void main(String[] args) throws Exception { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("X-Tenant-Name", "default"); RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices")); ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class); System.out.println(stringResponseEntity.getBody()); ResponseEntity<MicroserviceArray> microseriveResponseEntity = template .exchange(requestEntity, MicroserviceArray.class); MicroserviceArray microserives = microseriveResponseEntity.getBody(); System.out.println(microserives.getServices().get(1).getServiceId()); // instance headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId()); requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId() + "/instances")); ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class); System.out.println(microserviceInstanceResponseEntity.getBody()); }
/** * * * <p><b>200</b> - Success * @param model The model parameter * @return JwtToken * @throws RestClientException if an error occurs while attempting to invoke the API */ public JwtToken apiAuthorizationJwtPost(LoginModel model) throws RestClientException { Object postBody = model; String path = UriComponentsBuilder.fromPath("/api/authorization/jwt").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "text/plain", "application/json", "text/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<JwtToken> returnType = new ParameterizedTypeReference<JwtToken>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
/** * * * <p><b>200</b> - Success * @param model The model parameter * @throws RestClientException if an error occurs while attempting to invoke the API */ public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException { Object postBody = model; String path = UriComponentsBuilder.fromPath("/api/authorization/login").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
/** * Build unauthorized response entity. * * @param code the code * @return the response entity */ private static ResponseEntity buildUnauthorizedResponseEntity(final String code) { final LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(1); map.add(OAuth20Constants.ERROR, code); final String value = OAuth20Utils.jsonify(map); return new ResponseEntity<>(value, HttpStatus.UNAUTHORIZED); }
public static CompositeAccessToken getAccessAndRefreshToken(String oauthEndpoint, String code, DashboardClient dashboardClient, String redirectUri) throws RestClientException { String clientBasicAuth = getClientBasicAuthHeader(dashboardClient.getId(), dashboardClient.getSecret()); RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String,String> form = new LinkedMultiValueMap<>(); form.add("response_type", "token"); form.add("grant_type", "authorization_code"); form.add("client_id", dashboardClient.getId()); form.add("client_secret", dashboardClient.getSecret()); form.add("redirect_uri", redirectUri); form.add("code", code); ResponseEntity<CompositeAccessToken> token = template.exchange(oauthEndpoint + "/token", HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class); if (token != null) return token.getBody(); else return null; }
@Test public void shouldGetTopStoriesOfLocation() throws Exception{ Story story = generateStory(); Geolocation geolocation = new Geolocation(); geolocation.setLatitude(0); geolocation.setLongitude(0); MultiValueMap<String,String> params = new LinkedMultiValueMap<>(); params.add("latitude",String.valueOf(geolocation.getLatitude())); params.add("longitude",String.valueOf(geolocation.getLongitude())); when(topStoriesService.getStoriesOfLocation(any(Geolocation.class))).thenReturn(ImmutableList.of(story)); mockMvc.perform(get("/topStories/location").params(params)) .andExpect(jsonPath("$[0].id").value(story.getId())) .andExpect(status().isOk()); }
@Test public void shouldRetrieveHotStories() throws Exception{ Story story = generateStory(); Geolocation geolocation = new Geolocation(); geolocation.setLatitude(0); geolocation.setLongitude(0); MultiValueMap<String,String> params = new LinkedMultiValueMap<>(); params.add("latitude",String.valueOf(geolocation.getLatitude())); params.add("longitude",String.valueOf(geolocation.getLongitude())); when(homepageService.retrieveHotStories(anyString(),any(Geolocation.class))).thenReturn(ImmutableList.of(story)); mockMvc.perform(get("/homepage/retrieveHotStories").params(params).principal(new UserPrincipal("testUserId"))) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].id").value(story.getId())); }
@Test public void shouldRetrieveNewStories() throws Exception{ Story story = generateStory(); Geolocation geolocation = new Geolocation(); geolocation.setLatitude(0); geolocation.setLongitude(0); MultiValueMap<String,String> params = new LinkedMultiValueMap<>(); params.add("latitude",String.valueOf(geolocation.getLatitude())); params.add("longitude",String.valueOf(geolocation.getLongitude())); when(homepageService.retrieveNewStories(anyString(),any(Geolocation.class))).thenReturn(ImmutableList.of(story)); mockMvc.perform(get("/homepage/retrieveNewStories").params(params).principal(new UserPrincipal("testUserId"))) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].id").value(story.getId())); }
@Override protected HierarchicalUriComponents expandInternal(UriTemplateVariables uriVariables) { Assert.state(!this.encoded, "Cannot expand an already encoded UriComponents object"); String expandedScheme = expandUriComponent(getScheme(), uriVariables); String expandedUserInfo = expandUriComponent(this.userInfo, uriVariables); String expandedHost = expandUriComponent(this.host, uriVariables); PathComponent expandedPath = this.path.expand(uriVariables); MultiValueMap<String, String> expandedQueryParams = new LinkedMultiValueMap<String, String>(this.queryParams.size()); for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) { String expandedName = expandUriComponent(entry.getKey(), uriVariables); List<String> expandedValues = new ArrayList<String>(entry.getValue().size()); for (String value : entry.getValue()) { String expandedValue = expandUriComponent(value, uriVariables); expandedValues.add(expandedValue); } expandedQueryParams.put(expandedName, expandedValues); } String expandedFragment = expandUriComponent(this.getFragment(), uriVariables); return new HierarchicalUriComponents(expandedScheme, expandedUserInfo, expandedHost, this.port, expandedPath, expandedQueryParams, expandedFragment, false, false); }
/** * Create occurrence. * * @param occurrence the occurrence * @return the occurrence */ public Occurrence create(Occurrence occurrence) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("message", createMessage(occurrence)); map.add("link", occurrence.getUrl()); map.add("place", occurrence.getEvent().flatMap(Event::getLocation).map(Location::getFacebookId).map(String::valueOf).orElse("")); map.add("published", "false"); map.add("scheduled_publish_time", String.valueOf(occurrence.getStartTime().minusHours((int) (Math.random() * 6 + 1)).getMillis() / 1000)); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<FacebookPost> response = restTemplate.postForEntity(generateRequestUrl(), request, FacebookPost.class); occurrence.setFacebookPostId(response.getBody().getId()); return occurrence; }
@Test @WithMockUser("user123") public void testSocialConnections() throws Exception { LinkedMultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>(); connections.add(connection.getKey().getProviderId(), connection); when(connectionRepository.findAllConnections()).thenReturn(connections); MockHttpServletRequestBuilder request = get("/api/profile/socials") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andDo(document("user-profile-socials-list")) .andReturn() .getResponse(); assertThat(response.getStatus()).isEqualTo(200); JsonNode jsonResponse = objectMapper.readTree(response.getContentAsByteArray()); assertThat(jsonResponse.isObject()).isTrue(); assertThat(jsonResponse.has(PROVIDER_ID)).isTrue(); assertThat(jsonResponse.get(PROVIDER_ID).isObject()).isTrue(); assertThat(jsonResponse.get(PROVIDER_ID).get("imageUrl").textValue()).isEqualTo(connection.getImageUrl()); verify(connectionRepository).findAllConnections(); }
/** * Create Feed Post * <p> * Requires the Twitch *channel_feed_edit* Scope. * * @param credential OAuth token for a Twitch user (that as 2fa enabled) * @param channelId Channel ID * @param message message to feed * @param share Share to Twitter if is connected */ public void createFeedPost(OAuthCredential credential, Long channelId, String message, Optional<Boolean> share) { // Endpoint String requestUrl = String.format("%s//feed/%s/posts", Endpoints.API.getURL(), channelId); RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential); // Parameters restTemplate.getInterceptors().add(new QueryRequestInterceptor("share", share.orElse(false).toString())); // Post Data MultiValueMap<String, Object> postBody = new LinkedMultiValueMap<String, Object>(); postBody.add("content", message); // REST Request try { restTemplate.postForObject(requestUrl, postBody, Void.class); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } }
private HttpEntity<MultiValueMap<String, Object>> buildRequestEntity(byte[] packaged, String notifyToken, String notifyUrl) { MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); HttpHeaders textHeaders = new HttpHeaders(); textHeaders.setContentType(MediaType.TEXT_PLAIN); HttpHeaders binaryHeaders = new HttpHeaders(); binaryHeaders.setContentDispositionFormData("file", SUBMISSION_FILENAME); map.add("file", new HttpEntity<>(new ByteArrayResource(packaged), binaryHeaders)); map.add("token", new HttpEntity<>(notifyToken, textHeaders)); map.add("notify", new HttpEntity<>(notifyUrl, textHeaders)); return new HttpEntity<>(map); }
@Test public void cancelsBooking() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("number", bookingId); form.add("userid", userId); ResponseEntity<String> responseEntity = restTemplate.exchange( "/rest/api/bookings/cancelbooking", HttpMethod.POST, new HttpEntity<>(form, headers), String.class ); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody(), is("booking " + bookingId + " deleted.")); verify(bookingService).cancelBooking(userId, bookingId); }
private MultiValueMap<String, BuildArtifact> getBuildArtifactsById( List<DeployableArtifact> deployableArtifacts) { MultiValueMap<String, BuildArtifact> buildArtifacts = new LinkedMultiValueMap<>(); deployableArtifacts.forEach((deployableArtifact) -> { try { String id = getArtifactId(deployableArtifact); getBuildArtifact(deployableArtifact).ifPresent( (buildArtifact) -> buildArtifacts.add(id, buildArtifact)); } catch (Exception ex) { // Ignore and don't add as a module } }); return buildArtifacts; }
private static MultiValueMap<String, String> getRequestParameters(NativeWebRequest request, String... ignoredParameters) { List<String> ignoredParameterList = asList(ignoredParameters); MultiValueMap<String, String> convertedMap = new LinkedMultiValueMap<>(); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { if (!ignoredParameterList.contains(entry.getKey())) { convertedMap.put(entry.getKey(), asList(entry.getValue())); } } return convertedMap; }
/** * Get the request entity payload * @param requestEntity RequestEntity * @return Request entity payload, may be null */ protected Object getRequestPayload(RequestEntity<?> requestEntity) { if (requestEntity != null) { boolean form = requestEntity.getMediaType().map(m -> APPLICATION_FORM_URLENCODED_MEDIA_TYPE.equals(m)) .orElse(Boolean.FALSE); return requestEntity.getPayload().map(p -> form ? new LinkedMultiValueMap<>(HttpUtils.getAsMultiMap(p)) : p) .orElse(null); } return null; }
@Test public void testBuildOuath1Url() { when(oauth1Operations.getVersion()).thenReturn(OAuth1Version.CORE_10); when(oauth1Operations.fetchRequestToken(any(), any())).thenReturn(oauthToken); when(oauth1Operations.buildAuthenticateUrl(any(), any())).thenReturn("oauth1redirect"); String result = target.buildOAuthUrl(oauth1ConnectionFactory, request, new LinkedMultiValueMap<>()); assertEquals("oauth1redirect", result); }
@Test public void browsesFlightsWithUnderlyingService() { when(flightService.getFlightByAirports( departFlight.getFlightSegment().getOriginPort(), departFlight.getFlightSegment().getDestPort())).thenReturn(singletonList(departFlight)); when(flightService.getFlightByAirports( departFlight.getFlightSegment().getDestPort(), departFlight.getFlightSegment().getOriginPort())).thenReturn(singletonList(returnFlight)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("fromAirport", departFlight.getFlightSegment().getOriginPort()); form.add("toAirport", departFlight.getFlightSegment().getDestPort()); form.add("oneWay", String.valueOf(false)); ResponseEntity<TripFlightOptions> responseEntity = restTemplate.exchange( "/rest/api/flights/browseflights", HttpMethod.POST, new HttpEntity<>(form, headers), TripFlightOptions.class ); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); TripFlightOptions flightOptions = responseEntity.getBody(); assertThat(flightOptions.getTripLegs(), is(2)); List<TripLegInfo> tripFlights = flightOptions.getTripFlights(); assertThat(tripFlights.get(0).getFlightsOptions(), contains(toFlightInfo(departFlight))); assertThat(tripFlights.get(1).getFlightsOptions(), contains(toFlightInfo(returnFlight))); }
public void test_for_issue() throws Exception { ParserConfig parserConfig = new ParserConfig(); parserConfig.setAutoTypeSupport(true); LinkedMultiValueMap<String, String> result = new LinkedMultiValueMap(); result.add("test", "11111"); String test = JSON.toJSONString(result, SerializerFeature.WriteClassName); JSON.parseObject(test, Object.class, parserConfig, JSON.DEFAULT_PARSER_FEATURE); }
/** * 把数据先保存到keyvalue里. */ public FormParameter doSaveRecord(Map<String, Object> map, String userId, String tenantId) throws Exception { FormParameter formParameter = new FormParameter(); MultiValueMap multiValueMap = new LinkedMultiValueMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { multiValueMap.add(entry.getKey(), entry.getValue()); } formParameter.setMultiValueMap(multiValueMap); formParameter.setBpmProcessId((String) map.get("bpmProcessId")); String businessKey = operationService.saveDraft(userId, tenantId, formParameter); if ((formParameter.getBusinessKey() == null) || "".equals(formParameter.getBusinessKey().trim())) { formParameter.setBusinessKey(businessKey); } Record record = keyValueConnector.findByCode(businessKey); record = new RecordBuilder().build(record, multiValueMap, tenantId); keyValueConnector.save(record); return formParameter; }
private MultiValueMap<String, String> getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); if(request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else { form.set("scope", OAuth2Utils.formatParameterList(resource.getScope())); } String redirectUri = resource.getPreEstablishedRedirectUri(); Object preservedState = request.getPreservedState(); if(redirectUri == null && preservedState != null) { redirectUri = String.valueOf(preservedState); } else { redirectUri = request.getCurrentUri(); } String stateKey = request.getStateKey(); if(stateKey != null) { form.set("state", stateKey); if(preservedState == null) { throw new InvalidRequestException("Possible CSRF detected - state parameter was present but no state could be found"); } } if(redirectUri != null) { form.set("redirect_uri", redirectUri); } return form; }