Search in sources :

Example 61 with HttpEntity

use of org.springframework.http.HttpEntity in project cas by apereo.

the class RestGoogleAuthenticatorTokenCredentialRepository method save.

@Override
public void save(final String userName, final String secretKey, final int validationCode, final List<Integer> scratchCodes) {
    final MultifactorAuthenticationProperties.GAuth.Rest rest = gauth.getRest();
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.put("username", Arrays.asList(userName));
    headers.put("validationCode", Arrays.asList(String.valueOf(validationCode)));
    headers.put("secretKey", Arrays.asList(secretKey));
    headers.put("scratchCodes", scratchCodes.stream().map(String::valueOf).collect(Collectors.toList()));
    final HttpEntity<String> entity = new HttpEntity<>(headers);
    final ResponseEntity<Boolean> result = restTemplate.exchange(rest.getEndpointUrl(), HttpMethod.POST, entity, Boolean.class);
    if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
        LOGGER.debug("Posted google authenticator account successfully");
    }
    LOGGER.warn("Failed to save google authenticator account successfully");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity)

Example 62 with HttpEntity

use of org.springframework.http.HttpEntity in project cas by apereo.

the class RestGoogleAuthenticatorTokenCredentialRepository method getSecret.

@Override
public String getSecret(final String username) {
    final MultifactorAuthenticationProperties.GAuth.Rest rest = gauth.getRest();
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.put("username", Arrays.asList(username));
    final HttpEntity<String> entity = new HttpEntity<>(headers);
    final ResponseEntity<String> result = restTemplate.exchange(rest.getEndpointUrl(), HttpMethod.GET, entity, String.class);
    if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
        return result.getBody();
    }
    return null;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity)

Example 63 with HttpEntity

use of org.springframework.http.HttpEntity in project spring-boot-admin by codecentric.

the class HipchatNotifierTest method test_onApplicationEvent_resolve.

@Test
public void test_onApplicationEvent_resolve() {
    StatusInfo infoDown = StatusInfo.ofDown();
    StatusInfo infoUp = StatusInfo.ofUp();
    @SuppressWarnings("unchecked") ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor.forClass((Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class);
    when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class))).thenReturn(ResponseEntity.ok((Void) null));
    notifier.notify(new ClientApplicationStatusChangedEvent(Application.create("App").withId("-id-").withHealthUrl("http://health").build(), infoDown, infoUp));
    assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type", asList("application/json"));
    Map<String, Object> body = httpRequest.getValue().getBody();
    assertThat(body).containsEntry("color", "green");
    assertThat(body).containsEntry("message", "<strong>App</strong>/-id- is <strong>UP</strong>");
    assertThat(body).containsEntry("notify", Boolean.TRUE);
    assertThat(body).containsEntry("message_format", "html");
}
Also used : HttpEntity(org.springframework.http.HttpEntity) StatusInfo(de.codecentric.boot.admin.model.StatusInfo) ClientApplicationStatusChangedEvent(de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent) Test(org.junit.Test)

Example 64 with HttpEntity

use of org.springframework.http.HttpEntity in project zeppelin by apache.

the class BaseLivyInterprereter method callRestAPI.

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString()));
    } catch (RestClientException e) {
        // Exception happens when kerberos is enabled.
        if (e.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
            if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
                throw new SessionNotFoundException(cause.getResponseBodyAsString());
            }
        }
        throw new LivyException(e);
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(), response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException("No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) ResponseEntity(org.springframework.http.ResponseEntity) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException)

Example 65 with HttpEntity

use of org.springframework.http.HttpEntity in project spring-framework by spring-projects.

the class FormHttpMessageConverterTests method writeMultipartOrder.

// SPR-13309
@Test
public void writeMultipartOrder() throws Exception {
    MyBean myBean = new MyBean();
    myBean.setString("foo");
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("part1", myBean);
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(MediaType.TEXT_XML);
    HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders);
    parts.add("part2", entity);
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.setMultipartCharset(StandardCharsets.UTF_8);
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertNotNull("No boundary found", contentType.getParameter("boundary"));
    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertEquals(2, items.size());
    FileItem item = items.get(0);
    assertTrue(item.isFormField());
    assertEquals("part1", item.getFieldName());
    assertEquals("{\"string\":\"foo\"}", item.getString());
    item = items.get(1);
    assertTrue(item.isFormField());
    assertEquals("part2", item.getFieldName());
    // With developer builds we get: <MyBean><string>foo</string></MyBean>
    // But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
    // So... we make a compromise:
    assertThat(item.getString(), allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MockHttpOutputMessage(org.springframework.http.MockHttpOutputMessage) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) MediaType(org.springframework.http.MediaType) RequestContext(org.apache.commons.fileupload.RequestContext) FileUpload(org.apache.commons.fileupload.FileUpload) Test(org.junit.Test)

Aggregations

HttpEntity (org.springframework.http.HttpEntity)104 HttpHeaders (org.springframework.http.HttpHeaders)81 Test (org.junit.Test)46 RestTemplate (org.springframework.web.client.RestTemplate)17 URI (java.net.URI)15 ArrayList (java.util.ArrayList)13 ResponseEntity (org.springframework.http.ResponseEntity)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Map (java.util.Map)11 MediaType (org.springframework.http.MediaType)11 HashMap (java.util.HashMap)10 List (java.util.List)10 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)10 MultiValueMap (org.springframework.util.MultiValueMap)9 ByteArrayInputStream (java.io.ByteArrayInputStream)7 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)7 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)7 HttpStatus (org.springframework.http.HttpStatus)6 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)6 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)6