/**
   * Test a complete scenario. User sends .wmc file via POST and gets back the generated file path.
   * Then user asks via GET to get back the file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testWMCService() throws Exception {

    // valid wmc file content
    String fileContent =
        "<ViewContext xmlns=\"http://www.opengis.net/context\" version=\"1.1.0\" id=\"OpenLayers_Context_133\" xsi:schemaLocation=\"http://www.opengis.net/context http://schemas.opengis.net/context/1.1.0/context.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><General><Window width=\"1233\" height=\"342\"/><BoundingBox minx=\"-201405.7589\" miny=\"2245252.767\" maxx=\"598866.8058\" maxy=\"2467226.179\" SRS=\"EPSG:2154\"/><Title/><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/></Extension></General><LayerList><Layer queryable=\"0\" hidden=\"0\"><Server service=\"OGC:WMS\" version=\"1.1.1\"><OnlineResource xlink:type=\"simple\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"http://drebretagne-geobretagne.int.lsn.camptocamp.com/geoserver/wms\"/></Server><Name>topp:communes_geofla</Name><Title>communes_geofla</Title><FormatList><Format current=\"1\">image/jpeg</Format></FormatList><StyleList><Style current=\"1\"><Name/><Title>Default</Title></Style></StyleList><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/><ol:numZoomLevels xmlns:ol=\"http://openlayers.org/context\">16</ol:numZoomLevels><ol:units xmlns:ol=\"http://openlayers.org/context\">m</ol:units><ol:isBaseLayer xmlns:ol=\"http://openlayers.org/context\">true</ol:isBaseLayer><ol:displayInLayerSwitcher xmlns:ol=\"http://openlayers.org/context\">true</ol:displayInLayerSwitcher><ol:singleTile xmlns:ol=\"http://openlayers.org/context\">false</ol:singleTile></Extension></Layer></LayerList></ViewContext>"; // wmc file to be send

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.WMC_URL); // fake URI, Rest style
    _requestPost.setContent(fileContent.getBytes()); // fake body containing wmc file

    _controller.storeWMCFile(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.WMC_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getWMCFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(fileContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
예제 #2
0
  @Test
  public void WithoutArgsShouldForbidden() throws Exception {
    // null args method getProductCodes
    this.HttpStatus = HTTP_FORBIDDEN;
    MockHttpServletResponse mockresponse = this.getResponse(GET_OBJECTCUSTOMS, null);
    String reason_error = mockresponse.getHeader("Reason");
    Assert.assertNotNull(reason_error);

    String jsonstring = mockresponse.getContentAsString();
    Assert.assertNotNull(jsonstring);

    // null args method setProductCode
    MockHttpServletResponse mockresponse_set = this.getResponse(SET_OBJECTCUSTOMS, null);
    String reason_error_set = mockresponse_set.getHeader("Reason");
    Assert.assertNotNull(reason_error_set);

    String jsonstring_set = mockresponse_set.getContentAsString();

    Assert.assertNotNull(jsonstring_set);
    //  Assert.assertEquals("{\"code\":\"BUSINESS_ERR\",\"message\":\"at least some parameters need
    // to execute this service: nID, sID_UA, sName_UA\"}", jsonstring_set);

    // null args method removeProductCode
    MockHttpServletResponse mockresponse_remove = this.getResponse(REMOVE_OBJECTCUSTOMS, null);
    String reason_error_remove = mockresponse_remove.getHeader("Reason");
    Assert.assertNotNull(reason_error_remove);

    String jsonstring_remove = mockresponse_remove.getContentAsString();

    Assert.assertNotNull(jsonstring_remove);
    // Assert.assertEquals("{\"code\":\"BUSINESS_ERR\",\"message\":\"at least one parameter need to
    // execute this service: nID, sID_UA\"}", jsonstring_remove);

  }
  /**
   * Test a complete scenario. User sends sld file content via POST and gets back the generated file
   * path. Then user asks via GET to get back the sld file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testSLDService() throws Exception {

    // valid sld file
    String sldContent =
        "<StyledLayerDescriptor version=\"1.1.0\" xsi:schemaLocation=\"http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd\" xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:se=\"http://www.opengis.net/se\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <NamedLayer><se:Name>OCEANSEA_1M:Foundation</se:Name><UserStyle><se:Name>GEOSYM</se:Name><IsDefault>1</IsDefault><se:FeatureTypeStyle><se:FeatureTypeName>Foundation</se:FeatureTypeName><se:Rule><se:Name>main</se:Name><se:PolygonSymbolizer uom=\"http://www.opengis.net/sld/units/pixel\"><se:Name>MySymbol</se:Name><se:Description><se:Title>Example Symbol</se:Title><se:Abstract>This is just a simple example.</se:Abstract></se:Description><se:Geometry><ogc:PropertyName>GEOMETRY</ogc:PropertyName></se:Geometry><se:Fill><se:SvgParameter name=\"fill\">#96C3F5</se:SvgParameter></se:Fill></se:PolygonSymbolizer></se:Rule></se:FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.SLD_URL); // fake URI, Rest style
    _requestPost.setContent(sldContent.getBytes()); // fake body containing sld file
    _requestPost.setContentType("application/vnd.ogc.sld+xml");

    _controller.doSLDPost(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.SLD_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getSLDFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(sldContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
예제 #4
0
  @Test
  public void setObjectCustomsSaveOrUpdateUniqueAndSetDuplicate() throws Exception {
    // set duplicate sID_UA — must be error

    this.HttpStatus = HTTP_FORBIDDEN;
    this.params_duplicate.clear();
    this.params_duplicate.put("sID_UA", "0101");
    this.params_duplicate.put("sName_UA", "Руда");
    this.params_duplicate.put("sMeasure_UA", "кг");
    MockHttpServletResponse mockresponse_duplicate =
        this.getResponse(SET_OBJECTCUSTOMS, this.params_duplicate);
    String reason_error = mockresponse_duplicate.getHeader("Reason");
    Assert.assertNotNull(reason_error);

    // update with new unique data

    this.HttpStatus = HTTP_OK;

    MockHttpServletResponse mockresponse = this.getResponse(SET_OBJECTCUSTOMS, this.params_update);
    String jsonstring = mockresponse.getContentAsString();
    ObjectCustoms pcode_update = JsonRestUtils.readObject(jsonstring, ObjectCustoms.class);
    Assert.assertNotNull(jsonstring);
    Assert.assertEquals(this.expObjectCustomsUpdate, pcode_update);

    // set new data
    this.HttpStatus = HTTP_OK;
    MockHttpServletResponse mockresponse_set = this.getResponse(SET_OBJECTCUSTOMS, this.params_set);
    String jsonstring_set = mockresponse_set.getContentAsString();
    ObjectCustoms pcode_set = JsonRestUtils.readObject(jsonstring_set, ObjectCustoms.class);
    Assert.assertNotNull(jsonstring_set);
    Assert.assertEquals(this.expObjectCustomsSet, pcode_set);
  }
  @Test
  public void testParams() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params");
    Object handler = null;
    try {
      handler = this.handlerMapping.getHandler(request);
    } catch (Exception e) {
      // There is no matching handlers and some default handler
      // See
      // org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleNoMatch
      assertTrue(e instanceof UnsatisfiedServletRequestParameterException);
    }

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    request.addParameter("param2", "1");

    handler = this.handlerMapping.getHandler(request).getHandler();

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("User=1;account=1", testResponse);

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    handler = this.handlerMapping.getHandler(request).getHandler();

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("User=1", testResponse);
  }
  @Test
  public void testProduces() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/xml");
    Object handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertEquals(
        Collections.singleton(MediaType.APPLICATION_XML),
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("<test>XML</test>", testResponse);

    request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/json");
    handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertNull(
        "Negated expression should not be listed as a producible type",
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("{\"json\":\"body\"}", testResponse);
  }
예제 #7
0
  public void testRunWithErrors() throws Exception {
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
    request.setContent(("document=foobar.foobar").getBytes()); // NOTE: need space between periods.
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    System.out.println(response.getContentAsString());
    JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors");
    // the following will change whenever the configuration or validator functionaliy changes
    // but it doesn't indicate what particular errors are new/missing
    // assertEquals(3, errors.length());
    assertTrue(errors.get(0).toString().length() > 0);
  }
  /*
   * See SPR-6876
   */
  @Test
  public void variableNames() throws Exception {
    initDispatcherServlet(VariableNamesController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/foo");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("foo-foo", response.getContentAsString());

    request = new MockHttpServletRequest("DELETE", "/test/bar");
    response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("bar-bar", response.getContentAsString());
  }
  @Test
  public void multiPaths() throws Exception {
    initDispatcherServlet(MultiPathController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/category/page/5");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("handle4-page-5", response.getContentAsString());

    request = new MockHttpServletRequest("GET", "/category/page/5.html");
    response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("handle4-page-5", response.getContentAsString());
  }
  @Test
  public void relative() throws Exception {
    initDispatcherServlet(RelativePathUriTemplateController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("test-42-21", response.getContentAsString());

    request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21.html");
    response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("test-42-21", response.getContentAsString());
  }
예제 #11
0
  public void testSMDPrimitivesNoResult() throws Exception {
    // request
    setRequestContent("smd-6.txt");
    this.request.addHeader("content-type", "application/json-rpc");

    JSONInterceptor interceptor = new JSONInterceptor();
    interceptor.setEnableSMD(true);
    SMDActionTest1 action = new SMDActionTest1();

    this.invocation.setAction(action);

    // can't be invoked
    interceptor.intercept(this.invocation);
    assertFalse(this.invocation.isInvoked());

    // asert values were passed properly
    assertEquals("string", action.getStringParam());
    assertEquals(1, action.getIntParam());
    assertEquals(true, action.isBooleanParam());
    assertEquals('c', action.getCharParam());
    assertEquals(2, action.getLongParam());
    assertEquals(new Float(3.3), action.getFloatParam());
    assertEquals(4.4, action.getDoubleParam());
    assertEquals(5, action.getShortParam());
    assertEquals(6, action.getByteParam());

    String json = response.getContentAsString();

    String normalizedActual = TestUtils.normalize(json, true);
    String normalizedExpected = TestUtils.normalize(JSONResultTest.class.getResource("smd-11.txt"));
    assertEquals(normalizedExpected, normalizedActual);

    assertEquals("application/json;charset=ISO-8859-1", response.getContentType());
  }
  @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();

    ((OAuth20WrapperController) oauth20WrapperController)
        .getServicesManager()
        .save(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));

    final Map<String, Object> map = new HashMap<>();
    map.put(NAME, VALUE);
    final List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);

    final Principal p = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, map);
    final TicketGrantingTicketImpl impl =
        new TicketGrantingTicketImpl(
            TGT_ID,
            org.jasig.cas.authentication.TestUtils.getAuthentication(p),
            new NeverExpiresExpirationPolicy());

    ((OAuth20WrapperController) oauth20WrapperController)
        .getTicketRegistry()
        .addTicket(
            new ServiceTicketImpl(
                CODE,
                impl,
                org.jasig.cas.authentication.TestUtils.getService(),
                false,
                new ExpirationPolicy() {
                  private static final long serialVersionUID = -7321055962209199811L;

                  @Override
                  public boolean isExpired(final TicketState ticketState) {
                    return false;
                  }
                }));

    oauth20WrapperController.handleRequest(mockRequest, mockResponse);

    ((OAuth20WrapperController) oauth20WrapperController).getTicketRegistry().deleteTicket(CODE);

    assertEquals("text/plain", mockResponse.getContentType());
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    assertTrue(
        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 - 10 - delta);
  }
 @Test
 public void customSuffix() throws Exception {
   registerAndRefreshContext("spring.groovy.template.suffix:.groovytemplate");
   MockHttpServletResponse response = render("suffixed");
   String result = response.getContentAsString();
   assertThat(result, containsString("suffixed"));
 }
 @Test(expected = IllegalArgumentException.class)
 public void verifyDeleteServiceNoService() throws Exception {
   final MockHttpServletResponse response = new MockHttpServletResponse();
   this.controller.deleteRegisteredService(1200, response);
   assertNull(this.servicesManager.findServiceBy(1200));
   assertFalse(response.getContentAsString().contains("serviceName"));
 }
  @Test
  public void verifyExpiredAccessToken() throws Exception {
    final Principal principal =
        org.jasig.cas.authentication.TestUtils.getPrincipal(ID, new HashMap<String, Object>());
    final Authentication authentication = new OAuthAuthentication(ZonedDateTime.now(), principal);
    final DefaultAccessTokenFactory expiringAccessTokenFactory = new DefaultAccessTokenFactory();
    expiringAccessTokenFactory.setExpirationPolicy(
        new ExpirationPolicy() {
          @Override
          public boolean isExpired(final TicketState ticketState) {
            return true;
          }
        });
    final AccessTokenImpl accessToken =
        (AccessTokenImpl) expiringAccessTokenFactory.create(TestUtils.getService(), authentication);
    oAuth20ProfileController.getTicketRegistry().addTicket(accessToken);

    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    oAuth20ProfileController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    assertEquals(
        "{\"error\":\"" + OAuthConstants.EXPIRED_ACCESS_TOKEN + "\"}",
        mockResponse.getContentAsString());
  }
 @Test
 public void customTemplateLoaderPath() throws Exception {
   registerAndRefreshContext("spring.groovy.template.prefix:classpath:/custom-templates/");
   MockHttpServletResponse response = render("custom");
   String result = response.getContentAsString();
   assertThat(result, containsString("custom"));
 }
 @Test
 public void testGetTranslations() throws Exception {
   MockHttpServletResponse response = new MockHttpServletResponse();
   translationController.getTranslations(Locale.ENGLISH, response);
   assertThat(response.getStatus(), is(200));
   assertThat(response.getContentAsString(), isNotEmpty());
 }
예제 #18
0
 public void testRun() throws Exception {
   MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
   request.setContent("document=Foobar".getBytes());
   MockHttpServletResponse response = invoke(request);
   assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
   JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors");
   assertEquals(0, errors.length());
 }
 @Test
 public void includesViewResolution() throws Exception {
   registerAndRefreshContext();
   MockHttpServletResponse response = render("includes");
   String result = response.getContentAsString();
   assertThat(result, containsString("here"));
   assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
 }
예제 #20
0
  @Test
  public void shouldSendUpdateWhenOnePlayerRequested() throws UnsupportedEncodingException {
    sender.scheduleUpdate(updateRequestFor("vasya"));

    sender.sendUpdates(screenFor("vasya", "vasyaboard").asMap());

    assertContainsPlayerBoard(response.getContentAsString(), "vasya", "vasyaboard");
  }
 @Test
 public void customContentType() throws Exception {
   registerAndRefreshContext("spring.groovy.template.contentType:application/json");
   MockHttpServletResponse response = render("home");
   String result = response.getContentAsString();
   assertThat(result, containsString("home"));
   assertThat(response.getContentType(), equalTo("application/json;charset=UTF-8"));
 }
예제 #22
0
  @Test
  public void testCascadeGetLegendGraphics() throws Exception {
    // setup the layer
    WMSLayer layer = createWMSLayer("image/png");
    final byte[] responseBody = new String("Fake body").getBytes();
    layer.setSourceHelper(
        new WMSHttpHelper() {
          @Override
          public GetMethod executeRequest(
              URL url, Map<String, String> queryParams, Integer backendTimeout)
              throws HttpException, IOException {
            GetMethod response = EasyMock.createMock(GetMethod.class);
            expect(response.getStatusCode()).andReturn(200);
            expect(response.getResponseBodyAsStream())
                .andReturn(new ByteArrayInputStream(responseBody));
            expect(response.getResponseCharSet()).andReturn("UTF-8");
            expect(response.getResponseHeader("Content-Type"))
                .andReturn(new Header("Content-Type", "image/png"));
            response.releaseConnection();
            expectLastCall();
            replay(response);
            return response;
          }
        });
    MockLockProvider lockProvider = new MockLockProvider();
    layer.setLockProvider(lockProvider);

    // setup the conveyor tile
    final StorageBroker mockStorageBroker = EasyMock.createMock(StorageBroker.class);

    String layerId = layer.getName();
    MockHttpServletRequest servletReq = new MockHttpServletRequest();
    servletReq.setQueryString(
        "REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=topp:states");
    MockHttpServletResponse servletResp = new MockHttpServletResponse();

    long[] gridLoc = {0, 0, 0}; // x, y, level
    MimeType mimeType = layer.getMimeTypes().get(0);
    GridSet gridSet = gridSetBroker.WORLD_EPSG4326;
    String gridSetId = gridSet.getName();
    ConveyorTile tile =
        new ConveyorTile(
            mockStorageBroker,
            layerId,
            gridSetId,
            gridLoc,
            mimeType,
            null,
            servletReq,
            servletResp);

    // proxy the request, and check the response
    layer.proxyRequest(tile);

    assertEquals(200, servletResp.getStatus());
    assertEquals("Fake body", servletResp.getContentAsString());
    assertEquals("image/png", servletResp.getContentType());
  }
  @Test
  public void simple() throws Exception {
    initDispatcherServlet(SimpleUriTemplateController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("test-42", response.getContentAsString());
  }
예제 #24
0
  @Test
  public void shouldSendScores() throws UnsupportedEncodingException {
    sender.scheduleUpdate(updateRequestFor("vasya"));

    sender.sendUpdates(screenFor("vasya", 345, "vasyaboard").asMap());

    JsonPath jsonPath = from(response.getContentAsString());
    assertEquals(345, jsonPath.getInt("vasya.score"));
  }
  @Test
  public void testMultiplePathsTheSameEndpoint() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/path1");
    MockHttpServletResponse response = new MockHttpServletResponse();
    Object handler = this.handlerMapping.getHandler(request).getHandler();
    this.handlerAdapter.handle(request, response, handler);
    assertEquals(TEST_STRING_MULTIPLE_PATHS, response.getContentAsString());

    request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/path2");
    response = new MockHttpServletResponse();
    handler = this.handlerMapping.getHandler(request).getHandler();
    this.handlerAdapter.handle(request, response, handler);
    assertEquals(TEST_STRING_MULTIPLE_PATHS, response.getContentAsString());
  }
 @Test
 public void localeViewResolution() throws Exception {
   LocaleContextHolder.setLocale(Locale.FRENCH);
   registerAndRefreshContext();
   MockHttpServletResponse response = render("includes", Locale.FRENCH);
   String result = response.getContentAsString();
   assertThat(result, containsString("voila"));
   assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
 }
  @Test
  public void implicitSubPath() throws Exception {
    initDispatcherServlet(ImplicitSubPathController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("test-42", response.getContentAsString());
  }
  /*
   * See SPR-6640
   */
  @Test
  public void menuTree() throws Exception {
    initDispatcherServlet(MenuTreeController.class, null);

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/book/menu/type/M5");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);
    assertEquals("M5", response.getContentAsString());
  }
 @Test
 public void testCommenceWithHtmlAccept() throws Exception {
   request.addHeader("Accept", MediaType.TEXT_HTML_VALUE);
   entryPoint.commence(request, response, new BadCredentialsException("Bad"));
   // TODO: maybe use forward / redirect for HTML content?
   assertEquals(HttpServletResponse.SC_NOT_ACCEPTABLE, response.getStatus());
   assertEquals("", response.getContentAsString());
   assertEquals(null, response.getErrorMessage());
 }
  @Override
  protected void renderMergedOutputModel(
      Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
    super.renderMergedOutputModel(model, request, mockedResponse);
    encode(response.getOutputStream(), mockedResponse.getContentAsString());
  }