Search in sources :

Example 61 with HttpStatus

use of org.springframework.http.HttpStatus in project dhis2-core by dhis2.

the class DhisApiTokenAuthenticationEntryPoint method _commence.

public void _commence(HttpServletResponse response) {
    HttpStatus status = HttpStatus.UNAUTHORIZED;
    LinkedHashMap<String, String> parameters = new LinkedHashMap<>();
    if (this.realmName != null) {
        parameters.put("realm", this.realmName);
    }
    String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);
    response.addHeader("WWW-Authenticate", wwwAuthenticate);
    response.setStatus(status.value());
}
Also used : HttpStatus(org.springframework.http.HttpStatus) LinkedHashMap(java.util.LinkedHashMap)

Example 62 with HttpStatus

use of org.springframework.http.HttpStatus in project dhis2-core by dhis2.

the class WebClientUtils method getCreatedId.

private static String getCreatedId(HttpResponse response) {
    HttpStatus actual = response.status();
    if (actual == HttpStatus.CREATED) {
        JsonObject report = response.contentUnchecked().getObject("response");
        if (report.exists()) {
            return report.getString("uid").string();
        }
    }
    String location = response.location();
    return location == null ? null : location.substring(location.lastIndexOf('/') + 1);
}
Also used : HttpStatus(org.springframework.http.HttpStatus) JsonObject(org.hisp.dhis.jsontree.JsonObject)

Example 63 with HttpStatus

use of org.springframework.http.HttpStatus in project dhis2-core by dhis2.

the class SyncUtils method isRemoteServerAvailable.

/**
 * Checks the availability of remote server
 *
 * @param systemSettingManager Reference to SystemSettingManager
 * @param restTemplate Reference to RestTemplate
 * @return AvailabilityStatus that says whether the server is available or
 *         not
 */
public static AvailabilityStatus isRemoteServerAvailable(SystemSettingManager systemSettingManager, RestTemplate restTemplate) {
    if (!isRemoteServerConfigured(systemSettingManager)) {
        return new AvailabilityStatus(false, "Remote server is not configured", HttpStatus.BAD_GATEWAY);
    }
    String url = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_URL) + PING_PATH;
    String username = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_USERNAME);
    String password = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_PASSWORD);
    log.debug(String.format("Remote server ping URL: %s, username: %s", url, username));
    HttpEntity<String> request = getBasicAuthRequestEntity(username, password);
    ResponseEntity<String> response = null;
    HttpStatus sc = null;
    String st = null;
    AvailabilityStatus status = null;
    try {
        response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        sc = response.getStatusCode();
    } catch (HttpClientErrorException | HttpServerErrorException ex) {
        sc = ex.getStatusCode();
        st = ex.getStatusText();
    } catch (ResourceAccessException ex) {
        return new AvailabilityStatus(false, "Network is unreachable", HttpStatus.BAD_GATEWAY);
    }
    log.debug("Response status code: " + sc);
    if (HttpStatus.OK.equals(sc)) {
        status = new AvailabilityStatus(true, "Authentication was successful", sc);
    } else if (HttpStatus.FOUND.equals(sc)) {
        status = new AvailabilityStatus(false, "No authentication was provided", sc);
    } else if (HttpStatus.UNAUTHORIZED.equals(sc)) {
        status = new AvailabilityStatus(false, "Authentication failed", sc);
    } else if (HttpStatus.INTERNAL_SERVER_ERROR.equals(sc)) {
        status = new AvailabilityStatus(false, "Remote server experienced an internal error", sc);
    } else {
        status = new AvailabilityStatus(false, "Server is not available: " + st, sc);
    }
    log.info("Status: " + status);
    return status;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) AvailabilityStatus(org.hisp.dhis.dxf2.synch.AvailabilityStatus) HttpStatus(org.springframework.http.HttpStatus) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) ResourceAccessException(org.springframework.web.client.ResourceAccessException)

Example 64 with HttpStatus

use of org.springframework.http.HttpStatus in project midpoint by Evolveum.

the class PageError method onInitialize.

@Override
protected void onInitialize() {
    super.onInitialize();
    Label codeLabel = new Label(ID_CODE, code);
    add(codeLabel);
    Label errorMessage = new Label(ID_ERROR_MESSAGE, createStringResource(getErrorMessageKey()));
    add(errorMessage);
    String errorLabel = "Unexpected error";
    if (code != null) {
        HttpStatus httpStatus = HttpStatus.valueOf(code);
        if (httpStatus != null) {
            errorLabel = httpStatus.getReasonPhrase();
        }
    }
    Label labelLabel = new Label(ID_LABEL, errorLabel);
    add(labelLabel);
    final IModel<String> message = new IModel<String>() {

        @Override
        public String getObject() {
            if (exClass == null) {
                return null;
            }
            SimpleDateFormat df = new SimpleDateFormat();
            return df.format(new Date()) + "\t" + exClass + ": " + exMessage;
        }
    };
    Label label = new Label(ID_MESSAGE, message);
    label.add(new VisibleEnableBehaviour() {

        @Override
        public boolean isVisible() {
            return StringUtils.isNotEmpty(message.getObject());
        }
    });
    add(label);
    AjaxButton back = new AjaxButton(ID_BACK, createStringResource("PageError.button.back")) {

        @Override
        public void onClick(AjaxRequestTarget target) {
            backPerformed(target);
        }
    };
    add(back);
    AjaxButton home = new AjaxButton(ID_HOME, createStringResource("PageError.button.home")) {

        @Override
        public void onClick(AjaxRequestTarget target) {
            homePerformed(target);
        }
    };
    add(home);
    MidpointForm form = new MidpointForm(ID_LOGOUT_FORM);
    form.add(AttributeModifier.replace("action", (IModel<String>) () -> getUrlForLogout()));
    form.add(new VisibleEnableBehaviour() {

        @Override
        public boolean isVisible() {
            return AuthUtil.getPrincipalUser() != null;
        }
    });
    add(form);
    WebMarkupContainer csrfField = SecurityUtils.createHiddenInputForCsrf(ID_CSRF_FIELD);
    form.add(csrfField);
}
Also used : IModel(org.apache.wicket.model.IModel) HttpStatus(org.springframework.http.HttpStatus) Label(org.apache.wicket.markup.html.basic.Label) MidpointForm(com.evolveum.midpoint.web.component.form.MidpointForm) Date(java.util.Date) WebMarkupContainer(org.apache.wicket.markup.html.WebMarkupContainer) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) AjaxButton(com.evolveum.midpoint.web.component.AjaxButton) VisibleEnableBehaviour(com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour) SimpleDateFormat(java.text.SimpleDateFormat)

Example 65 with HttpStatus

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

the class MockMvcClientHttpRequestFactory method getClientHttpResponse.

private ClientHttpResponse getClientHttpResponse(HttpMethod httpMethod, URI uri, HttpHeaders requestHeaders, byte[] requestBody) {
    try {
        MockHttpServletResponse servletResponse = this.mockMvc.perform(request(httpMethod, uri).content(requestBody).headers(requestHeaders)).andReturn().getResponse();
        HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
        byte[] body = servletResponse.getContentAsByteArray();
        MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
        clientResponse.getHeaders().putAll(getResponseHeaders(servletResponse));
        return clientResponse;
    } catch (Exception ex) {
        byte[] body = ex.toString().getBytes(StandardCharsets.UTF_8);
        return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : HttpStatus(org.springframework.http.HttpStatus) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockClientHttpResponse(org.springframework.mock.http.client.MockClientHttpResponse)

Aggregations

HttpStatus (org.springframework.http.HttpStatus)165 ResponseEntity (org.springframework.http.ResponseEntity)43 HttpHeaders (org.springframework.http.HttpHeaders)38 Test (org.junit.jupiter.api.Test)26 MediaType (org.springframework.http.MediaType)17 Mono (reactor.core.publisher.Mono)17 IOException (java.io.IOException)16 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)15 Collections (java.util.Collections)13 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 URI (java.net.URI)12 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 Map (java.util.Map)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 Resource (org.springframework.core.io.Resource)9 HashMap (java.util.HashMap)8