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

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

Introduction

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

Prototype

public String getContentAsString() throws UnsupportedEncodingException 

Source Link

Document

Get the content of the response body as a String , using the charset specified for the response by the application, either through HttpServletResponse methods or through a charset parameter on the Content-Type .

Usage

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testServiceOnlyWithScopeEndpoint() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    req.addParameter("client_id", serviceApplicationWithScope.getExternalId());
    req.addParameter("client_secret", serviceApplicationWithScope.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {/*from  ww  w . ja  va 2s.  c  o m*/
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();
        final String accessToken = token.get(ACCESS_TOKEN).getAsString();

        Assert.assertTrue("response must be a valid json and have access_token field",
                token.has(ACCESS_TOKEN) && accessToken.length() > 0);

        String result = target("bennu-oauth").path("test").path("service-only-with-scope")
                .queryParam(ACCESS_TOKEN, accessToken).request().get(String.class);
        Assert.assertEquals("this is an endpoint with SERVICE scope, serviceOnly", result);

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

public void testDoPost_NoFiles_Handler() throws Exception {
    final String BEAN_NAME = "testAsyncUpNetSf";
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Map<String, List<FileItem>> mapFiles = new HashMap<>();
    Map<String, String[]> mapParameters = new HashMap<>();
    mapParameters.put("handler", new String[] { BEAN_NAME });
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, mapFiles,
            mapParameters);//from  www  .j  a v  a  2  s. com

    clearLuteceSpringCache();
    ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) SpringContextService
            .getContext()).getBeanFactory();
    beanFactory.registerSingleton(BEAN_NAME, new IAsynchronousUploadHandler() {
        @Override
        public void process(HttpServletRequest request, HttpServletResponse response, JSONObject mainObject,
                List<FileItem> fileItems) {
            mainObject.clear();
            mainObject.element("testnetsf", "valuetestnetsf");
        }

        @Override
        public boolean isInvoked(HttpServletRequest request) {
            return BEAN_NAME.equals(request.getParameter("handler"));
        }
    });

    try {
        new UploadServlet().doPost(multipartRequest, response);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ((DefaultListableBeanFactory) beanFactory).destroySingleton(BEAN_NAME);
        clearLuteceSpringCache();
    }

    String strResponseJson = response.getContentAsString();
    System.out.println(strResponseJson);

    String strRefJson = "{\"testnetsf\":\"valuetestnetsf\"}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode objectNodeRef = objectMapper.readTree(strRefJson);
    JsonNode objectNodeJson = objectMapper.readTree(strResponseJson);

    assertEquals(objectNodeRef, objectNodeJson);
}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

public void testDoPost_NoFiles_Handler2() throws Exception {
    final String BEAN_NAME = "testAsyncUpMap";
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Map<String, List<FileItem>> mapFiles = new HashMap<>();
    Map<String, String[]> mapParameters = new HashMap<>();
    mapParameters.put("handler", new String[] { BEAN_NAME });
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, mapFiles,
            mapParameters);//from   w ww.  j  av  a2 s  .c om

    clearLuteceSpringCache();
    ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) SpringContextService
            .getContext()).getBeanFactory();
    beanFactory.registerSingleton(BEAN_NAME, new IAsynchronousUploadHandler2() {
        @Override
        public void process(HttpServletRequest request, HttpServletResponse response,
                Map<String, Object> mainObject, List<FileItem> fileItems) {
            mainObject.clear();
            mainObject.put("testmap", "valuetestmap");
        }

        @Override
        public boolean isInvoked(HttpServletRequest request) {
            return BEAN_NAME.equals(request.getParameter("handler"));
        }
    });

    try {
        new UploadServlet().doPost(multipartRequest, response);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ((DefaultListableBeanFactory) beanFactory).destroySingleton(BEAN_NAME);
        clearLuteceSpringCache();
    }

    String strResponseJson = response.getContentAsString();
    System.out.println(strResponseJson);

    String strRefJson = "{\"testmap\":\"valuetestmap\"}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode objectNodeRef = objectMapper.readTree(strRefJson);
    JsonNode objectNodeJson = objectMapper.readTree(strResponseJson);

    assertEquals(objectNodeRef, objectNodeJson);
}

From source file:com.formkiq.core.service.workflow.WorkflowServiceImplTest.java

/**
 * print action./*from w w  w.ja  v  a  2  s  . c  o  m*/
 * @throws IOException IOException
 */
@Test
public void testActions02() throws IOException {
    // given
    String html = "<p>html</p>";
    byte[] pdf = html.getBytes(CHARSET_UTF8);
    MockHttpServletResponse resp = new MockHttpServletResponse();
    WebFlow flow = expectStart(this.form).getRight();
    Map<String, Object> map = ImmutableMap.of("flow", flow);

    resetAll();

    this.req.setParameter("execution", "s1e1");
    this.req.setParameter("_eventId_download", "");

    // when
    expect(this.printRender.generateHTML(this.req, "flow/print", map)).andReturn(html);
    expect(this.printRender.createPDF(html)).andReturn(pdf);
    replayAll();

    ModelAndView result = this.ws.actions(this.req, resp);

    // then
    verifyAll();

    assertNull(result);
    assertEquals("application/pdf", resp.getContentType());
    assertEquals(html.length(), resp.getContentLength());
    assertEquals(html, resp.getContentAsString());
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void getServiceAccessTokenHeaderTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*from   w  ww. j  a v a 2 s  .  co m*/
    String clientSecret = serviceApplication.getExternalId() + ":" + serviceApplication.getSecret();
    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();

        Assert.assertTrue("response must be a valid json and have access_token field",
                token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0);

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testServiceApplicationWithUnexistingScope() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*from  w  ww  .  j av a 2  s . c  om*/

    User user = createUser("testServiceApplicationWithUnexistingScope", "John", "Doe", "John Doe",
            "john.doe@fenixedu.org");

    ServiceApplication serviceApplication = new ServiceApplication();
    serviceApplication.setAuthor(user);

    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret", serviceApplication.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final String serviceAccessToken = new JsonParser().parse(tokenJson).getAsJsonObject()
                .get("access_token").getAsString();

        Response response = target("bennu-oauth").path("test").path("service-only-with-unexisting-scope")
                .queryParam("access_token", serviceAccessToken).request().get();

        Assert.assertNotEquals("request must fail since scope does not exist", 200, response.getStatus());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:com.openmeap.services.ServletManagementServletTest.java

@Test
public void testRefreshApplication() throws Exception {
    MockHttpServletRequest request = new Request();
    MockHttpServletResponse response = new MockHttpServletResponse();
    String randomUuid = UUID.randomUUID().toString();

    GlobalSettings settings = modelManager.getGlobalSettings();

    /////////////////
    // validate that finding the application, modifying it, and then finding it again 
    // will return an object with the same modifications.
    Application app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    app.setName(randomUuid);//from ww  w .j a va 2s. c o  m
    Assert.assertTrue(modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName()
            .equals(randomUuid));

    modelManager.refresh(app, null);
    app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    Assert.assertTrue(!modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName()
            .equals(randomUuid));

    ServiceManagementServlet servlet = new ServiceManagementServlet();
    servlet.setModelManager(modelManager);
    servlet.setModelServiceRefreshHandler(new ModelServiceRefreshHandler());
    servlet.getModelServiceRefreshHandler().setModelManager(modelManager);

    ////////////////////
    // validate the happy path of providing all the required information
    String authSalt = servlet.getAuthSalt();
    String authToken = AuthTokenProvider.newAuthToken(authSalt);
    request.setParameter(UrlParamConstants.REFRESH_TYPE, "Application");
    request.setParameter(UrlParamConstants.REFRESH_OBJ_PKID, "1");
    request.setParameter(UrlParamConstants.AUTH_TOKEN, authToken);
    request.setParameter(UrlParamConstants.ACTION, ModelEntityEventAction.MODEL_REFRESH.getActionName());
    servlet.service(request, response);
    String contentString = response.getContentAsString();
    JSONObjectBuilder job = new JSONObjectBuilder();
    Result result = (Result) job.fromJSON(new JSONObject(contentString), new Result());
    Assert.assertTrue(result.getStatus().equals(Result.Status.SUCCESS));
    Assert.assertTrue(!modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName()
            .equals(randomUuid));

    ////////////////////
    // validate that failing to provide auth token fails to refresh cache
    app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    app.setName(randomUuid);
    response = new MockHttpServletResponse();
    request.removeParameter(UrlParamConstants.AUTH_TOKEN);
    request.setParameter(UrlParamConstants.ACTION, ModelEntityEventAction.MODEL_REFRESH.getActionName());
    request.setParameter(UrlParamConstants.REFRESH_TYPE, "Application");
    request.setParameter(UrlParamConstants.REFRESH_OBJ_PKID, "1");
    servlet.service(request, response);
    contentString = response.getContentAsString();
    result = (Result) job.fromJSON(new JSONObject(contentString), new Result());
    Assert.assertTrue(result.getStatus().equals(Result.Status.FAILURE));
    Assert.assertTrue(modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName()
            .equals(randomUuid));

}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testServiceApplicationOAuthAccessProvider() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();//from w  ww  .j a  va2  s  .co  m

    User user = createUser("testServiceApplicationOAuthAccessProvider", "John", "Doe", "John Doe",
            "john.doe@fenixedu.org");

    ServiceApplication serviceApplication = new ServiceApplication();
    serviceApplication.setAuthor(user1);
    serviceApplication.addScopes(serviceApplicationOAuthAccessProvider);
    serviceApplication.addScopes(loggedScope);

    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret", serviceApplication.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final String serviceAccessToken = new JsonParser().parse(tokenJson).getAsJsonObject()
                .get("access_token").getAsString();

        String result = target("oauth").path("provider").path(serviceApplication.getExternalId())
                .path(user.getUsername()).queryParam("access_token", serviceAccessToken).request()
                .post(null, String.class);

        Authenticate.unmock();

        final String userAccessToken = new JsonParser().parse(result).getAsJsonObject().get("access_token")
                .getAsString();

        result = target("bennu-oauth").path("test").path("test-scope-with-logged-user")
                .queryParam("access_token", userAccessToken).request().get(String.class);

        Assert.assertEquals("this is an endpoint with TEST scope: testServiceApplicationOAuthAccessProvider",
                result);

        Authenticate.mock(user);

        JsonArray authorizations = target("bennu-oauth").path("authorizations").request().get(JsonElement.class)
                .getAsJsonArray();

        Assert.assertEquals("no authorizations because it is a service application", 0, authorizations.size());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    } finally {
        serviceApplication.removeScope(serviceApplicationOAuthAccessProvider);
        serviceApplication.removeScope(loggedScope);
    }

}

From source file:com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

@SuppressWarnings("unchecked")
private MockMvcResponse performRequest(MockHttpServletRequestBuilder requestBuilder) {
    MockHttpServletResponse response;

    if (interceptor != null) {
        interceptor.intercept(requestBuilder);
    }//w  ww  .  jav  a 2  s .  c om

    if (isSpringSecurityInClasspath()
            && authentication instanceof org.springframework.security.core.Authentication) {
        org.springframework.security.core.context.SecurityContextHolder.getContext()
                .setAuthentication((org.springframework.security.core.Authentication) authentication);
    } else if (authentication instanceof Principal) {
        requestBuilder.principal((Principal) authentication);
    }

    for (RequestPostProcessor requestPostProcessor : requestPostProcessors) {
        requestBuilder.with(requestPostProcessor);
    }

    MockMvcRestAssuredResponseImpl restAssuredResponse;
    try {
        final long start = System.currentTimeMillis();
        ResultActions perform = mockMvc.perform(requestBuilder);
        final long responseTime = System.currentTimeMillis() - start;
        if (!resultHandlers.isEmpty()) {
            for (ResultHandler resultHandler : resultHandlers) {
                perform.andDo(resultHandler);
            }
        }
        MvcResult mvcResult = getMvcResult(perform, isAsyncRequest);
        response = mvcResult.getResponse();
        restAssuredResponse = new MockMvcRestAssuredResponseImpl(perform, logRepository);
        restAssuredResponse.setConfig(convertToRestAssuredConfig(config));
        restAssuredResponse.setContent(response.getContentAsString());
        restAssuredResponse.setContentType(response.getContentType());
        restAssuredResponse.setHasExpectations(false);
        restAssuredResponse.setStatusCode(response.getStatus());
        restAssuredResponse.setResponseHeaders(assembleHeaders(response));
        restAssuredResponse.setRpr(getRpr());
        restAssuredResponse.setStatusLine(assembleStatusLine(response, mvcResult.getResolvedException()));
        restAssuredResponse.setFilterContextProperties(new HashMap() {
            {
                put(RESPONSE_TIME_MILLISECONDS, responseTime);
            }
        });

        if (responseSpecification != null) {
            responseSpecification.validate(ResponseConverter.toStandardResponse(restAssuredResponse));
        }

    } catch (Exception e) {
        return SafeExceptionRethrower.safeRethrow(e);
    } finally {
        if (isSpringSecurityInClasspath()) {
            org.springframework.security.core.context.SecurityContextHolder.clearContext();
        }
    }
    return restAssuredResponse;
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void getAccessTokenHeaderTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*from w  w  w  .ja v a  2  s.com*/

    ExternalApplication externalApp = new ExternalApplication();
    externalApp.setAuthor(user1);
    externalApp.setName("Test External Application");
    externalApp.setDescription("This is a test external application");
    externalApp.setRedirectUrl("http://test.url/callback");

    ApplicationUserSession applicationUserSession = new ApplicationUserSession();
    applicationUserSession.setCode("fenixedu");

    ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1,
            externalApp);
    applicationUserAuthorization.addSession(applicationUserSession);
    externalApp.addApplicationUserAuthorization(applicationUserAuthorization);

    String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret();
    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl());
    req.addParameter(CODE, applicationUserSession.getCode());
    req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);
        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();
        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();

        Assert.assertTrue("response must be a valid json and have access_token field",
                token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0);

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}