Java 类org.springframework.http.HttpMethod 实例源码

项目:esup-sgc    文件:ApiCrousService.java   
public void postOrUpdateRightHolder(String eppn) {  
    if(enable) {
        String url = webUrl + "/rightholders/" + eppn;
        HttpHeaders headers = this.getAuthHeaders();    
        HttpEntity entity = new HttpEntity(headers);        
        try {
            ResponseEntity<RightHolder> response = restTemplate.exchange(url, HttpMethod.GET, entity, RightHolder.class);
            log.info("Getting RightHolder for " + eppn +" : " + response.toString());
            RightHolder oldRightHolder = response.getBody();
            RightHolder newRightHolder = this.computeEsupSgcRightHolder(eppn);
            if(!newRightHolder.fieldWoDueDateEquals(oldRightHolder) || mustUpdateDueDateCrous(oldRightHolder, eppn)) {
                updateRightHolder(eppn);
            } 
        } catch(HttpClientErrorException clientEx) {
            if(HttpStatus.NOT_FOUND.equals(clientEx.getStatusCode())) {
                postRightHolder(eppn);
                return ;
            } else {
                throw clientEx;
            }
        }
    }
}
项目:second-opinion-api    文件:CaseControllerIT.java   
@Test
public void should_return_cases_as_empty_list_if_patient_not_exist() {
    //Given
    long patientId = 123123;

    //When
    ResponseEntity<List<Case>> response = testRestTemplate.
            withBasicAuth("1","1").
            exchange("/v1/cases?patientId="+patientId,
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<List<Case>>() {
                    });
    List<Case> cases = response.getBody();

    //Then
    assertThat(cases).isNotNull();
    assertThat(cases).isEmpty();
}
项目:bxbot-ui-server    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()

            // no need to create session as JWT auth is stateless and per request
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            .antMatchers("/auth").permitAll()                   // allow anyone to try and authenticate
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // allow CORS pre-flighting
            .anyRequest().authenticated();                      // lock down everything else

    // Add our custom JWT security filter before Spring Security's Username/Password filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // Disable page caching in the browser
    httpSecurity.headers().cacheControl().disable();
}
项目:spring-webflux-client    文件:DefaultRequestExecutorTest.java   
@Test
public void execute_withHeaders() {
    Request request = new MockRequest("http://example.ca", HttpMethod.GET);
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);

    requestExecutor.execute(request);
    ClientRequest clientRequest = verifyExchange();
    assertThat(clientRequest.url())
            .isEqualTo(URI.create("http://example.ca"));
    assertThat(clientRequest.method())
            .isEqualTo(HttpMethod.GET);
    assertThat(clientRequest.headers().getFirst(HttpHeaders.ACCEPT))
            .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
    assertThat(clientRequest.headers().getFirst(HttpHeaders.CONTENT_TYPE))
            .isEqualTo(MediaType.APPLICATION_XML_VALUE);
}
项目:OpenLRW    文件:AdminUserProcessingFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException,
    ServletException {
  if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) {
    if (logger.isDebugEnabled()) {
      logger.debug("Authentication method not supported. Request method: " + request.getMethod());
    }
    throw new AuthMethodNotSupportedException("Authentication method not supported");
  }

  LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);

  if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
    throw new AuthenticationServiceException("Username or Password not provided");
  }

  AdminUserAuthenticationToken token = new AdminUserAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

  return this.getAuthenticationManager().authenticate(token);
}
项目:keti    文件:ZoneEnforcementStepsDefinitions.java   
@When("^client_two does a DELETE on (.*?) with (.*?) in zone (.*?)$")
public void client_two_does_a_DELETE_on_api_with_identifier_in_test_zone_dev(final String api,
        final String identifier, final String zone) throws Throwable {

    OAuth2RestTemplate acsTemplate = this.acsZone2Template;
    String zoneName = getZoneName(zone);

    HttpHeaders zoneHeaders = ACSTestUtil.httpHeaders();
    zoneHeaders.set(PolicyHelper.PREDIX_ZONE_ID, zoneName);

    String encodedIdentifier = URLEncoder.encode(identifier, "UTF-8");
    URI uri = URI.create(this.acsUrl + ACS_VERSION + "/" + api + "/" + encodedIdentifier);
    try {
        this.status = acsTemplate
                .exchange(uri, HttpMethod.DELETE, new HttpEntity<>(zoneHeaders), ResponseEntity.class)
                .getStatusCode().value();
    } catch (HttpClientErrorException e) {
        Assert.fail("Unable to DELETE identifier: " + identifier + " for api: " + api);
    }
}
项目:tdd-pingpong    文件:SubmissionSenderServiceTest.java   
@Test
public void testSubmit()
    throws ExecutionException, InterruptedException {
  String packageData = "this_is_a_package";

  // This test is *very* limited as Spring doesn't have any easy way to check
  // requests with multipart form data...
  server.expect(requestTo("/tasks.json"))
      .andExpect(method(HttpMethod.POST))
      .andExpect(content().contentTypeCompatibleWith(MediaType.MULTIPART_FORM_DATA))
      .andRespond(withSuccess("{\"status\":\"ok\"}", MediaType.APPLICATION_JSON));

  UUID submissionId = UUID.randomUUID();

  CompletableFuture<SubmissionResponse> responseFuture = sender
      .sendSubmission(submissionId, packageData.getBytes());
  SubmissionResponse response = responseFuture.get();

  assertTrue(response.getStatus().equals(SubmissionResponse.OK));
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:CommentHelper.java   
@HystrixCommand(fallbackMethod = "defaultComments")
public List<Comment> getComments(Image image, String sessionId) {

    ResponseEntity<List<Comment>> results = restTemplate.exchange(
        "http://COMMENTS/comments/{imageId}",
        HttpMethod.GET,
        new HttpEntity<>(new HttpHeaders() {{
            String credentials = imagesConfiguration.getCommentsUser() + ":" +
                imagesConfiguration.getCommentsPassword();
            String token = new String(Base64Utils.encode(credentials.getBytes()));
            set(AUTHORIZATION, "Basic " + token);
            set("SESSION", sessionId);
        }}),
        new ParameterizedTypeReference<List<Comment>>() {},
        image.getId());
    return results.getBody();
}
项目:open-kilda    文件:FlowsIntegrationService.java   
/**
 * Gets the topology flows.
 *
 * @return the topology flows
 */
public List<TopologyFlowsResponse> getTopologyFlows() {
    List<TopologyFlowsResponse> flowPathList = new ArrayList<TopologyFlowsResponse>();
    try {
        HttpResponse response =
                restClientManager.invoke(applicationProperties.getTopologyFlows(),
                        HttpMethod.GET, "", "", util.kildaAuthHeader());
        if (RestClientManager.isValidResponse(response)) {

            flowPathList =
                    restClientManager.getResponseList(response, TopologyFlowsResponse.class);
        }

    } catch (Exception exception) {
        log.error("Exception in getTopologyFlows " + exception.getMessage());
    }
    return flowPathList;
}
项目:esup-sgc    文件:ApiCrousService.java   
public synchronized void authenticate() {
    if(enable) {
        String url = webUrl + "/authenticate";
        HttpHeaders headers = getJsonHeaders();
        Map<String, String> body = new HashMap<String, String>();
        body.put("login", login);
        body.put("password", password);
        HttpEntity entity = new HttpEntity(body, headers);  
        HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        HttpHeaders httpHeadersResponse = response.getHeaders();
        log.info("Headers response for crous api authentication : " + httpHeadersResponse);
        List<String> authorizations = httpHeadersResponse.get("authorization");
        if(authorizations!=null && !authorizations.isEmpty()) {
            authToken = authorizations.get(0);
            log.info("Auth Token of Crous API is renew : " + authToken);
        } else {
            throw new SgcRuntimeException("No authorization header when crous authentication : " + httpHeadersResponse, null);
        }
    }
}
项目:second-opinion-api    文件:CaseControllerIT.java   
@Test
public void should_put_return_406_when_case_not_have_an_id() throws Exception {
    // given
    Case caseEntity = new Case();
    caseEntity.setIllnessStartDate(LocalDate.MAX);
    caseEntity.setNickname("R2-D2");
    caseEntity.setSymptoms("Lorem ipsum dolor sit amet");
    caseEntity.setNote("superiz");
    Case persistedCase = caseRepository.save(caseEntity);
    Long caseId = persistedCase.getId();

    Case updatedCaseOnClientSide = persistedCase;
    updatedCaseOnClientSide.setId(null);

    // when
    ResponseEntity<Void> putResponse = testRestTemplate
            .withBasicAuth("1", "1")
            .exchange("/v1/cases/" + caseId,
                    HttpMethod.PUT,
                    new HttpEntity<>(updatedCaseOnClientSide),
                    Void.class);

    // then
    assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
}
项目:monarch    文件:ClientHttpRequest.java   
/**
 * Gets the HTTP method indicating the operation to perform on the resource identified in the
 * client's HTTP request. This method converts GemFire's HttpMethod enumerated value from the Link
 * into a corresponding Spring HttpMethod enumerated value.
 * <p/>
 * 
 * @return a Spring HttpMethod enumerated value indicating the operation to perform on the
 *         resource identified in the client's HTTP request.
 * @see org.apache.geode.management.internal.web.http.HttpMethod
 * @see org.apache.geode.management.internal.web.domain.Link#getMethod()
 * @see org.springframework.http.HttpMethod
 * @see org.springframework.http.HttpRequest#getMethod()
 */
@Override
public HttpMethod getMethod() {
  switch (getLink().getMethod()) {
    case DELETE:
      return HttpMethod.DELETE;
    case HEAD:
      return HttpMethod.HEAD;
    case OPTIONS:
      return HttpMethod.OPTIONS;
    case POST:
      return HttpMethod.POST;
    case PUT:
      return HttpMethod.PUT;
    case TRACE:
      return HttpMethod.TRACE;
    case GET:
    default:
      return HttpMethod.GET;
  }
}
项目:bxbot-ui-server    文件:TestEmailAlertsConfigRepository.java   
@Test
public void whenGetCalledThenExpectEmailAlertsConfigToBeReturned() throws Exception {

    final String emailAlertsConfigInJson = objectMapper.writeValueAsString(someEmailAlertsConfig);

    mockServer.expect(requestTo(REST_ENDPOINT_BASE_URL + EMAIL_ALERTS_RESOURCE_PATH))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(emailAlertsConfigInJson, MediaType.APPLICATION_JSON));

    final EmailAlertsConfig emailAlertsConfig = restClient.get(botConfig);
    assertThat(emailAlertsConfig.getId()).isEqualTo(BOT_ID);
    assertThat(emailAlertsConfig.isEnabled()).isEqualTo(ENABLED);
    assertThat(emailAlertsConfig.getSmtpConfig().getAccountUsername()).isEqualTo(ACCOUNT_USERNAME);
    assertThat(emailAlertsConfig.getSmtpConfig().getAccountPassword()).isEqualTo(ACCOUNT_PASSWORD);
    assertThat(emailAlertsConfig.getSmtpConfig().getHost()).isEqualTo(HOST);
    assertThat(emailAlertsConfig.getSmtpConfig().getTlsPort()).isEqualTo(TLS_PORT);
    assertThat(emailAlertsConfig.getSmtpConfig().getFromAddress()).isEqualTo(FROM_ADDRESS);
    assertThat(emailAlertsConfig.getSmtpConfig().getToAddress()).isEqualTo(TO_ADDRESS);

    mockServer.verify();
}
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:ResourceServerOAuth2Config.java   
@Override
 public void configure(final HttpSecurity http) throws Exception {
    http
        .requestMatchers().antMatchers("/doctor/**", "/rx/**", "/account/**")
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.GET,"/doctor/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST,"/doctor/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('write')")
.antMatchers(HttpMethod.GET,"/rx/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST,"/rx/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('write')")   
.antMatchers("/account/**").permitAll()
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
.and()
.csrf().disable();

 }
项目:bxbot-ui-server    文件:TestEngineConfigRepository.java   
@Test
public void whenSaveCalledThenExpectRepositoryToSaveItAndReturnSavedEngineConfig() throws Exception {

    final String engineConfigInJson = objectMapper.writeValueAsString(someEngineConfig);

    mockServer.expect(requestTo(REST_ENDPOINT_BASE_URL + ENGINE_RESOURCE_PATH))
            .andExpect(method(HttpMethod.PUT))
            .andRespond(withSuccess(engineConfigInJson, MediaType.APPLICATION_JSON));

    final EngineConfig engineConfig = restClient.save(botConfig, someEngineConfig);
    assertThat(engineConfig.getId()).isEqualTo(BOT_ID);
    assertThat(engineConfig.getBotName()).isEqualTo(BOT_ALIAS);
    assertThat(engineConfig.getTradeCycleInterval()).isEqualTo(ENGINE_TRADE_CYCLE_INTERVAL);
    assertThat(engineConfig.getEmergencyStopCurrency()).isEqualTo(ENGINE_EMERGENCY_STOP_CURRENCY);
    assertThat(engineConfig.getEmergencyStopBalance()).isEqualTo(ENGINE_EMERGENCY_STOP_BALANCE);

    mockServer.verify();
}
项目:bxbot-ui-server    文件:TestEmailAlertsConfigRepository.java   
@Test
public void whenSaveCalledThenExpectRepositoryToSaveItAndReturnSavedEmailAlertsConfig() throws Exception {

    final String emailAlertsConfigInJson = objectMapper.writeValueAsString(someEmailAlertsConfig);

    mockServer.expect(requestTo(REST_ENDPOINT_BASE_URL + EMAIL_ALERTS_RESOURCE_PATH))
            .andExpect(method(HttpMethod.PUT))
            .andRespond(withSuccess(emailAlertsConfigInJson, MediaType.APPLICATION_JSON));

    final EmailAlertsConfig emailAlertsConfig = restClient.save(botConfig, someEmailAlertsConfig);
    assertThat(emailAlertsConfig.getId()).isEqualTo(BOT_ID);
    assertThat(emailAlertsConfig.isEnabled()).isEqualTo(ENABLED);
    assertThat(emailAlertsConfig.getSmtpConfig().getAccountUsername()).isEqualTo(ACCOUNT_USERNAME);
    assertThat(emailAlertsConfig.getSmtpConfig().getAccountPassword()).isEqualTo(ACCOUNT_PASSWORD);
    assertThat(emailAlertsConfig.getSmtpConfig().getHost()).isEqualTo(HOST);
    assertThat(emailAlertsConfig.getSmtpConfig().getTlsPort()).isEqualTo(TLS_PORT);
    assertThat(emailAlertsConfig.getSmtpConfig().getFromAddress()).isEqualTo(FROM_ADDRESS);
    assertThat(emailAlertsConfig.getSmtpConfig().getToAddress()).isEqualTo(TO_ADDRESS);

    mockServer.verify();
}
项目:MicroServiceDemo    文件:RestTemplate.java   
@Override
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
                          @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
    String from = name;
    String to = url.
            toString().
            replace("http://", "").
            replace("http:// www.", "").
            replace("www.", "").
            replace("/", "%20").
            toLowerCase();

    System.out.println(from);
    System.out.println(to);

    try {
        restTemplate.postForObject("http://trace-callback-service/" + from + "/" + to, null, Object.class);
    } catch (Exception exception) {
    }

    return super.doExecute(url, method, requestCallback, responseExtractor);
}
项目:alfresco-remote-api    文件:SerializeTests.java   
@Test
public void testPagedCollection() throws IOException
{
    ResourceWithMetadata relationResource = locator.locateRelationResource(api,"sheep", "baaahh", HttpMethod.GET);
    assertNotNull(relationResource);
    RelationshipResourceAction.Read<?> getter = (RelationshipResourceAction.Read<?>) relationResource.getResource();
    CollectionWithPagingInfo<?> resources = getter.readAll("123",Params.valueOf("", null, null));
    assertNotNull(resources);
    assertTrue(resources.getTotalItems().intValue() == 3);
    assertFalse(resources.hasMoreItems());
    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api,null, Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List with pagination", StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":3,"));

    resources = getter.readAll("123",ParamsExtender.valueOf(Paging.valueOf(0, 1),"123"));
    assertTrue(resources.getCollection().size() == 1);
    assertTrue(resources.hasMoreItems());
    out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api,null, Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List with pagination", StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":1,"));

}
项目:apollo-custom    文件:RetryableRestTemplate.java   
private <T> T doExecute(HttpMethod method, ServiceDTO service, String path, Object request,
                        Class<T> responseType,
                        Object... uriVariables) {
  T result = null;
  switch (method) {
    case GET:
      result = restTemplate.getForObject(parseHost(service) + path, responseType, uriVariables);
      break;
    case POST:
      result =
          restTemplate.postForEntity(parseHost(service) + path, request, responseType, uriVariables).getBody();
      break;
    case PUT:
      restTemplate.put(parseHost(service) + path, request, uriVariables);
      break;
    case DELETE:
      restTemplate.delete(parseHost(service) + path, uriVariables);
      break;
    default:
      throw new UnsupportedOperationException(String.format("unsupported http method(method=%s)", method));
  }
  return result;
}
项目:jwala    文件:WebServerStateSetterWorkerTest.java   
@Test
public void testPingWebServerTwice() throws Exception {
    when(mockClientHttpResponse.getStatusCode()).thenReturn(HttpStatus.OK);
    when(mockClientHttpRequest.execute()).thenReturn(mockClientHttpResponse);
    when(mockHttpRequestFactory.createRequest(any(URI.class), eq(HttpMethod.GET))).thenReturn(mockClientHttpRequest);
    final Identifier<WebServer> id = new Identifier<>(1L);
    when(mockWebServer.getId()).thenReturn(id);
    webServerStateSetterWorker.pingWebServer(mockWebServer);
    verify(mockWebServerService).updateState(any(Identifier.class), eq(WebServerReachableState.WS_REACHABLE),
            eq(StringUtils.EMPTY));
    verify(mockMessagingService).send(any(WebServerState.class));


    reset(mockWebServerService);
    reset(mockMessagingService);
    webServerStateSetterWorker.pingWebServer(mockWebServer);
    verify(mockWebServerService, never()).updateState(any(Identifier.class), eq(WebServerReachableState.WS_REACHABLE),
            eq(StringUtils.EMPTY));
    verify(mockMessagingService, never()).send(any(WebServerState.class));
}
项目:second-opinion-api    文件:MedicineControllerIT.java   
@Test
public void should_delete_return_404_for_non_existing_medicine() throws Exception {
    //given

    // when
    ResponseEntity<Void> deleteResponse = testRestTemplate
            .withBasicAuth("1", "1")
            .exchange(url + "/1234321",
                    HttpMethod.DELETE,
                    HttpEntity.EMPTY,
                    Void.class);

    // then
    assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);

}
项目:second-opinion-api    文件:TreatmentControllerIT.java   
@Test
public void should_put_return_404_for_nonexisting_treatment() throws Exception {

    // given
    ResponseEntity<Void> response = getCreateTreatmentResponse();
    URI location = response.getHeaders().getLocation();
    String id = RestHelper.extractIdStringFromURI(location);

    Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id));

    // when
    ResponseEntity<Void> putResponse = testRestTemplate
            .withBasicAuth("1", "1")
            .exchange("/v1/treatments/1938412",
                    HttpMethod.PUT,
                    new HttpEntity<>(savedTreatment),
                    Void.class);

    // then
    assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
项目:incubator-servicecomb-java-chassis    文件:TestRestTemplateWrapper.java   
@Test
public void executeWithUnderlyingRestTemplate() {
  RequestCallback requestCallback = clientHttpRequest -> {
  };
  ResponseExtractor<ResponseEntity<String>> responseExtractor = clientHttpResponse -> responseEntity;

  ResponseEntity<String> actual;

  for (HttpMethod method : httpMethods) {
    when(underlying.execute(url, method, requestCallback, responseExtractor, param1, param2))
        .thenReturn(responseEntity);
    actual = wrapper.execute(url, method, requestCallback, responseExtractor, param1, param2);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(url, method, requestCallback, responseExtractor, param1, param2);

    when(underlying.execute(url, method, requestCallback, responseExtractor, paramsMap)).thenReturn(responseEntity);
    actual = wrapper.execute(url, method, requestCallback, responseExtractor, paramsMap);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(url, method, requestCallback, responseExtractor, paramsMap);

    when(underlying.execute(uri, method, requestCallback, responseExtractor)).thenReturn(responseEntity);
    actual = wrapper.execute(uri, method, requestCallback, responseExtractor);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(uri, method, requestCallback, responseExtractor);
  }
}
项目:MicroServiceDemo    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // 使用JWT不需要csrf
            .csrf().disable()
            // 基于token不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/info").permitAll()
            // login route is only publicly available for POST requests
            .antMatchers(HttpMethod.POST, "/register").permitAll()
            .antMatchers(HttpMethod.GET, "/login").permitAll()
            .antMatchers(HttpMethod.GET, "/refresh").permitAll()
            .anyRequest().authenticated()
            .and()
            // And filter other requests to check the presence of JWT in header
            // 集成JWT和Spring Security
            // 如果客户端请求体中包含token,在检查token之后才放行
            .addFilterBefore(authenticationFilterBean(),
                    UsernamePasswordAuthenticationFilter.class);
    // 禁用缓存
    http.headers().cacheControl();
}
项目:lams    文件:AsyncRestTemplate.java   
@Override
public <T> ListenableFuture<ResponseEntity<T>> postForEntity(String url, HttpEntity<?> request,
        Class<T> responseType, Object... uriVariables) throws RestClientException {
    AsyncRequestCallback requestCallback = httpEntityCallback(request, responseType);
    ResponseExtractor<ResponseEntity<T>> responseExtractor =
            responseEntityExtractor(responseType);
    return execute(url, HttpMethod.POST, requestCallback, responseExtractor,
            uriVariables);
}
项目:spring-cloud-skipper    文件:DefaultSkipperClient.java   
@Override
public String manifest(String releaseName) {
    ParameterizedTypeReference<Resource<Manifest>> typeReference =
            new ParameterizedTypeReference<Resource<Manifest>>() {  };
    Map<String, String> uriVariables = new HashMap<String, String>();
    uriVariables.put("releaseName", releaseName);
    ResponseEntity<Resource<Manifest>> resourceResponseEntity =
            restTemplate.exchange(baseUri + "/release/manifest/{releaseName}",
                    HttpMethod.GET,
                    null,
                    typeReference,
                    uriVariables);
    return resourceResponseEntity.getBody().getContent().getData();
}
项目:apollo-custom    文件:NotificationControllerV2IntegrationTest.java   
@Test
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWithMultipleNamespacesAndIncorrectCase() throws Exception {
  AtomicBoolean stop = new AtomicBoolean();
  String key = assembleKey(someAppId, someCluster, somePublicNamespace);
  periodicSendMessage(executorService, key, stop);

  String someDefaultNamespaceWithIncorrectCase = defaultNamespace.toUpperCase();
  String somePublicNamespaceWithIncorrectCase = somePublicNamespace.toUpperCase();

  ResponseEntity<List<ApolloConfigNotification>> result = restTemplate.exchange(
      "{baseurl}/notifications/v2?appId={appId}&cluster={clusterName}&notifications={notifications}",
      HttpMethod.GET, null, typeReference,
      getHostUrl(), someAppId, someCluster,
      transformApolloConfigNotificationsToString(defaultNamespace + ".properties",
          ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, someDefaultNamespaceWithIncorrectCase,
          ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, somePublicNamespaceWithIncorrectCase,
          ConfigConsts.NOTIFICATION_ID_PLACEHOLDER));

  stop.set(true);

  List<ApolloConfigNotification> notifications = result.getBody();
  assertEquals(HttpStatus.OK, result.getStatusCode());
  assertEquals(1, notifications.size());
  assertEquals(somePublicNamespaceWithIncorrectCase, notifications.get(0).getNamespaceName());
  assertNotEquals(0, notifications.get(0).getNotificationId());

  ApolloNotificationMessages messages = result.getBody().get(0).getMessages();
  assertEquals(1, messages.getDetails().size());
  assertTrue(messages.has(key));
  assertNotEquals(ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, messages.get(key).longValue());
}
项目:spring-cloud-samples    文件:CoordinatorManager.java   
@Retryable(value = { TccCoordinatorException.class }, maxAttempts = 5, backoff = @Backoff(value = 0))
public void retryConfirm(Participant participant) {
    final ResponseEntity<String> response = restTemplate.exchange(participant.getUri(), HttpMethod.PUT,
            REQUEST_ENTITY, String.class);
    count++;
    if (count < 4 || response.getStatusCode() != HttpStatus.NO_CONTENT) {
        throw new TccCoordinatorException("事务处理失败");
    }
    count = 0;
}
项目:lams    文件:RestTemplate.java   
@Override
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
        ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException {

    Type type = responseType.getType();
    RequestCallback requestCallback = httpEntityCallback(requestEntity, type);
    ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
    return execute(url, method, requestCallback, responseExtractor, uriVariables);
}
项目:alfresco-remote-api    文件:ResourceLocatorTests.java   
@Test(expected=org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException.class)
public void testLocateResource()
{
    Map<String, String> templateVars = new HashMap<String, String>();
    templateVars.put(ResourceLocator.COLLECTION_RESOURCE, "sheep");
    ResourceWithMetadata collResource = locator.locateResource(api, templateVars, HttpMethod.GET);
    assertNotNull(collResource);
    assertNotNull(collResource.getMetaData().getOperation(HttpMethod.GET));

    collResource = locator.locateResource(api, templateVars, HttpMethod.POST);
    assertNotNull(collResource);
    assertNotNull(collResource.getMetaData().getOperation(HttpMethod.POST));

    templateVars.put(ResourceLocator.ENTITY_ID, "farmersUniqueId");
    ResourceWithMetadata entityResource = locator.locateResource(api,templateVars, HttpMethod.GET);
    assertNotNull(entityResource);
    assertNotNull(entityResource.getMetaData().getOperation(HttpMethod.GET));

    entityResource = locator.locateResource(api, templateVars, HttpMethod.PUT);
    assertNotNull(entityResource);
    assertNotNull(entityResource.getMetaData().getOperation(HttpMethod.PUT));

    templateVars.clear();
    templateVars.put(ResourceLocator.COLLECTION_RESOURCE, "sheepnoaction");
    collResource = locator.locateResource(api,templateVars, HttpMethod.GET);

}
项目:BreakfastServer    文件:OrgService.java   
@Override
public OrgInfoModel[] GetAvailiableOrgsByUser() {
    ParameterizedTypeReference<PmsResultModel<String>> typeRef = new ParameterizedTypeReference<PmsResultModel<String>>() { };
    PmsResultModel<String> result = pmsRestClient.GetClient().exchange(requestCallContext.GetUser().getUrl()+"/API/Configure/GetAvailiableOrgsByUser", HttpMethod.GET, null,typeRef).getBody();
    if (result.getCode() != 0) {
        throw new IllegalArgumentException(result.getMessage());
    }

    return JsonUtils.Deserialize(result.getContent(),OrgInfoModel[].class);
}
项目:bxbot-ui-server    文件:TestMarketConfigRepository.java   
@Test
public void whenSaveCalledAndRemoteCallFailsThenReturnNullMarket() throws Exception {

    mockServer.expect(requestTo(REST_ENDPOINT_BASE_URL + MARKETS_RESOURCE_PATH))
            .andExpect(method(HttpMethod.PUT))
            .andRespond(withServerError());

    final MarketConfig marketConfig = restClient.save(botConfig, unrecognizedMarketConfig());
    assertThat(marketConfig).isEqualTo(null);

    mockServer.verify();
}
项目:springboot-seed    文件:ResourceServerConfig.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/v2/**","/swagger**", "/druid/**").permitAll()
            .antMatchers(HttpMethod.GET, "/user/{id}").permitAll()
            .antMatchers("/user/password").authenticated()
            .antMatchers("/user/**").hasAuthority("admin")
            .anyRequest().permitAll();
}
项目:swordfish-service    文件:RestoreQueryGatewayRestController.java   
@GetMapping("/restore/snapshots/transfer/{projectId}/{transferId}")
public ResponseEntity<String> transferSnapshots(@PathVariable String projectId,
                                                @PathVariable String transferId) {
    ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {
    };

    return restTemplate.exchange(
            SERVICE + "/snapshots/transfer/{projectId}/{transferId}", HttpMethod.GET,
            null, reference, projectId, transferId);
}
项目:IPPR2016    文件:ProcessEngineCallerImpl.java   
@Async
public Future<ResponseEntity<ProcessStartedDTO>> startProcess(
    @RequestBody final ProcessStartDTO processStartDTO, final HttpHeaderUser headerUser)
    throws URISyntaxException {
  LOG.debug("Create request to start process instance");

  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("/processes/startProcess");

  final HttpHeaders header = headerUser.getHttpHeaders();
  return createRequest(uri, HttpMethod.POST, processStartDTO, ProcessStartedDTO.class, header);
}
项目:keti    文件:PrivilegeHelper.java   
public BaseResource[] listResources(final RestTemplate restTemplate, final String acsEndpoint,
        final HttpHeaders headers) {
    URI uri = URI.create(acsEndpoint + ACS_RESOURCE_API_PATH);
    ResponseEntity<BaseResource[]> response = restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(headers),
            BaseResource[].class);
    return response.getBody();
}
项目:keti    文件:AttributeConnectorConfigurationIT.java   
@Test(dataProvider = "requestUrlProvider")
public void testDeleteConnectorDeniedWithoutSufficientScope(final String endpointUrl) throws Exception {
    try {
        this.zone1ConnectorReadClient.exchange(this.acsUrl + V1 + endpointUrl, HttpMethod.DELETE,
                new HttpEntity<>(this.zone1Headers), String.class);
        Assert.fail("No exception thrown when deleting connector without sufficient scope.");
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.FORBIDDEN);
    }
}
项目:apollo-custom    文件:NotificationControllerV2IntegrationTest.java   
@Test(timeout = 5000L)
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWthMultipleNamespacesAndMultipleNamespacesChanged()
    throws Exception {
  String publicAppId = "somePublicAppId";
  String someDC = "someDC";

  AtomicBoolean stop = new AtomicBoolean();
  String key = assembleKey(publicAppId, someDC, somePublicNamespace);
  periodicSendMessage(executorService, key, stop);

  ResponseEntity<List<ApolloConfigNotification>> result = restTemplate.exchange(
      "{baseurl}/notifications/v2?appId={appId}&cluster={clusterName}&notifications={notifications}&dataCenter={dataCenter}",
      HttpMethod.GET, null, typeReference,
      getHostUrl(), someAppId, someCluster,
      transformApolloConfigNotificationsToString(defaultNamespace, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER,
          somePublicNamespace, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER),
      someDC);

  stop.set(true);

  List<ApolloConfigNotification> notifications = result.getBody();
  assertEquals(HttpStatus.OK, result.getStatusCode());
  assertEquals(1, notifications.size());
  assertEquals(somePublicNamespace, notifications.get(0).getNamespaceName());
  assertNotEquals(0, notifications.get(0).getNotificationId());

  ApolloNotificationMessages messages = result.getBody().get(0).getMessages();
  assertEquals(1, messages.getDetails().size());
  assertTrue(messages.has(key));
  assertNotEquals(ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, messages.get(key).longValue());
}
项目:lams    文件:RestTemplate.java   
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
        ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException {

    URI expanded = new UriTemplate(url).expand(urlVariables);
    return doExecute(expanded, method, requestCallback, responseExtractor);
}
项目:meparty    文件:RestApiProxyInvocationHandlerTest.java   
@Test
public void patchMapping_shouldExtract_HttpMethodPatch() throws NoSuchMethodException {
  Method method = ChildRestApi_Annotations.class.getMethod("patchMapping");

  RestApiProxyInvocationHandler handler = new RestApiProxyInvocationHandler();
  HttpMethod httpMethod = handler.extractMapping(method).getHttpMethod();

  assertEquals(httpMethod, HttpMethod.PATCH);
}