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

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

Introduction

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

Prototype

@Override
    @Nullable
    public String getContentType() 

Source Link

Usage

From source file:org.geoserver.wps.gs.download.DownloadMapProcessTest.java

@Test
public void downloadRemoteSimple13() throws Exception {
    String request = IOUtils.toString(getClass().getResourceAsStream("mapRemoteSimple13.xml"));
    String caps130 = IOUtils.toString(getClass().getResourceAsStream("caps130.xml"));
    byte[] getMapBytes = FileUtils.readFileToByteArray(new File(SAMPLES + "mapSimple.png"));
    DownloadMapProcess process = applicationContext.getBean(DownloadMapProcess.class);
    MockHttpClient client = new MockHttpClient();
    client.expectGet(/*from   w ww.j  av a 2  s.  co m*/
            new URL("http://geoserver.org/geoserver/wms?service=WMS&request=GetCapabilities&version=1.3.0"),
            new MockHttpResponse(caps130, "text/xml"));
    // check it follows the links in the caps document and does axis flipping as required
    client.expectGet(new URL("http://mock.test.geoserver"
            + ".org/wms13?SERVICE=WMS&LAYERS=cite:BasicPolygons&FORMAT=image%2Fpng&HEIGHT=256&TRANSPARENT=false"
            + "&REQUEST=GetMap&WIDTH=256&BBOX=1.4,-2.4,4.2,0.4&CRS=EPSG:4326&VERSION=1.3.0"),
            new MockHttpResponse(getMapBytes, "image/png"));
    // switch from the standard supplier to one using the mock client prepared above
    Supplier<HTTPClient> oldSupplier = process.getHttpClientSupplier();
    try {
        process.setHttpClientSupplier(() -> client);

        MockHttpServletResponse response = postAsServletResponse("wps", request);
        assertEquals("image/png", response.getContentType());
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(response.getContentAsByteArray()));
        ImageAssert.assertEquals(new File(SAMPLES + "mapSimple.png"), image, 100);
    } finally {
        process.setHttpClientSupplier(oldSupplier);
    }
}

From source file:org.geoserver.wps.gs.download.DownloadMapProcessTest.java

@Test
public void downloadLocalRemote() throws Exception {
    String request = IOUtils.toString(getClass().getResourceAsStream("mapLocalRemote.xml"));
    String caps111 = IOUtils.toString(getClass().getResourceAsStream("caps111.xml"));
    byte[] getMapBytes = FileUtils.readFileToByteArray(new File(SAMPLES + "lakes.png"));
    DownloadMapProcess process = applicationContext.getBean(DownloadMapProcess.class);
    MockHttpClient client = new MockHttpClient();
    client.expectGet(//w w  w  . j a  v a2s .  c  o m
            new URL("http://geoserver"
                    + ".org/geoserver/wms?service=WMS&request=GetCapabilities&version=1.1.0"),
            new MockHttpResponse(caps111, "text/xml"));
    // check it follows the links in the caps document
    client.expectGet(
            new URL("http://mock.test.geoserver"
                    + ".org/wms11?SERVICE=WMS&LAYERS=cite:Lakes&FORMAT=image%2Fpng&HEIGHT=256&TRANSPARENT=true"
                    + "&REQUEST=GetMap&WIDTH=256&BBOX=0.0,-0.003,0.004,0.001&SRS=EPSG:4326&VERSION=1.1.1"),
            new MockHttpResponse(getMapBytes, "image/png"));
    // switch from the standard supplier to one using the mock client prepared above
    Supplier<HTTPClient> oldSupplier = process.getHttpClientSupplier();
    try {
        process.setHttpClientSupplier(() -> client);

        MockHttpServletResponse response = postAsServletResponse("wps", request);
        assertEquals("image/png", response.getContentType());
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(response.getContentAsByteArray()));
        ImageAssert.assertEquals(new File(SAMPLES + "localRemote.png"), image, 100);
    } finally {
        process.setHttpClientSupplier(oldSupplier);
    }
}

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testGetCap() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/WMTSCapabilities.xml");
    MockHttpServletResponse resp = dispatch(req);

    assertEquals(200, resp.getStatus());
    assertEquals("text/xml", resp.getContentType());
    final Document doc = XMLUnit.buildTestDocument(resp.getContentAsString());
    assertXpathExists("//wmts:Contents/wmts:Layer", doc);
    assertXpathExists("//wmts:Contents/wmts:Layer[ows:Identifier='mockLayer']", doc);
    assertXpathEvaluatesTo("2", "count(//wmts:Contents/wmts:Layer/wmts:Style/ows:Identifier)", doc);
    assertXpathExists("//wmts:Contents/wmts:Layer/wmts:Style[ows:Identifier='style-a']", doc);
    assertXpathExists("//wmts:Contents/wmts:Layer/wmts:Style[ows:Identifier='style-b']/wmts:LegendURL"
            + "[@width='125'][@height='130'][@format='image/png']"
            + "[@minScaleDenominator='5000.0'][@maxScaleDenominator='10000.0']"
            + "[@xlink:href='https://some-url?some-parameter=value3&another-parameter=value4']", doc);
    assertXpathExists("//wmts:Contents/wmts:Layer/wmts:ResourceURL[@resourceType='tile']"
            + "[@format='image/jpeg']" + "[@template='http://localhost/service/wmts/rest/"
            + "mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/jpeg&time={time}&elevation={elevation}']",
            doc);//www.j ava  2 s.com
    assertXpathExists("//wmts:Contents/wmts:Layer/wmts:ResourceURL[@resourceType='FeatureInfo']"
            + "[@format='text/plain']" + "[@template='http://localhost/service/wmts/rest"
            + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}/{J}/{I}?format=text/plain&time={time}&elevation={elevation}']",
            doc);
    assertXpathExists("//wmts:ServiceMetadataURL[@xlink:href='http://localhost/service/wmts/rest"
            + "/WMTSCapabilities.xml']", doc);
}

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testGetTileWithStyle() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/style-a/EPSG:4326/EPSG:4326:0/0/0");
    req.addParameter("format", "image/png");

    MockHttpServletResponse resp = dispatch(req);

    assertEquals(200, resp.getStatus());
    assertEquals("image/png", resp.getContentType());
    assertEquals("EPSG:4326", resp.getHeader("geowebcache-crs"));
    assertArrayEquals(getSampleTileContent().getContents(), resp.getContentAsByteArray());
}

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testGetInfoWithStyle() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/style-a/EPSG:4326/EPSG:4326:0/0/0/0/0");
    req.addParameter("format", "text/plain");

    final MockHttpServletResponse resp = dispatch(req);

    assertEquals(200, resp.getStatus());
    assertEquals("text/plain", resp.getContentType());
}

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testGetInfoWithoutStyle() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/EPSG:4326/EPSG:4326:0/0/0/0/0");
    req.addParameter("format", "text/plain");

    final MockHttpServletResponse resp = dispatch(req);

    assertEquals(200, resp.getStatus());
    assertEquals("text/plain", resp.getContentType());
}

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testOWSException() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/EPSG:4326/EPSG:4326:0/0/0/0/0");
    req.addParameter("format", "text/none");

    MockHttpServletResponse resp = dispatch(req);

    assertEquals(HttpStatus.SC_BAD_REQUEST, resp.getStatus());
    assertEquals("text/xml", resp.getContentType());

    Document doc = XMLUnit.buildTestDocument(resp.getContentAsString());
    assertXpathExists("//ows:ExceptionReport/ows:Exception[@exceptionCode='InvalidParameterValue']", doc);
}

From source file:org.jasig.cas.support.oauth.web.OAuth20AccessTokenControllerTests.java

@Test
public void verifyOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    final ServiceTicket serviceTicket = mock(ServiceTicket.class);
    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    // 10 seconds
    final int timeBefore = 10;
    when(ticketGrantingTicket.getCreationTime()).thenReturn(System.currentTimeMillis() - timeBefore * 1000);
    when(ticketGrantingTicket.getId()).thenReturn(TGT_ID);
    when(serviceTicket.isExpired()).thenReturn(false);
    when(serviceTicket.getId()).thenReturn(CODE);
    when(serviceTicket.getGrantingTicket()).thenReturn(ticketGrantingTicket);
    when(ticketRegistry.getTicket(CODE)).thenReturn(serviceTicket);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.setTimeout(TIMEOUT);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    verify(ticketRegistry).deleteTicket(CODE);
    assertEquals("text/plain", mockResponse.getContentType());
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    assertTrue(/* ww w  .jav a 2s. c  om*/
            body.startsWith(OAuthConstants.ACCESS_TOKEN + "=" + TGT_ID + "&" + OAuthConstants.EXPIRES + "="));
    // delta = 2 seconds
    final int delta = 2;
    final int timeLeft = Integer.parseInt(StringUtils.substringAfter(body, "&" + OAuthConstants.EXPIRES + "="));
    assertTrue(timeLeft >= TIMEOUT - timeBefore - delta);
    assertTrue(timeLeft <= TIMEOUT - timeBefore + delta);
}

From source file:org.kuali.mobility.shared.controllers.FileControllerTest.java

@Test
public void testGetFile() {
    String viewName;// w  ww  .ja v  a2  s  . co  m
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    MockHttpServletResponse response = new MockHttpServletResponse();
    try {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);

        MockMultipartFile mockFile = new MockMultipartFile(FORM_FILE_NAME, FILE_NAME, CONTENT_TYPE, in);

        File file = new File(mockFile);

        when(getFileService().findFileById(file.getId())).thenReturn(file);

        getController().getFile(file.getId(), request, response);

        assertTrue("Content type of response is not text/plain.",
                CONTENT_TYPE.equals(response.getContentType()));
        assertTrue("Response content length does not match file length.",
                file.getFileSize() == response.getContentLength());
        String responseText = IOUtils.toString(response.getContentAsByteArray(), CONTENT_ENCODING);

        String fileContent = IOUtils.toString(file.getBytes(), CONTENT_ENCODING);
        assertTrue("Response content does not match file content.", fileContent.equals(responseText));

    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
        fail("Could not get file because of an IOException.");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage(), e);
        fail("Could not get file because of an Exception.");
    }
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

private MockHttpServletResponse initAndExecuteDetailedCheck(HealthServlet healthServlet) throws Exception {
    healthServlet.init();//from  ww w  . ja v  a2 s .c  o  m
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost:8080/rice-standalone/health");
    request.setMethod("GET");
    request.setParameter("detail", "true");
    MockHttpServletResponse response = new MockHttpServletResponse();
    healthServlet.service(request, response);
    String content = response.getContentAsString();
    assertEquals("application/json", response.getContentType());
    assertFalse(content.isEmpty());
    return response;
}