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

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

Introduction

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

Prototype

public byte[] getContentAsByteArray() 

Source Link

Usage

From source file:org.eclipse.virgo.apps.repository.web.RepositoryControllerTests.java

@Test
public void getIndex() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setRequestURI("http://localhost:8080/org.eclipse.virgo.server.repository/my-repo");
    request.setMethod("GET");

    byte[] indexBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

    RepositoryIndex repositoryIndex = createMock(RepositoryIndex.class);
    expect(repositoryIndex.getInputStream()).andReturn(new ByteArrayInputStream(indexBytes)).anyTimes();
    expect(repositoryIndex.getETag()).andReturn("123456789").anyTimes();
    expect(repositoryIndex.getLength()).andReturn(indexBytes.length).anyTimes();

    expect(this.repositoryManager.getIndex("my-repo")).andReturn(repositoryIndex);

    replay(this.repositoryManager, repositoryIndex);

    repositoryController.getIndex(request, response);

    verify(this.repositoryManager, repositoryIndex);

    assertEquals("application/org.eclipse.virgo.repository.Index", response.getContentType());
    assertArrayEquals(indexBytes, response.getContentAsByteArray());
}

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestWithoutEntityButWithContentType() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, DOCROOT_ENDPOINT);
    request.setMethod(Method.Save.getProtocolGivenName());
    request.setContentType(DEFAULT_CONTENT_TYPE);
    request.setContent(new byte[] {});

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Save, DOCROOT_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertEquals(DEFAULT_CONTENT_TYPE, response.getContentType());
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals(response.getContentAsByteArray().length, response.getContentLength());
}

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestPostNoData() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();

    initMockHttpRequest(request, DOCROOT_ENDPOINT);
    request.setMethod(Method.Save.getProtocolGivenName());
    request.setContentType(DEFAULT_CONTENT_TYPE);
    request.setContent(new byte[] {});

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Save, DOCROOT_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertEquals(DEFAULT_CONTENT_TYPE, response.getContentType());
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals(response.getContentAsByteArray().length, response.getContentLength());
}

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestWithHostHeader() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_SPOOF_1_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    request.addHeader(WrmlServlet.WRML_HOST_HEADER_NAME, LOCALHOST);

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Get, CAPRICA_SIX_SPOOF_1_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals(DEFAULT_CONTENT_TYPE, response.getContentType());
    Assert.assertEquals(response.getContentAsByteArray().length, response.getContentLength());
}

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestWithHostAndPortHeaders() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    request.addHeader(WrmlServlet.WRML_HOST_HEADER_NAME, LOCALHOST);
    request.addHeader(WrmlServlet.WRML_PORT_HEADER_NAME, PORT_1);

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Get, CAPRICA_SIX_SPOOF_2_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals(DEFAULT_CONTENT_TYPE, response.getContentType());
    Assert.assertEquals(response.getContentAsByteArray().length, response.getContentLength());
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

@Test
public void testWorkspaceExport() throws Exception {
    MockHttpServletResponse response = doWorkspaceExport("sf");

    assertEquals("application/zip", response.getContentType());
    assertEquals("attachment; filename=\"sf.zip\"", response.getHeader("Content-Disposition"));

    Path tmp = Files.createTempDirectory(Paths.get("target"), "export");
    org.geoserver.data.util.IOUtils.decompress(new ByteArrayInputStream(response.getContentAsByteArray()),
            tmp.toFile());// w ww .  j a va2 s .  c  om

    assertTrue(tmp.resolve("bundle.json").toFile().exists());
}

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

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

    if (interceptor != null) {
        interceptor.intercept(requestBuilder);
    }/*from www.  ja  v  a2 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(ConfigConverter.convertToRestAssuredConfig(config));
        restAssuredResponse.setContent(response.getContentAsByteArray());
        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(TimingFilter.RESPONSE_TIME_MILLISECONDS, responseTime);
            }
        });
        restAssuredResponse.setCookies(convertCookies(response.getCookies()));

        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.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test attempt to retrieve a good file by an admin, where a good file is one that exists and is retrievable by
 * authorized user.//from  w w  w.  j  ava  2s.c  o  m
 *
 * Expected: Status 200
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 *
 * @throws IOException
 */
@Test
public void testGetFileRequestByAdmin() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;

    fileController.handleFileGetRequest(null, null, null, req, res);

    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));

    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);

    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good file request with null "Accept" header and null "If-Modified-Since" header
 * Expected: Status 200/* w  w  w  .  j  a v a  2 s . c  om*/
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestNullAcceptModifiedSinceHeader() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;

    //run the handle request
    fileController.handleFileGetRequest("foo", null, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);

    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good file request with specific "Accept" header
 * Expected: Status 200//  www . j a  v  a2  s  .c  o  m
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestSpecificAcceptHeader() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;
    String expectedMimeType = URLConnection.getFileNameMap().getContentTypeFor(dataFileOne.getName());

    //run the handle request
    fileController.handleFileGetRequest("foo", expectedMimeType, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);
    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}