Java Code Examples for org.springframework.mock.web.MockHttpServletRequest

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest. These examples are extracted from open source projects. 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
public void testDoCreateRoleInvalidToken( ) throws AccessDeniedException
{
    RoleManagementJspBean bean = new RoleManagementJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    final String roleName = getRandomName( );
    request.setParameter( "role_key", roleName );
    request.setParameter( "role_description", roleName );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "admin/rbac/create_role.html" ) + "b" );
    try
    {
        assertFalse(RBACRoleHome.checkExistRole( roleName ) );
        bean.doCreateRole( request );
        fail( "Should have thrown" );
    }
    catch ( AccessDeniedException e )
    {
        assertFalse(RBACRoleHome.checkExistRole( roleName ) );
    }
    finally
    {
        RBACRoleHome.remove( roleName );
    }
}
 
Example 2
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}");
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 3
@Test
public void getFDForDatasetScanStationDataset() throws IOException {
  MockHttpServletRequest req = new MockHttpServletRequest();
  MockHttpServletResponse res = new MockHttpServletResponse();

  String reqPath = "testStationScan/Surface_METAR_20130826_0000.nc";
  FeatureDataset fd = TdsRequestedDataset.getPointDataset(req, res, reqPath);
  if (fd == null) {
    DataRootManager.DataRootMatch match = matcher.findDataRootMatch(reqPath);
    if (match == null) {
      Formatter f = new Formatter();
      matcher.showRoots(f);
      System.out.printf("DataRoots%n%s%n", f);
    }

  }
  assertNotNull(fd);
  assertEquals(FeatureType.STATION, fd.getFeatureType());
}
 
Example 4
Source Project: alchemy   Source File: JWTFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example 5
/**
 * The servlet is supposed to embed the audit id the page is 
 * about. If not, the ForbiddenPageException is caught.
 * @throws Exception 
 */
public void testDisplayPageListWithoutAuditId() throws Exception {
    System.out.println("testDisplayPageListWithoutAuditId");
    
    // The servlet is supposed to embed the webresource id the page is 
    // about. If not, the access denied page is returned
     try {
        instance.displayPageList(
                new MockHttpServletRequest(), 
                new MockHttpServletResponse(), 
                new ExtendedModelMap());
        assertTrue(false);
    } catch (AuditParameterMissingException fbe) {
        assertTrue(true);
    }
}
 
Example 6
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(true);
    context.setResponse(response);

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8");

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertThat(responseBody).isEqualTo("{\"basePath\":\"/service1\"}");
}
 
Example 7
@Test
public void mergeInvokesDefaultRequestPostProcessorFirst() {
	final String ATTR = "ATTR";
	final String EXEPCTED = "override";

	MockHttpServletRequestBuilder defaultBuilder =
			new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar")
			.with(requestAttr(ATTR).value("default"));

	builder
			.with(requestAttr(ATTR).value(EXEPCTED));

	builder.merge(defaultBuilder);

	MockHttpServletRequest request = builder.buildRequest(servletContext);
	request = builder.postProcessRequest(request);

	assertEquals(EXEPCTED, request.getAttribute(ATTR));
}
 
Example 8
Source Project: jsonrpc4j   Source File: JsonRpcServerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetMethod_base64Params() throws Exception {
	EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.addParameter("id", Integer.toString(123));
	request.addParameter("method", "testMethod");
	request.addParameter("params", net.iharder.Base64.encodeBytes("[\"Whir?inaki\"]".getBytes(StandardCharsets.UTF_8)));

	jsonRpcServer.handle(request, response);

	assertTrue("application/json-rpc".equals(response.getContentType()));
	checkSuccessfulResponse(response);
}
 
Example 9
Source Project: ehcache3-samples   Source File: JWTFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example 10
@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 11
public void testDoModifyAccessibilityMode( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, AccessibilityModeAdminUserMenuItemProvider.TEMPLATE ) );

    getUser( request );
    Utils.registerAdminUser( request, _user );
    boolean bAccessibilityMode = _user.getAccessibilityMode( );
    try
    {
        AdminMenuJspBean instance = new AdminMenuJspBean( );
        instance.doModifyAccessibilityMode( request );
        assertEquals( !bAccessibilityMode, _user.getAccessibilityMode( ) );
    }
    finally
    {
        _user.setAccessibilityMode( bAccessibilityMode );
        AdminUserHome.update( _user );
    }
}
 
Example 12
Source Project: glowroot   Source File: JdbcServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    if (connection == null) {
        connection = JDBCDriver.getConnection("jdbc:hsqldb:mem:test", null);
        Statement statement = connection.createStatement();
        try {
            statement.execute("create table employee (name varchar(100))");
            statement.execute("insert into employee (name) values ('john doe')");
            statement.execute("insert into employee (name) values ('jane doe')");
            statement.execute("insert into employee (name) values ('sally doe')");
        } finally {
            statement.close();
        }
    }
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/jdbcservlet");
    MockHttpServletResponse response = new MockHttpServletResponse();
    service((ServletRequest) request, (ServletResponse) response);
}
 
Example 13
@Test
public void testOnAuthenticationFailure() throws ServletException {
    AuthExceptionHandler authExceptionHandler = mock(AuthExceptionHandler.class);

    MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();

    FailedAuthenticationHandler failedAuthenticationHandler = new FailedAuthenticationHandler(authExceptionHandler);

    BadCredentialsException badCredentialsException = new BadCredentialsException("ERROR");
    failedAuthenticationHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, badCredentialsException);

    verify(authExceptionHandler).handleException(
        httpServletRequest,
        httpServletResponse,
        badCredentialsException
    );
}
 
Example 14
Source Project: crnk-framework   Source File: CrnkServletRejectJsonTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptJsonApi() 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", HttpHeaders.JSONAPI_CONTENT_TYPE);

    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 15
@Test
public void testGenericError() {
    MessageService messageService = new YamlMessageService();
    InternalServerErrorController errorController = new InternalServerErrorController(messageService);

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, new Exception("Hello"));
    request.setAttribute(ErrorUtils.ATTR_ERROR_STATUS_CODE, 523);
    request.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, "/uri");

    ResponseEntity<ApiMessageView> response = errorController.error(request);

    assertEquals(523,  response.getStatusCodeValue());
    assertEquals("org.zowe.apiml.common.internalRequestError",  response.getBody().getMessages().get(0).getMessageKey());
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("Hello"));
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("/uri"));
}
 
Example 16
Source Project: herd   Source File: TrustedUserAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTrustedUserFilterNoSpel() throws Exception
{
    // Override configuration.
    Map<String, Object> overrideMap = new HashMap<>();
    overrideMap.put(ConfigurationValue.SECURITY_ENABLED_SPEL_EXPRESSION.getKey(), "");
    modifyPropertySourceInEnvironment(overrideMap);

    try
    {
        // Invalidate user session if exists.
        invalidateApplicationUser(null);

        trustedUserAuthenticationFilter.init(new MockFilterConfig());
        trustedUserAuthenticationFilter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());

        assertNoUserInContext();
    }
    finally
    {
        // Restore the property sources so we don't affect other tests.
        restorePropertySourceInEnvironment();
    }
}
 
Example 17
public void testDoRemoveWorkgroupNoToken( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( "workgroup_key", adminWorkgroup.getKey( ) );

    assertTrue( AdminWorkgroupHome.checkExistWorkgroup( adminWorkgroup.getKey( ) ) );
    try
    {
        bean.doRemoveWorkgroup( request );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertTrue( AdminWorkgroupHome.checkExistWorkgroup( adminWorkgroup.getKey( ) ) );
    }
}
 
Example 18
public void testDoUninstallPluginInvalidToken( ) throws AccessDeniedException
{
    PluginService.getPlugin( PLUGIN_NAME ).install( );
    assertTrue( PluginService.isPluginEnable( PLUGIN_NAME ) );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( "plugin_name", PLUGIN_NAME );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/system/DoUninstallPlugin.jsp" ) + "b" );
    try
    {
        instance.doUninstallPlugin( request, request.getServletContext( ) );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertTrue( PluginService.isPluginEnable( PLUGIN_NAME ) );
    }
}
 
Example 19
Source Project: tutorials   Source File: JWTFilterUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example 20
public void testDoRemoveMailingListInvalidToken( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( "id_mailinglist", Integer.toString( mailingList.getId( ) ) );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/mailinglist/DoRemoveMailingList.jsp" ) + "b" );

    assertNotNull( MailingListHome.findByPrimaryKey( mailingList.getId( ) ) );
    try
    {
        bean.doRemoveMailingList( request );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertNotNull( MailingListHome.findByPrimaryKey( mailingList.getId( ) ) );
    }
}
 
Example 21
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress)
        throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));

    getThrottle().preHandle(request, response, null);

    try {
        authenticationManager.authenticate(badCredentials(username));
    } catch (final AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AuthenticationException");
    return null;
}
 
Example 22
@Test
public void doFilter_with_error_test() throws IOException, ServletException {
    OptionsProvider optionsProvider = mock(OptionsProvider.class);
    doThrow(new RuntimeException()).when(optionsProvider).getAttestationOptions(any(), any(), any());
    OptionsEndpointFilter optionsEndpointFilter = new OptionsEndpointFilter(optionsProvider, objectConverter);
    AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
    optionsEndpointFilter.setTrustResolver(trustResolver);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(OptionsEndpointFilter.FILTER_URL);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();

    optionsEndpointFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
 
Example 23
@Test
public void testKatharsisMatchingException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks-matching-exception");
	request.setRequestURI("/api/matching-exception");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();
	assertTrue("Response should not be returned for non matching resource type", StringUtils.isBlank(responseContent));
	assertEquals(404, response.getStatus());

}
 
Example 24
private void testDoModifyAttribute( AttributeType type ) throws PasswordResetException, AccessDeniedException, InstantiationException,
        IllegalAccessException, ClassNotFoundException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    IAttribute attribute = _attributes.get( type );
    assertNotNull( attribute );
    request.setParameter( "id_attribute", Integer.toString( attribute.getIdAttribute( ) ) );
    String strTitle = getRandomName( );
    request.setParameter( "title", strTitle );
    request.setParameter( "width", "5" );

    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, attribute.getTemplateModifyAttribute( ) ) );

    Utils.registerAdminUserWithRigth( request, new AdminUser( ), "CORE_USERS_MANAGEMENT" );
    AttributeJspBean instance = new AttributeJspBean( );
    instance.init( request, "CORE_USERS_MANAGEMENT" );

    instance.doModifyAttribute( request );
    IAttribute stored = AttributeService.getInstance( ).getAttributeWithoutFields( attribute.getIdAttribute( ), Locale.FRANCE );
    assertNotNull( stored );
    assertEquals( strTitle, stored.getTitle( ) );
}
 
Example 25
@Override
protected void setUp() throws Exception {
    super.setUp();
    this.configManager = (ConfigInterface) this.getService(SystemConstants.BASE_CONFIG_MANAGER);
    IPageManager pageManager = (IPageManager) this.getService(SystemConstants.PAGE_MANAGER);
    ILangManager langManager = (ILangManager) this.getService(SystemConstants.LANGUAGE_MANAGER);
    RequestContext reqCtx = (RequestContext) super.getRequest().getAttribute(RequestContext.REQCTX);
    reqCtx.addExtraParam(SystemConstants.EXTRAPAR_CURRENT_PAGE, pageManager.getOnlineRoot());
    reqCtx.addExtraParam(SystemConstants.EXTRAPAR_CURRENT_LANG, langManager.getDefaultLang());
    reqCtx.addExtraParam(SystemConstants.EXTRAPAR_CURRENT_FRAME, 0);
    ((MockHttpServletRequest) super.getRequest()).setScheme("https");
    ((MockHttpServletRequest) super.getRequest()).setServerName("www.myproduct.com");
    ((MockHttpServletRequest) super.getRequest()).addHeader("Host", "www.myproduct.com");
    ((MockHttpServletRequest) super.getRequest()).setContextPath("/entando");
}
 
Example 26
Source Project: tutorials   Source File: KeycloakConfigurationIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    servletRequest = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest));
    servletRequest.setUserPrincipal(keycloakPrincipal);
    when(keycloakPrincipal.getKeycloakSecurityContext()).thenReturn(keycloakSecurityContext);
}
 
Example 27
Source Project: katharsis-framework   Source File: KatharsisServletTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void onCollectionRequestWithParamsGetShouldReturnCollection() 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", "*/*");
	request.addParameter("filter[name]", "John");
	request.setQueryString(URLEncoder.encode("filter[name]", StandardCharsets.UTF_8.name()) + "=John");

	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 28
public void testDoRemovePageNotANumber( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( Parameters.PAGE_ID, "foo" );
    _bean.doRemovePage( request );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( AdminMessage.TYPE_ERROR, message.getType( ) );
}
 
Example 29
@Test
public void cookie() {
	Cookie cookie1 = new Cookie("foo", "bar");
	Cookie cookie2 = new Cookie("baz", "qux");
	this.builder.cookie(cookie1, cookie2);

	MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
	Cookie[] cookies = request.getCookies();

	assertEquals(2, cookies.length);
	assertEquals("foo", cookies[0].getName());
	assertEquals("bar", cookies[0].getValue());
	assertEquals("baz", cookies[1].getName());
	assertEquals("qux", cookies[1].getValue());
}
 
Example 30
public void testDoUnAssignUserNoToken( ) throws AccessDeniedException
{
    RBACRole role = new RBACRole( );
    role.setKey( getRandomName( ) );
    role.setDescription( role.getKey( ) );
    RBACRoleHome.create( role );
    AdminUser user = AdminUserHome.findUserByLogin( "admin" );
    int userId = user.getUserId( );
    AdminUserHome.createRoleForUser( userId, role.getKey( ) );
    RoleManagementJspBean bean = new RoleManagementJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( "role_key", role.getKey( ) );
    request.setParameter( "id_user", Integer.toString( userId ) );
    request.setParameter( "anchor", "anchor" );
    try
    {
        assertTrue( AdminUserHome.hasRole( user, role.getKey( ) ) );
        bean.doUnAssignUser( request );
        fail( "Should have thrown" );
    }
    catch ( AccessDeniedException e )
    {
        assertTrue( AdminUserHome.hasRole( user, role.getKey( ) ) );
    }
    finally
    {
        AdminUserHome.removeRoleForUser( userId, role.getKey( ) );
        RBACRoleHome.remove( role.getKey( ) );
    }
}