Java Code Examples for org.springframework.mock.web.mockhttpservletrequest#setServerPort()

The following examples show how to use org.springframework.mock.web.mockhttpservletrequest#setServerPort() . 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: SwaggerControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testSwaggerHostAddsPort() {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setScheme("http");
  request.setMethod("GET");
  request.setServletPath("/plugin/swagger/");
  request.setServerPort(8080);
  RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

  when(metaDataService.getEntityTypes()).thenReturn(Stream.empty());

  assertEquals("view-swagger", swaggerController.swagger(model, response));

  verify(model).addAttribute("scheme", "http");
  verify(model).addAttribute("host", "localhost:8080");
}
 
Example 2
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 3
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 testReverseProxyWithModuleBase() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();

	// set mock request in context holder
	MockHttpServletRequest mockRequest = new MockHttpServletRequest();
	mockRequest.setScheme("http");
	mockRequest.setServerName("myhost");
	mockRequest.setServerPort(80);
	mockRequest.setContextPath("/test");
	mockRequest.addHeader(X_FORWARD_HOST_HEADER, "geomajas.org");
	mockRequest.addHeader(X_GWT_MODULE_HEADER, "http://geomajas.org/app/Module");
	ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
	RequestContextHolder.setRequestAttributes(attributes);
	Assert.assertEquals("http://geomajas.org/app/d/", adus.getDispatcherUrl());

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example 4
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 testLocalizeConfigured() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();
	adus.setLocalDispatcherUrl("http://my:8080/local/dispatcher/");

	// 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://my:8080/local/dispatcher/something", adus.localize("http://geomajas.org/test/d/something"));

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example 5
Source File: RequestProcessorTest.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
private MockHttpServletRequest getRequest(Map<String, Object> parameters) {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme("https");
    request.setServerName("me.auth0.com");
    request.setServerPort(80);
    request.setRequestURI("/callback");
    request.setParameters(parameters);
    return request;
}
 
Example 6
Source File: HtmlUnitRequestBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void ports(UriComponents uriComponents, MockHttpServletRequest request) {
	int serverPort = uriComponents.getPort();
	request.setServerPort(serverPort);
	if (serverPort == -1) {
		int portConnection = this.webRequest.getUrl().getDefaultPort();
		request.setLocalPort(serverPort);
		request.setRemotePort(portConnection);
	}
	else {
		request.setRemotePort(serverPort);
	}
}
 
Example 7
Source File: PutMethodTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes WebDAV method for testing
 * <p>
 * Sets content to request from a test file
 * 
 * @param methodName Method to prepare, should be initialized (PUT, LOCK, UNLOCK are supported)
 * @param fileName the name of the file set to the context, can be used with path, i.e. "path/to/file/fileName.txt"
 * @param content If <b>not null</b> adds test content to the request
 * @param headers to set to request, can be null
 * @throws Exception
 */
private void executeMethod(String methodName, String fileName, byte[] content, Map<String, String> headers) throws Exception
{
    if (methodName == WebDAV.METHOD_PUT)
        method = new PutMethod();
    else if (methodName == WebDAV.METHOD_LOCK)
        method = new LockMethod();
    else if (methodName == WebDAV.METHOD_UNLOCK)
        method = new UnlockMethod();
    if (method != null)
    {
        request = new MockHttpServletRequest(methodName, "/alfresco/webdav/" + fileName);
        response = new MockHttpServletResponse();
        request.setServerPort(8080);
        request.setServletPath("/webdav");
        if (content != null)
        {
            request.setContent(content);
        }

        if (headers != null && !headers.isEmpty())
        {
            for (String key : headers.keySet())
            {
                request.addHeader(key, headers.get(key));
            }
        }

        method.setDetails(request, response, webDAVHelper, companyHomeNodeRef);

        method.execute();
    }
}
 
Example 8
Source File: WebDAVonContentUpdateTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes WebDAV method for testing
 * <p>
 * Sets content to request from a test file
 * 
 * @param methodName Method name to prepare, should be initialized (PUT, LOCK, UNLOCK are supported)
 * @param fileName the name of the file set to the context, can be used with path, i.e. "path/to/file/fileName.txt"
 * @param content If <b>not null</b> adds test content to the request
 * @param headers to set to request, can be null
 * @throws Exception
 */
private void executeMethod(String methodName, String fileName, byte[] content, Map<String, String> headers) throws Exception
{
    if (methodName == WebDAV.METHOD_PUT)
        method = new PutMethod();
    else if (methodName == WebDAV.METHOD_LOCK)
        method = new LockMethod();
    else if (methodName == WebDAV.METHOD_UNLOCK)
        method = new UnlockMethod();
    if (method != null)
    {
        request = new MockHttpServletRequest(methodName, "/alfresco/webdav/" + fileName);
        response = new MockHttpServletResponse();
        request.setServerPort(8080);
        request.setServletPath("/webdav");
        if (content != null)
        {
            request.setContent(content);
        }

        if (headers != null && !headers.isEmpty())
        {
            for (String key : headers.keySet())
            {
                request.addHeader(key, headers.get(key));
            }
        }

        method.setDetails(request, response, webDAVHelper, companyHomeNodeRef);

        method.execute();
    }
}
 
Example 9
Source File: ExplorerHandlerTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private void testHandle(String scheme, int port, String expectedLocation) throws Exception {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setScheme(scheme);
  request.setServerName("localhost");
  request.setServerPort(port);
  request.setRequestURI("/_ah/api/explorer/");
  MockHttpServletResponse response = new MockHttpServletResponse();
  ExplorerHandler handler = new ExplorerHandler();
  EndpointsContext context = new EndpointsContext("GET", "explorer", request, response, true);
  handler.handle(context);

  assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
  assertThat(response.getHeader("Location")).isEqualTo(expectedLocation);
}
 
Example 10
Source File: ServletNettyChannelHandler.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
private MockHttpServletRequest createHttpServletRequest(FullHttpRequest fullHttpReq) {
	UriComponents uriComponents = UriComponentsBuilder.fromUriString(fullHttpReq.getUri()).build();

	MockHttpServletRequest servletRequest = new MockHttpServletRequest(this.servletContext);
	servletRequest.setRequestURI(uriComponents.getPath());
	servletRequest.setPathInfo(uriComponents.getPath());
	servletRequest.setMethod(fullHttpReq.getMethod().name());
	servletRequest.setCharacterEncoding(UTF_8);

	if (uriComponents.getScheme() != null) {
		servletRequest.setScheme(uriComponents.getScheme());
	}
	if (uriComponents.getHost() != null) {
		servletRequest.setServerName(uriComponents.getHost());
	}
	if (uriComponents.getPort() != -1) {
		servletRequest.setServerPort(uriComponents.getPort());
	}
	
	copyHttpHeaders(fullHttpReq, servletRequest);
	copyHttpBodyData(fullHttpReq, servletRequest);
	
	copyQueryParams(uriComponents, servletRequest);
	copyToServletCookie(fullHttpReq, servletRequest);
	
	return servletRequest;
}
 
Example 11
Source File: PasswordResetterImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testResetPassword() {
  String emailAddress = "[email protected]";

  User user = mock(User.class);
  when(user.getEmail()).thenReturn(emailAddress);

  when(userService.getUserByEmail(emailAddress)).thenReturn(user);

  String token = "MyToken";
  when(passwordResetTokenRepository.createToken(user)).thenReturn(token);

  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setScheme("http");
  request.setServerName("my.host.org");
  request.setServerPort(80);
  RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

  String appTitle = "MyAppTitle";
  when(appSettings.getTitle()).thenReturn(appTitle);

  passwordResetServiceImpl.resetPassword(emailAddress);

  SimpleMailMessage simpleMessage = new SimpleMailMessage();
  simpleMessage.setTo(emailAddress);
  simpleMessage.setSubject("Password reset on MyAppTitle");
  simpleMessage.setText(
      "Hello,\n"
          + "\n"
          + "You are receiving this email because we received a password reset request for your account.\n"
          + "\n"
          + "http://my.host.org/account/password/change?username&token=MyToken\n"
          + "\n"
          + "If you did not request a password reset, you can safely ignore this email.");
  verify(mailSender).send(simpleMessage);
}
 
Example 12
Source File: ServletRequestContextTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	servletContext = Mockito.mock(ServletContext.class);

	servletRequest = new MockHttpServletRequest(servletContext);
	servletRequest.setMethod("GET");
	servletRequest.setContextPath("");
	servletRequest.setServerPort(1234);
	servletRequest.setRequestURI("/api/tasks/");
	servletRequest.setServerName("test");

	servletResponse = new MockHttpServletResponse();
}
 
Example 13
Source File: OAuth20AuthorizeControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.STATE, STATE);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<RegisteredService>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    assertEquals(
            OAuthUtils.addParameter(CAS_URL, "service", CAS_URL + CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL),
            redirectView.getUrl());
}
 
Example 14
Source File: EndpointsPeerAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static MockHttpServletRequest createRequest(
    String host, int port, String servletPath, String contextPath, String queryString) {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.addHeader("Host", host);
  request.setServerName(host);
  request.setServerPort(port);
  request.setServletPath(servletPath);
  request.setQueryString(queryString);
  request.setContextPath(contextPath);
  return request;
}
 
Example 15
Source File: OAuth20AuthorizeControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.STATE, STATE);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    
    final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    reqSvc.setServerName(CAS_SERVER);
    reqSvc.setServerPort(CAS_PORT);
    reqSvc.setScheme(CAS_SCHEME);
    final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString()));
    final URL url2 = new URL(redirectView.getUrl());

    assertEquals(url, url2);
}
 
Example 16
Source File: OAuth20AuthorizeControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    
    final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    reqSvc.setServerName(CAS_SERVER);
    reqSvc.setServerPort(CAS_PORT);
    reqSvc.setScheme(CAS_SCHEME);
    final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString()));
    final URL url2 = new URL(redirectView.getUrl());

    assertEquals(url, url2);
}
 
Example 17
Source File: ResponseLinksMapperTest.java    From moserp with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(){
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setRequestURI("/api/products");
    servletRequest.setServerPort(8080);
    RequestContextHolder.setRequestAttributes(new ServletWebRequest(servletRequest));
}
 
Example 18
Source File: WebAuthnRegistrationRequestValidatorTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void validate_test() {
    WebAuthnRegistrationRequestValidator target = new WebAuthnRegistrationRequestValidator(
            webAuthnManager, serverPropertyProvider
    );

    ServerProperty serverProperty = mock(ServerProperty.class);
    when(serverPropertyProvider.provide(any())).thenReturn(serverProperty);

    CollectedClientData collectedClientData = mock(CollectedClientData.class);
    AttestationObject attestationObject = mock(AttestationObject.class);
    AuthenticationExtensionsClientOutputs<RegistrationExtensionClientOutput<?>> clientExtensionOutputs = new AuthenticationExtensionsClientOutputs<>();
    when(webAuthnManager.validate(any(RegistrationRequest.class), any(RegistrationParameters.class))).thenReturn(
            new RegistrationData(attestationObject, null, collectedClientData, null, clientExtensionOutputs, null));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.setScheme("https");
    mockHttpServletRequest.setServerName("example.com");
    mockHttpServletRequest.setServerPort(443);
    String clientDataBase64 = "clientDataBase64";
    String attestationObjectBase64 = "attestationObjectBase64";
    Set<String> transports = Collections.emptySet();
    String clientExtensionsJSON = "clientExtensionsJSON";

    target.validate(mockHttpServletRequest, clientDataBase64, attestationObjectBase64, transports, clientExtensionsJSON);

    ArgumentCaptor<RegistrationRequest> registrationRequestArgumentCaptor = ArgumentCaptor.forClass(RegistrationRequest.class);
    ArgumentCaptor<RegistrationParameters> registrationParametersArgumentCaptor = ArgumentCaptor.forClass(RegistrationParameters.class);
    verify(webAuthnManager).validate(registrationRequestArgumentCaptor.capture(), registrationParametersArgumentCaptor.capture());
    RegistrationRequest registrationRequest = registrationRequestArgumentCaptor.getValue();
    RegistrationParameters registrationParameters = registrationParametersArgumentCaptor.getValue();

    assertThat(registrationRequest.getClientDataJSON()).isEqualTo(Base64UrlUtil.decode(clientDataBase64));
    assertThat(registrationRequest.getAttestationObject()).isEqualTo(Base64UrlUtil.decode(attestationObjectBase64));
    assertThat(registrationRequest.getClientExtensionsJSON()).isEqualTo(clientExtensionsJSON);
    assertThat(registrationParameters.getServerProperty()).isEqualTo(serverProperty);
    assertThat(registrationParameters.getExpectedExtensionIds()).isEqualTo(target.getExpectedRegistrationExtensionIds());
}
 
Example 19
Source File: ProxyingDiscoveryServiceTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static MockHttpServletRequest createRequest(String apiPath) {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setRequestURI(BASE_PATH + apiPath);
  request.setServerName(SERVER_NAME);
  request.setServerPort(SERVER_PORT);
  return request;
}
 
Example 20
Source File: ApiProxyHandlerTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private void testWithServletPath(String servletPath) throws Exception {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setServerName("localhost");
  request.setServerPort(8080);
  request.setServletPath(servletPath);
  MockHttpServletResponse response = new MockHttpServletResponse();
  ApiProxyHandler handler = new ApiProxyHandler();
  EndpointsContext context =
      new EndpointsContext("GET", "static/proxy.html", request, response, true);

  handler.handle(context);

  assertThat(response.getContentAsString()).contains("googleapis.server.init()");
}