Java 类org.springframework.util.MultiValueMap 实例源码

项目:users-service    文件:EmailServiceImpl.java   
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()
        );
    }
}
项目:monarch    文件:ClientHttpRequest.java   
/**
 * 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 {
      // NOTE the HTTP "Content-Type" header will be determined and set by the appropriate
      // HttpMessageConverter
      // based on the Class type of the "content".
      return new HttpEntity<Object>(getContent(), getHeaders());
    }
  } else {
    return new HttpEntity<Object>(getHeaders());
  }
}
项目:knowledge-forest-dialogue-recommendation    文件:Tuling123.java   
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");
}
项目:tdd-pingpong    文件:FakeSandboxRestService.java   
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);
}
项目:Code4Health-Platform    文件:CustomSocialUsersConnectionRepositoryIntTest.java   
@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"));
}
项目:microservices-sample-project    文件:AsyncResponseEntityReturnHandler.java   
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue);

    Observable<?> observable = asyncResponseEntity.getObservable();
    Single<?> single = asyncResponseEntity.getSingle();
    MultiValueMap<String, String> headers =  asyncResponseEntity.getHeaders();
    HttpStatus status = asyncResponseEntity.getStatus();

    if(observable != null)
        WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer);
    else if(single != null)
        WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer);

}
项目:spring-io    文件:CustomSocialUsersConnectionRepositoryIntTest.java   
@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"));
}
项目:smarti    文件:RocketChatEndpoint.java   
private void notifyRocketChat(String callbackUrl, Conversation conversation, String token) {
    if (StringUtils.isBlank(callbackUrl)) return;

    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        final HttpPost post = new HttpPost(callbackUrl);
        final MultiValueMap<String, String> props = CollectionUtils.toMultiValueMap(conversation.getMeta().getProperties());
        post.setEntity(new StringEntity(
                toJsonString(new SmartiUpdatePing(conversation.getId(), props.getFirst(ConversationMeta.PROP_CHANNEL_ID), token)),
                ContentType.APPLICATION_JSON
        ));
        httpClient.execute(post, response -> null);
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage(), e);
        } else {
            log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage());
        }
    }
}
项目:incubator-servicecomb-java-chassis    文件:SpringMvcIntegrationTestBase.java   
@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));
}
项目:incubator-servicecomb-java-chassis    文件:SpringMvcIntegrationTestBase.java   
@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;
  Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
      new HttpEntity<>(body, headers),
      Date.class,
      seconds);

  assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));
}
项目:incubator-servicecomb-java-chassis    文件:ServiceCenterExample.java   
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());
}
项目:smarti    文件:ConversationMltQueryBuilder.java   
@Override
protected QueryRequest buildSolrRequest(ComponentConfiguration conf, Template intent, Conversation conversation, long offset, int pageSize, MultiValueMap<String, String> queryParams) {
    final ConversationMltQuery mltQuery = buildQuery(conf, intent, conversation);
    if (mltQuery == null) {
        return null;
    }

    final SolrQuery solrQuery = new SolrQuery();
    solrQuery.addField("*").addField("score");
    solrQuery.addFilterQuery(String.format("%s:%s", FIELD_TYPE, TYPE_MESSAGE));
    solrQuery.addFilterQuery(String.format("%s:0",FIELD_MESSAGE_IDX));
    solrQuery.addSort("score", SolrQuery.ORDER.desc).addSort(FIELD_VOTE, SolrQuery.ORDER.desc);

    // #39 - paging
    solrQuery.setStart((int) offset);
    solrQuery.setRows(pageSize);

    //since #46 the client field is used to filter for the current user
    addClientFilter(solrQuery, conversation);

    addPropertyFilters(solrQuery, conversation, conf);

    return new ConversationMltRequest(solrQuery, mltQuery.getContent());

}
项目:Settings    文件:AuthorizationApi.java   
/**
 * 
 * 
 * <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);
}
项目:Settings    文件:ApiClient.java   
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param <T> the return type to use
 * @param path The sub-path of the HTTP URL
 * @param method The request method
 * @param queryParams The query parameters
 * @param body The request body object
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @param returnType The return type into which to deserialize the response
 * @return The response body in chosen type
 */
public <T> T invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
    updateParamsForAuth(authNames, queryParams, headerParams);

    final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
    if (queryParams != null) {
        builder.queryParams(queryParams);
    }

    final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri());
    if(accept != null) {
        requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
    }
    if(contentType != null) {
        requestBuilder.contentType(contentType);
    }

    addHeadersToRequest(headerParams, requestBuilder);
    addHeadersToRequest(defaultHeaders, requestBuilder);

    RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType));

    ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);

    statusCode = responseEntity.getStatusCode();
    responseHeaders = responseEntity.getHeaders();

    if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) {
        return null;
    } else if (responseEntity.getStatusCode().is2xxSuccessful()) {
        if (returnType == null) {
            return null;
        }
        return responseEntity.getBody();
    } else {
        // The error handler built into the RestTemplate should handle 400 and 500 series errors.
        throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler");
    }
}
项目:Settings    文件:ApiKeyAuth.java   
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
    if (apiKey == null) {
        return;
    }
    String value;
    if (apiKeyPrefix != null) {
        value = apiKeyPrefix + " " + apiKey;
    } else {
        value = apiKey;
    }
    if (location.equals("query")) {
        queryParams.add(paramName, value);
    } else if (location.equals("header")) {
        headerParams.add(paramName, value);
   }
}
项目:Facegram    文件:HomepageControllerTest.java   
@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()));
}
项目:Sound.je    文件:FacebookPoster.java   
/**
 * 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;
}
项目:spring-cloud-vault-connector    文件:VaultServiceInfoCreator.java   
@Override
public VaultServiceInfo createServiceInfo(String id, String uri) {

    UriComponents uriInfo = UriComponentsBuilder.fromUriString(uri).build();

    String address = UriComponentsBuilder.newInstance() //
            .scheme(uriInfo.getScheme()) //
            .host(uriInfo.getHost()) //
            .port(uriInfo.getPort()) //
            .build().toString();

    MultiValueMap<String, String> queryParams = uriInfo.getQueryParams();

    String token = queryParams.getFirst("token");
    Assert.hasText(token, "Token (token=…) must not be empty");

    Map<String, String> backends = getBackends(queryParams, backendPattern);
    Map<String, String> sharedBackends = getBackends(queryParams,
            sharedBackendPattern);

    return new VaultServiceInfo(id, address, token.toCharArray(), backends,
            sharedBackends);
}
项目:spring-cloud-vault-connector    文件:VaultServiceInfoCreator.java   
private Map<String, String> getBackends(MultiValueMap<String, String> queryParams,
        Pattern pattern) {

    Map<String, String> backends = new HashMap<String, String>();

    for (Entry<String, List<String>> entry : queryParams.entrySet()) {

        Matcher matcher = pattern.matcher(entry.getKey());
        if (!matcher.find()) {
            continue;
        }

        backends.put(matcher.group(1), queryParams.getFirst(entry.getKey()));
    }

    return backends;
}
项目:nordvisa_calendar    文件:UserInformationValidatorTest.java   
@Test
public void validateRecaptcha() throws Exception {
    String url = "http://someurl.com";
    String secret = "shhhhhh";
    String secretFromClient = "SSSSSSSSSSSSHHHH!!!";
    ReflectionTestUtils.setField(sut, "recaptchaUrl", url);
    ReflectionTestUtils.setField(sut, "recaptchaRes", secret);

    ResponseEntity<RecaptchaResponseDTO> responseEntity = mock(ResponseEntity.class);
    RecaptchaResponseDTO dto = mock(RecaptchaResponseDTO.class);

    when(rest.postForEntity(eq(url), any(MultiValueMap.class), eq(RecaptchaResponseDTO.class)))
            .thenReturn(responseEntity);
    when(responseEntity.getBody()).thenReturn(dto);

    RecaptchaResponseDTO response = sut.validateRecaptcha(secretFromClient);

    assertEquals(dto, response);

    ArgumentCaptor<MultiValueMap> captor = ArgumentCaptor.forClass(MultiValueMap.class);
    verify(rest, times(1)).postForEntity(eq(url), captor.capture(), eq(RecaptchaResponseDTO.class));
    MultiValueMap<String, String> body = captor.getValue();

    assertEquals(secretFromClient, body.getFirst("secret"));
    assertEquals(secret, body.getFirst("response"));
}
项目:theskeleton    文件:SocialConnectionService.java   
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
    List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdOrderByRankAsc(userId);
    MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>();
    socialConnections.forEach(socialConnection -> {
        Connection<?> connection = connectionMapper.mapRow(socialConnection);
        String providerId = connection.getKey().getProviderId();
        connections.add(providerId, connection);
    });
    return connections;
}
项目:EasyTransaction    文件:RestRibbonEasyTransRpcConsumerImpl.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <P extends EasyTransRequest<R, ?>, R extends Serializable> R call(String appId, String busCode, String innerMethod, Map<String,Object> header, P params) {

    String context = properties.getConsumer().get(appId).getContext();
    if(context == null){
        context = "";
    }

    Class<? extends EasyTransRequest> paramsClass = params.getClass();
    Class<?> resultClass = ReflectUtil.getResultClass(paramsClass);


    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.set(RestRibbonEasyTransConstants.HttpHeaderKey.EASYTRANS_HEADER_KEY, encodeEasyTransHeader(header));
    HttpEntity<P> requestEntity = new HttpEntity<>(params, headers);

    ResponseEntity<?> exchangeResult = loadBalancedRestTemplate.exchange("http://" + appId + "/" + context + "/" + busCode + "/" + innerMethod, HttpMethod.POST, requestEntity, resultClass);
    if(!exchangeResult.getStatusCode().is2xxSuccessful()){
        throw new RuntimeException("远程请求发生错误:" + exchangeResult);
    }

    return (R) exchangeResult.getBody();
}
项目:xm-uaa    文件:SocialController.java   
@PostMapping(value = "/signin/{providerId}")
public RedirectView signIn(@PathVariable String providerId, NativeWebRequest request) {
    try {
        ConnectionFactory<?> connectionFactory = connectionFactoryLocator.getConnectionFactory(providerId);
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        return redirectAbsolute(connectSupport.buildOAuthUrl(connectionFactory, request, parameters));
    } catch (Exception e) {
        log.error("Exception while building authorization URL: ", e);
        return redirectOnError(providerId);
    }
}
项目:aces-listener-bitcoin    文件:BitcoinService.java   
private HttpEntity<String> getRequestEntity(String method, List<Object> params) {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Content-Type", "text/plain");

    BitcoinRpcRequest bitcoinRpcRequest = bitcoinRpcRequestFactory.create(method, params);
    String body = objectMapper.writeValueAsString(bitcoinRpcRequest);

    return new HttpEntity<>(body, headers);
}
项目:xm-uaa    文件:ConnectSupport.java   
private String buildOAuth2Url(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request,
    MultiValueMap<String, String> additionalParameters) {
    OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
    String defaultScope = connectionFactory.getScope();
    OAuth2Parameters parameters = getOAuth2Parameters(request, defaultScope, additionalParameters);
    String state = connectionFactory.generateState();
    parameters.add("state", state);
    sessionStrategy.setAttribute(request, OAUTH2_STATE_ATTRIBUTE, state);
    return oauthOperations.buildAuthenticateUrl(parameters);
}
项目:OAuth-2.0-Cookbook    文件:AuthorizationCodeConfiguration.java   
public MultiValueMap<String, String> getBody(String authorizationCode) {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("grant_type", "authorization_code");
    formData.add("scope", "read_profile");
    formData.add("code", authorizationCode);
    formData.add("redirect_uri", "http://localhost:9000/callback");
    return formData;
}
项目:artifactory-resource    文件:MavenBuildModulesGenerator.java   
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;
}
项目:lams    文件:FormHttpMessageConverter.java   
private void writeParts(OutputStream os, MultiValueMap<String, Object> parts, byte[] boundary) throws IOException {
    for (Map.Entry<String, List<Object>> entry : parts.entrySet()) {
        String name = entry.getKey();
        for (Object part : entry.getValue()) {
            if (part != null) {
                writeBoundary(boundary, os);
                HttpEntity<?> entity = getEntity(part);
                writePart(name, entity, os);
                writeNewLine(os);
            }
        }
    }
}
项目:artifactory-resource    文件:InHandler.java   
private void download(ArtifactoryServer artifactoryServer,
        MultiValueMap<String, DeployedArtifact> artifactsByRepo, File destination) {
    artifactsByRepo.forEach((repo, artifacts) -> artifacts.forEach((artifact) -> {
        console.log("Downloading {} from {}", artifact.getPath(), repo);
        artifactoryServer.repository(repo).download(artifact, destination);
    }));
}
项目:logistimo-web-service    文件:FileUploadServlet.java   
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (!isMultipart) {
    return;
  }
  try {
    MultipartHttpServletRequest
        multiRequest =
        new CommonsMultipartResolver().resolveMultipart(request);
    MultiValueMap<String, MultipartFile> fileMap = multiRequest.getMultiFileMap();
    BlobstoreService blobstoreService = AppFactory.get().getBlobstoreService();
    Map<String, String> names = new HashMap<>(1);
    for (String fieldName : fileMap.keySet()) {
      MultipartFile file = fileMap.getFirst(fieldName);
      String fileName = file.getOriginalFilename();
      String contentType = file.getContentType();
      long sizeInBytes = file.getSize();
      String
          blobKey =
          blobstoreService.store(fileName, contentType, sizeInBytes, file.getInputStream());
      names.put(fieldName, blobKey);

    }
    request.getSession().setAttribute("blobs", names);
    RequestDispatcher
        dispatcher =
        getServletContext().getRequestDispatcher(request.getParameter("ru"));
    dispatcher.forward(multiRequest, response);
  } catch (Exception ex) {
    _logger.severe("Upload failed", ex);
  }
}
项目:microservices-sample-project    文件:AsyncResponseEntity.java   
public AsyncResponseEntity(
        Observable<T> observable
        , MultiValueMap<String
        , String> headers,
        HttpStatus status
        ) {
    this.observable = observable;
    this.headers = headers;
    this.status = status;
}
项目:lams    文件:FormHttpMessageConverter.java   
private void writeMultipart(MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage)
        throws IOException {
    byte[] boundary = generateMultipartBoundary();

    Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));
    MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
    outputMessage.getHeaders().setContentType(contentType);

    writeParts(outputMessage.getBody(), parts, boundary);
    writeEnd(boundary, outputMessage.getBody());
}
项目:csap-core    文件:CsapEventClient.java   
public void testingOnlyPostEvent ( MultiValueMap<String, String> formParams )
        throws Exception {

    // Support for LT. do not blow through queue
    if ( numSent++ % 1000 == 0 ) {
        logger.info( "Messages sent: " + numSent + " backlog: " + eventPostQueue.size() );
    }

    ThreadPoolExecutor pool = (ThreadPoolExecutor) eventPostPool;
    if ( eventPostQueue.size() > 100 && pool.getCorePoolSize() == 1 ) {
        pool.setCorePoolSize( 6 );
        pool.setMaximumPoolSize( 6 );
    }

    // blocking for testing
    logger.info( "eventPostPool terminated: {}", eventPostPool.isTerminated() );
    Future<String> futureResult = eventPostPool.submit( new EventPostRunnable( lifecycleSettings.getEventUrl(),
        formParams, "test", "test" ) );

    // Non Blocking to test event caching/pooling
    // futureResult.get() ;
}
项目:xitikit-blue    文件:AzureGraphApiClient.java   
public AccessToken getAccessToken(){

        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        String clientId = graphApiClientProperties.getClientId();
        String clientSecret = graphApiClientProperties.getClientSecret();
        String baseUrl = graphApiClientProperties.getBaseUrl();

        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);
        params.add("resource", baseUrl);
        params.add("grant_type", "client_credentials");
        params.add("scope", "Directory.AccessAsUser.All");

        return restTemplate.postForObject(accessTokenUrl(), params, AccessToken.class);
    }
项目:artifactory-resource    文件:MavenMetadataGenerator.java   
private void generate(Directory root, File pomFile) {
    String name = StringUtils.getFilename(pomFile.getName());
    String extension = StringUtils.getFilenameExtension(pomFile.getName());
    String prefix = name.substring(0, name.length() - extension.length() - 1);
    File[] files = pomFile.getParentFile().listFiles((f) -> include(f, prefix));
    MultiValueMap<File, MavenCoordinates> coordinates = new LinkedMultiValueMap<>();
    for (File file : files) {
        String rootPath = StringUtils.cleanPath(root.getFile().getPath());
        String relativePath = StringUtils.cleanPath(file.getPath())
                .substring(rootPath.length() + 1);
        coordinates.add(file.getParentFile(),
                MavenCoordinates.fromPath(relativePath));
    }
    coordinates.forEach(this::writeMetadata);
}
项目:spring-security-oauth2-boot    文件:OAuth2AutoConfigurationTests.java   
private MultiValueMap<String, Object> getBody() {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.set("grant_type", "password");
    body.set("username", "foo");
    body.set("password", "bar");
    body.set("scope", "read");
    return body;
}
项目:spring-boot-autoconfigure    文件:OnBeansCondition.java   
protected void collect(MultiValueMap<String, Object> attributes, String key, List<String> destination) {
    List<?> values = attributes.get(key);
    if (values != null) {
        for (Object value : values) {
            if (value instanceof String[]) {
                Collections.addAll(destination, (String[]) value);
            } else {
                destination.add((String) value);
            }
        }
    }
}
项目:MTC_Labrat    文件:CustomSocialUsersConnectionRepositoryIntTest.java   
@Test
@SuppressWarnings("unchecked")
public void findAllConnections() {
    connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
    insertTwitterConnection();
    insertFacebookConnection();
    MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
    assertEquals(2, connections.size());
    Connection<TestFacebookApi> facebook = (Connection<TestFacebookApi>) connections.getFirst("facebook");
    assertFacebookConnection(facebook);
    Connection<TestTwitterApi> twitter = (Connection<TestTwitterApi>) connections.getFirst("twitter");
    assertTwitterConnection(twitter);
}
项目:MTC_Labrat    文件:CustomSocialUsersConnectionRepositoryIntTest.java   
@Test
public void findAllConnectionsMultipleConnectionResults() {
    connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
    insertTwitterConnection();
    insertFacebookConnection();
    insertFacebookConnection2();
    MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
    assertEquals(2, connections.size());
    assertEquals(2, connections.get("facebook").size());
    assertEquals(1, connections.get("twitter").size());
}