Example usage for org.springframework.mock.web MockHttpServletResponse getErrorMessage

List of usage examples for org.springframework.mock.web MockHttpServletResponse getErrorMessage

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getErrorMessage.

Prototype

@Nullable
    public String getErrorMessage() 

Source Link

Usage

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertErrorResponseUsingPersonUserCert(String certHeader, Object certAttribute,
        Cookie cookie, String expectedError) throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequestUsingPersonUserCert(certHeader, certAttribute,
            cookie);//from   w  w  w  .j ava2s .  com
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();

    Assert.assertNull("modelView", modelView);
    Assert.assertNull("sessionCookie", response.getCookie(SESSION_COOKIE_NAME));
    Assert.assertEquals("status", 401, response.getStatus());
    Assert.assertNotNull("errorResponseHeader", response.getHeader("CastleError"));
    Assert.assertEquals("errorMessage", expectedError, response.getErrorMessage());
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertErrorResponse(String loginString, String authzHeader, String expectedError,
        String expectedAuthzResponseHeader, String expectedAuthenticateHeader, CasIdmClient idmClient)
        throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, authzHeader,
            null /* sessionCookie */, idmClient);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    Assert.assertNull("sessionCookie", response.getCookie(SESSION_COOKIE_NAME));
    Assert.assertEquals("status", 401, response.getStatus());
    Object errorResponseHeader = response.getHeader("CastleError");
    Assert.assertNotNull("errorResponseHeader", errorResponseHeader);
    Assert.assertEquals("errorMessage", expectedError, response.getErrorMessage());

    if (expectedAuthzResponseHeader != null) {
        Object authzResponseHeader = response.getHeader("CastleAuthorization");
        Assert.assertNotNull("authzResponseHeader", authzResponseHeader);
        Assert.assertEquals("expectedAuthzResponseHeader", expectedAuthzResponseHeader,
                authzResponseHeader.toString());
    }/*from  w  w w  .ja va2  s . com*/

    if (expectedAuthenticateHeader != null) {
        Object wwwAuthenticateHeader = response.getHeader("WWW-Authenticate");
        Assert.assertNotNull("wwwAuthenticateHeader", wwwAuthenticateHeader);
        Assert.assertEquals("expectedAuthenticateHeader", expectedAuthenticateHeader,
                wwwAuthenticateHeader.toString());
    }
}

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void doTestPost() throws Exception {

    final String cookie = slurp(TestServletProxy.class.getResource("cookie.txt").openStream());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("/test_post");
    request.addHeader("Host", "test.samplesite.com");

    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Encoding", "gzip, deflate");
    request.addHeader("Accept-Language", "fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Cookie", cookie);

    request.addHeader("Referer",
            "https://test.samplesite.com/fr/group/control_panel/manage?p_auth=1bo6fC5N&p_p_id=dbSettingsPortlet_WAR_eloportalservicesportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&doAsGroupId=10157&refererPlid=10160&_dbSettingsPortlet_WAR_eloportalservicesportlet_action=showUpdate&_dbSettingsPortlet_WAR_eloportalservicesportlet_client=TMG");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setContent(//  www.  j a va 2 s . c om
            "_dbSettingsPortlet_WAR_eloportalservicesportlet_client=xxx&_dbSettingsPortlet_WAR_eloportalservicesportlet_url=jdbc%3Ajtds%3Asqlserver%3A%2F%2Fxxx.xxx.xxx.xxx%2FBD_FR533&_dbSettingsPortlet_WAR_eloportalservicesportlet_user=sa&_dbSettingsPortlet_WAR_eloportalservicesportlet_password=123abcd+&_dbSettingsPortlet_WAR_eloportalservicesportlet_poolmax=5"
                    .getBytes());

    final MockHttpServletResponse response = new MockHttpServletResponse();
    AjpServletProxy.forHost("localhost", getPort()).forward(request, response);
    if (response.getStatus() != 200) {
        System.out.println(response.getContentAsString());
        Assert.fail(response.getErrorMessage());
    }

    Assert.assertEquals("5", response.getContentAsString());
}

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void doTestGet() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/dizzy.mp4");
    final MockHttpServletResponse response = new MockHttpServletResponse();
    AjpServletProxy.forHost("localhost", getPort()).forward(request, response, 10, TimeUnit.SECONDS, true);
    if (response.getStatus() != 200) {
        System.out.println(response.getContentAsString());
        Assert.fail(response.getErrorMessage());
    }/*from  w ww  .j a v a2 s. co  m*/
}

From source file:alpha.portal.webapp.controller.ContributorRoleControllerTest.java

/**
 * "Umlaut"-Test.//from w w  w.  j a v a  2 s .  c  om
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
@Test
public void testUmlaute() throws Exception {
    final String newCRName = "'";

    MockHttpServletRequest request = this.newPost("/contributorRole");
    request.setRemoteUser(this.testUserName);
    request.addParameter("save_new", "button.save");
    request.addParameter("newContributorRole", newCRName);
    final MockHttpServletResponse response = new MockHttpServletResponse();
    this.ctrl.saveNew(request, response);
    Assert.assertTrue(StringUtils.isBlank(response.getErrorMessage()));

    request = this.newGet("/contributorRole");
    request.setRemoteUser(this.testUserName);
    final ModelAndView result = this.ctrl.showPage(request);
    final Map<String, Object> resModel = result.getModel();
    final Object contribListObj = resModel.get("contributorRolesList");
    final List<ContributorRole> contribList = (List<ContributorRole>) contribListObj;
    boolean contains = false;
    for (int c = 0; (c < contribList.size()) && (contains == false); c++) {
        if (contribList.get(c).getName().equals(newCRName)) {
            contains = true;
        }
    }
    Assert.assertTrue("Umlaut-Test failed", contains);
}

From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java

protected void sendData(String requestType, String contentType, String url, String data, int statusCode)
        throws Exception {
    MockHttpServletRequest request = createRequest(requestType, url);
    request.setContentType(contentType);

    if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
        request.setParameters(parseParamData(data));
        request.setContent(new byte[] {});
    } else {/*  w w  w  .  java  2  s . c  o m*/
        request.setContent(data.getBytes());
    }

    final MockHttpServletResponse response = createResponse();
    dispatch(request, response);

    s_log.info("Received response: {}", stringifyResponse(response));
    assertEquals(response.getErrorMessage(), statusCode, response.getStatus());
}

From source file:alpha.portal.webapp.controller.ContributorRoleControllerTest.java

/**
 * V-Test (save, show, edit, delete).//from  ww w .j av  a2  s  . c om
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
@Test
public void testVTest() throws Exception {
    final String newCRName = "New Test Contributor Role";

    final int numberOfRolesBeforeAdd = this.contributorRoleManager.getAll().size();

    /**
     * Add
     */
    MockHttpServletRequest request = this.newPost("/contributorRole");
    request.setRemoteUser(this.testUserName);
    request.addParameter("save_new", "button.save");
    request.addParameter("newContributorRole", newCRName);

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.ctrl.saveNew(request, response);
    Assert.assertTrue(StringUtils.isBlank(response.getErrorMessage()));

    /**
     * Show
     */
    request = this.newGet("/contributorRole");
    request.setRemoteUser(this.testUserName);

    ModelAndView result = this.ctrl.showPage(request);
    Map<String, Object> resModel = result.getModel();

    final Object contribListObj = resModel.get("contributorRolesList");
    final List<ContributorRole> contribList = (List<ContributorRole>) contribListObj;
    Assert.assertEquals((numberOfRolesBeforeAdd + 1), contribList.size());
    ContributorRole newCR = this.contributorRoleManager.getContributorRoleByName(newCRName);
    boolean contains = false;
    for (int c = 0; (c < contribList.size()) && (contains == false); c++) {
        if (contribList.get(c).getName().equals(newCRName)) {
            contains = true;
        }
    }
    Assert.assertTrue("New contrib.role in roles list", contains);

    /**
     * Edit-Page
     */
    request = this.newGet("/contributorRole");
    request.setRemoteUser(this.testUserName);
    request.addParameter("edit", newCR.getContributorRoleId().toString());

    result = this.ctrl.showPage(request);
    resModel = result.getModel();

    Assert.assertTrue(resModel.containsKey("showEditingForm"));
    Assert.assertTrue(resModel.containsKey("roleToEditId"));
    Assert.assertTrue(resModel.containsKey("roleToEdit"));
    Assert.assertFalse(resModel.containsKey("messageId"));

    Assert.assertEquals(newCR.getContributorRoleId().toString(), resModel.get("roleToEditId"));
    Assert.assertEquals(newCR.getName(), resModel.get("roleToEdit"));

    /**
     * Edit-Post
     */
    request = this.newPost("/contributorRole");
    request.setRemoteUser(this.testUserName);
    request.addParameter("save_edit", "button.save");
    request.addParameter("newContributorRole", newCRName + " - Changed");
    request.addParameter("oldContribRoleId", newCR.getContributorRoleId().toString());

    response = new MockHttpServletResponse();

    this.ctrl.saveEdit(request, response);
    Assert.assertTrue(StringUtils.isBlank(response.getErrorMessage()));

    newCR = this.contributorRoleManager.get(newCR.getContributorRoleId());
    Assert.assertEquals(newCRName + " - Changed", newCR.getName());

    /**
     * Delete
     */
    request = this.newPost("/contributorRole");
    request.setRemoteUser(this.testUserName);
    request.addParameter("delete", newCR.getContributorRoleId().toString());

    result = this.ctrl.showPage(request);
    resModel = result.getModel();

    Assert.assertTrue(resModel.containsKey("contributorRolesList"));
    Assert.assertTrue(StringUtils.isBlank(response.getErrorMessage()));

    boolean isException = false;
    try {
        newCR = this.contributorRoleManager.get(newCR.getContributorRoleId());
    } catch (final ObjectRetrievalFailureException e) {
        isException = true;
    }
    Assert.assertTrue("role not deleted", isException);
}

From source file:io.spring.initializr.web.test.MockMvcClientHttpRequestFactory.java

@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
    return new MockClientHttpRequest(httpMethod, uri) {
        @Override/*from w w w. j  a v  a 2 s. c  o  m*/
        public ClientHttpResponse executeInternal() throws IOException {
            try {
                MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
                requestBuilder.content(getBodyAsBytes());
                requestBuilder.headers(getHeaders());
                MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
                HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
                if (status.value() >= 400) {
                    requestBuilder = request(HttpMethod.GET, "/error")
                            .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
                            .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
                    if (servletResponse.getErrorMessage() != null) {
                        requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
                                servletResponse.getErrorMessage());
                    }
                    // Overwrites the snippets from the first request
                    servletResponse = actions(requestBuilder).andReturn().getResponse();
                }
                byte[] body = servletResponse.getContentAsByteArray();
                HttpHeaders headers = getResponseHeaders(servletResponse);
                MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
                clientResponse.getHeaders().putAll(headers);
                return clientResponse;
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }

    };
}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private String assembleStatusLine(MockHttpServletResponse response, Exception resolvedException) {
    StringBuilder builder = new StringBuilder();
    builder.append(response.getStatus());
    if (isNotBlank(response.getErrorMessage())) {
        builder.append(" ").append(response.getErrorMessage());
    } else if (resolvedException != null) {
        builder.append(" ").append(resolvedException.getMessage());
    }//from  ww w  .j a v  a2 s .c o m
    return builder.toString();
}

From source file:org.geoserver.opensearch.rest.CollectionsControllerTest.java

@Test
public void testGetCollectionsPagingValidation() throws Exception {
    MockHttpServletResponse response = getAsServletResponse("/rest/oseo/collections?offset=-1");
    assertEquals(400, response.getStatus());
    assertThat(response.getErrorMessage(), containsString("offset"));

    response = getAsServletResponse("/rest/oseo/collections?limit=-1");
    assertEquals(400, response.getStatus());
    assertThat(response.getErrorMessage(), containsString("limit"));

    response = getAsServletResponse("/rest/oseo/collections?limit=1000");
    assertEquals(400, response.getStatus());
    assertThat(response.getErrorMessage(), containsString("limit"));
}