Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#setContextPath()

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest#setContextPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HtmlUnitRequestBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void contextPath(MockHttpServletRequest request, UriComponents uriComponents) {
	if (this.contextPath == null) {
		List<String> pathSegments = uriComponents.getPathSegments();
		if (pathSegments.isEmpty()) {
			request.setContextPath("");
		}
		else {
			request.setContextPath("/" + pathSegments.get(0));
		}
	}
	else {
		String path = uriComponents.getPath();
		Assert.isTrue(path != null && path.startsWith(this.contextPath),
				() -> "\"" + uriComponents.getPath() +
						"\" should start with context path \"" + this.contextPath + "\"");
		request.setContextPath(this.contextPath);
	}
}
 
Example 2
Source File: CrnkServletTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onSimpleResourceGetShouldReturnOneResource() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks/1");
    request.setRequestURI("/api/tasks/1");
    request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    servlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);

    assertJsonPartEquals("tasks", responseContent, "data.type");
    assertJsonPartEquals("\"1\"", responseContent, "data.id");
    assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data.attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example 3
Source File: CrnkFilterTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onNonRepositoryRequestShouldPassTrough() throws Exception {
    MockFilterChain filterChain = new MockFilterChain();

    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo(null);
    request.setRequestURI("/api/somethingDifferent/");
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    filter.doFilter(request, response, filterChain);

    // no content set yet
    Assert.assertEquals(0, response.getContentLength());
}
 
Example 4
Source File: KatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onSimpleResourceGetShouldReturnOneResource() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/1");
	request.setRequestURI("/api/tasks/1");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();

	log.debug("responseContent: {}", responseContent);
	assertNotNull(responseContent);

	assertJsonPartEquals("tasks", responseContent, "data.type");
	assertJsonPartEquals("\"1\"", responseContent, "data.id");
	assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes");
	assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links");
	assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example 5
Source File: OpenTracingServerModuleTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws ServletException {
	simpleTransactionNames = false;

	tracer = Mockito.mock(Tracer.class);
	MockServletContext servletContext = new MockServletContext();

	initModule();

	request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/");
	request.setRequestURI("/api/tasks/");
	request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
	request.addHeader("Accept", "*/*");
}
 
Example 6
Source File: CrnkServletRejectJsonTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptWildcard() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks/1");
    request.setRequestURI("/api/tasks/1");
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    servlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);

    assertJsonPartEquals("tasks", responseContent, "data.type");
    assertJsonPartEquals("\"1\"", responseContent, "data.id");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example 7
Source File: HtmlUnitRequestBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void contextPath(MockHttpServletRequest request, UriComponents uriComponents) {
	if (this.contextPath == null) {
		List<String> pathSegments = uriComponents.getPathSegments();
		if (pathSegments.isEmpty()) {
			request.setContextPath("");
		}
		else {
			request.setContextPath("/" + pathSegments.get(0));
		}
	}
	else {
		String path = uriComponents.getPath();
		Assert.isTrue(path != null && path.startsWith(this.contextPath),
				() -> "\"" + uriComponents.getPath() +
						"\" should start with context path \"" + this.contextPath + "\"");
		request.setContextPath(this.contextPath);
	}
}
 
Example 8
Source File: MockHttpServletRequestBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Update the contextPath, servletPath, and pathInfo of the request.
 */
private void updatePathRequestProperties(MockHttpServletRequest request, String requestUri) {
	if (!requestUri.startsWith(this.contextPath)) {
		throw new IllegalArgumentException(
				"Request URI [" + requestUri + "] does not start with context path [" + this.contextPath + "]");
	}
	request.setContextPath(this.contextPath);
	request.setServletPath(this.servletPath);

	if ("".equals(this.pathInfo)) {
		if (!requestUri.startsWith(this.contextPath + this.servletPath)) {
			throw new IllegalArgumentException(
					"Invalid servlet path [" + this.servletPath + "] for request URI [" + requestUri + "]");
		}
		String extraPath = requestUri.substring(this.contextPath.length() + this.servletPath.length());
		this.pathInfo = (StringUtils.hasText(extraPath) ?
				urlPathHelper.decodeRequestString(request, extraPath) : null);
	}
	request.setPathInfo(this.pathInfo);
}
 
Example 9
Source File: OpendapServletTest.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void dodsDataRequestTest() throws IOException {
  String mockURI = "/thredds/dodsC" + path + ".dods";
  String mockQueryString = "Temperature_height_above_ground[0:1:0][0:1:0][41][31]";
  MockHttpServletRequest request = new MockHttpServletRequest("GET", mockURI);
  request.setContextPath("/thredds");
  request.setQueryString(mockQueryString);
  request.setPathInfo(path + ".dods");
  MockHttpServletResponse response = new MockHttpServletResponse();
  opendapServlet.doGet(request, response);
  assertEquals(200, response.getStatus());
  // not set by servlet mocker :: assertEquals("application/octet-stream", response.getContentType());

  String strResponse = response.getContentAsString();
  System.out.printf("%s%n", strResponse);
}
 
Example 10
Source File: BaseTestCase.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static RequestContext createRequestContext(ApplicationContext applicationContext, ServletContext srvCtx) {
    RequestContext reqCtx = new RequestContext();
    srvCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme("http");
    request.setServerName("www.entando.com");
    request.addHeader("Host", "www.entando.com");
    request.setContextPath("/Entando");
    request.setAttribute(RequestContext.REQCTX, reqCtx);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpSession session = new MockHttpSession(srvCtx);
    request.setSession(session);
    reqCtx.setRequest(request);
    reqCtx.setResponse(response);
    ILangManager langManager = (ILangManager) applicationContext.getBean(SystemConstants.LANGUAGE_MANAGER);
    Lang defaultLang = langManager.getDefaultLang();
    reqCtx.addExtraParam(SystemConstants.EXTRAPAR_CURRENT_LANG, defaultLang);
    return reqCtx;
}
 
Example 11
Source File: AutomaticDispatcherUrlServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testLocalizeAutomatic() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();

	// set mock request in context holder
	MockHttpServletRequest mockRequest = new MockHttpServletRequest();
	mockRequest.setScheme("http");
	mockRequest.setServerName("myhost");
	mockRequest.setServerPort(80);
	mockRequest.setLocalName("localhost");
	mockRequest.setLocalPort(8080);
	mockRequest.setContextPath("/test");
	mockRequest.addHeader(X_FORWARD_HOST_HEADER, "geomajas.org");
	ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
	RequestContextHolder.setRequestAttributes(attributes);
	Assert.assertEquals("http://localhost:8080/test/d/something", adus.localize("http://geomajas.org/test/d/something"));

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example 12
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onSimpleCollectionGetShouldReturnCollectionOfResources() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/");
	request.setRequestURI("/api/tasks/");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();

	log.debug("responseContent: {}", responseContent);
	assertNotNull(responseContent);

	assertJsonPartEquals("tasks", responseContent, "data[0].type");
	assertJsonPartEquals("\"1\"", responseContent, "data[0].id");
	assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes");
	assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
	assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links");
}
 
Example 13
Source File: OpendapServletTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void asciiDataRequestTest2() throws UnsupportedEncodingException {
  String mockURI = "/thredds/dodsC" + path + ".ascii";
  String mockQueryString = "Temperature_height_above_ground[0:1:0][0:1:0][0:10:64][0:10:92]";
  MockHttpServletRequest request = new MockHttpServletRequest("GET", mockURI);
  request.setContextPath("/thredds");
  request.setQueryString(mockQueryString);
  request.setPathInfo(path + ".ascii");
  MockHttpServletResponse response = new MockHttpServletResponse();
  opendapServlet.doGet(request, response);
  assertEquals(200, response.getStatus());

  String strResponse = response.getContentAsString();
  System.out.printf("%s%n", strResponse);
}
 
Example 14
Source File: RequestSpec.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Before
public final void setup() throws ServletException{
    replaceError();
    config = new MockFilterConfig();
    dispatcher = new RequestDispatcher();
    request = new MockHttpServletRequest();
    request.setContextPath("/test_context");
    dispatcher.init(config);
    response = new MockHttpServletResponse();
    RequestContext.clear();
    RequestContext.setTLs(request, response, config, new AppContext(), new RequestVo(), null);
    Configuration.getTemplateManager().setTemplateLocation("src/test/views");
}
 
Example 15
Source File: InitialFlowSetupActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifySettingContextPath() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath(CONST_CONTEXT_PATH);
    final MockRequestContext context = new MockRequestContext();
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));

    this.action.doExecute(context);

    assertEquals(CONST_CONTEXT_PATH + "/", this.warnCookieGenerator.getCookiePath());
    assertEquals(CONST_CONTEXT_PATH + "/", this.tgtCookieGenerator.getCookiePath());
}
 
Example 16
Source File: StaticViewerTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void checkViewerPropertyWithOpendapReplacement() throws URISyntaxException {
  String host = "http://test.thredds.servlet.StaticViewerTest";
  String contextPath = "/thredds";
  String servletPath = "/catalog";
  String catPathNoExtension = "/checkViewerPropertyWithOpendapReplacement";
  String docBaseUriString = host + contextPath + servletPath + catPathNoExtension + ".xml";
  URI docBaseUri = new URI(docBaseUriString);

  String catalogAsString = setupCatDsWithViewerProperty("viewer1", "{OPENDAP}.info,ODAP DS info");

  Dataset ds1 = constructCatalogAndAssertAsExpected(docBaseUri, catalogAsString);

  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setMethod("GET");
  request.setContextPath(contextPath);
  request.setServletPath(servletPath);
  request.setPathInfo(catPathNoExtension + ".html");
  request.setParameter("dataset", "ds1");

  ViewerLinkProvider sv = ViewerServiceImpl.getStaticView();
  List<ViewerLinkProvider.ViewerLink> viewerLinks = sv.getViewerLinks(ds1, request);
  assertNotNull(viewerLinks);
  Assert.assertEquals(1, viewerLinks.size());

  ViewerLinkProvider.ViewerLink vl = viewerLinks.get(0);
  assertNotNull(vl);
  Assert.assertEquals("ODAP DS info", vl.getTitle());
  Assert.assertEquals(host + contextPath + "/dodsC" + "/test/ds1.nc.info", vl.getUrl());
}
 
Example 17
Source File: InitialFlowSetupActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testSettingContextPath() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String CONST_CONTEXT_PATH = "/test";
    request.setContextPath(CONST_CONTEXT_PATH);
    final MockRequestContext context = new MockRequestContext();
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));

    this.action.doExecute(context);

    assertEquals(CONST_CONTEXT_PATH + "/", this.warnCookieGenerator.getCookiePath());
    assertEquals(CONST_CONTEXT_PATH + "/", this.tgtCookieGenerator.getCookiePath());
}
 
Example 18
Source File: ConditionalDelegatingFilterProxyTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	request = new MockHttpServletRequest();
	request.setContextPath("/context");
	response = new MockHttpServletResponse();
	filterChain = new MockFilterChain();
	delegate = new MockFilter();
}
 
Example 19
Source File: ExceptionHandlerFacadeImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testLogAndHandleExceptionHttpServletRequestProblem() {
  Exception e = mock(Exception.class);
  HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setContextPath("/context");
  request.setRequestURI("/context/api");
  ExceptionResponseGenerator responseGenerator = mock(ExceptionResponseGenerator.class);
  when(exceptionResponseGeneratorRegistry.getExceptionResponseGenerator(PROBLEM))
      .thenReturn(responseGenerator);

  exceptionHandlerFacadeImpl.logAndHandleException(e, httpStatus, request);
  verify(responseGenerator).createExceptionResponse(e, httpStatus, false);
}
 
Example 20
Source File: ConditionalDelegatingFilterProxyTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	request = new MockHttpServletRequest();
	request.setContextPath("/context");
	response = new MockHttpServletResponse();
	filterChain = new MockFilterChain();
	delegate = new MockFilter();
}