Java Code Examples for org.springframework.web.servlet.ModelAndView#getView()

The following examples show how to use org.springframework.web.servlet.ModelAndView#getView() . 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
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) {
	HttpSession session = request.getSession();

	if (session != null) {
		Message message = (Message) session.getAttribute(Message.ATTRIBUTE_KEY);
		if (message != null && !mav.getModelMap().containsKey(Message.ATTRIBUTE_KEY)) {
			mav.addObject(Message.ATTRIBUTE_KEY, message);
		}

		boolean shouldRemove = true;
		if (mav.hasView() && mav.getView() instanceof RedirectView) {
			shouldRemove = false;
		}
		if (mav.getViewName() != null && mav.getViewName().startsWith("redirect:")) {
			shouldRemove = false;
		}

		if (shouldRemove) {
			session.removeAttribute(Message.ATTRIBUTE_KEY);
		}
	}
}
 
Example 2
Source Project: web-sso   File: LogoutActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutWithCredentialAndService() throws IOException {
	String servce  = "http://app.com/logoutSucess.do";
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setParameter(WebConstants.SERVICE_PARAM_NAME, servce);
	MockHttpServletResponse response = new MockHttpServletResponse();
	HttpSession session = request.getSession();
	CredentialResolver credentialResolver = Mockito.mock(CredentialResolver.class);
	logoutAction.setCredentialResolver(credentialResolver);
	Ki4soService ki4soService = Mockito.mock(Ki4soService.class);
	logoutAction.setKi4soService(ki4soService);
	
	//测试存在cookie,登出后要清除cookie值,但是service参数的值是null的情况。
	request.setCookies(new Cookie(WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY, "dddsd"));
	
	ModelAndView mv = logoutAction.logout(request, response,session);
	Assert.assertEquals(1, response.getCookies().length);
	Assert.assertEquals(0, response.getCookies()[0].getMaxAge());
	RedirectView view = (RedirectView) mv.getView();
	Assert.assertEquals(servce, view.getUrl());
}
 
Example 3
Source Project: onetwo   File: MvcViewRender.java    License: Apache License 2.0 6 votes vote down vote up
public void doRender(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
	if(localeResolver!=null){
		Locale locale = this.localeResolver.resolveLocale(request);
		response.setLocale(locale);
	}
	
	View view;
	if (mv.isReference()) {
		view = resolveViewName(mv.getViewName(), mv.getModel(), response.getLocale(), request);
		if (view == null) {
			throw new BaseException("Could not resolve view with name '" + mv.getViewName() + "' in '" + getClass().getSimpleName() + "'");
		}
	}
	else {
		view = mv.getView();
		if (view == null) {
			throw new BaseException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in '" + getClass().getSimpleName() + "'");
		}
	}

	if (mv.getStatus() != null) {
		response.setStatus(mv.getStatus().value());
	}
	view.render(mv.getModel(), request, response);
}
 
Example 4
Source Project: gocd   File: ArtifactsControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnHttpErrorCodeWhenChecksumFileSaveFails() throws Exception {
    File artifactFile = new File("junk");
    JobIdentifier jobIdentifier = new JobIdentifier("pipeline-1", 1, "1", "stage-1", "2", "job-1", 122l);
    when(restfulService.findJob("pipeline-1", "1", "stage-1", "2", "job-1", 122l)).thenReturn(jobIdentifier);
    when(artifactService.findArtifact(any(JobIdentifier.class), eq("some-path"))).thenReturn(artifactFile);
    when(artifactService.saveFile(any(File.class), any(InputStream.class), eq(false), eq(1))).thenReturn(true);
    when(artifactService.saveOrAppendFile(any(File.class), any(InputStream.class))).thenReturn(false);

    MockMultipartHttpServletRequest mockMultipartHttpServletRequest = new MockMultipartHttpServletRequest();
    mockMultipartHttpServletRequest.addFile(new MockMultipartFile(REGULAR_MULTIPART_FILENAME, "content".getBytes()));
    mockMultipartHttpServletRequest.addFile(new MockMultipartFile(CHECKSUM_MULTIPART_FILENAME, "checksum-content".getBytes()));

    ModelAndView modelAndView = artifactsController.postArtifact("pipeline-1", "1", "stage-1", "2", "job-1", 122L, "some-path", 1, mockMultipartHttpServletRequest);


    ResponseCodeView view = (ResponseCodeView) modelAndView.getView();
    assertThat(view.getStatusCode(), is(SC_INTERNAL_SERVER_ERROR));
    assertThat(view.getContent(), is("Error saving checksum file for the artifact at path 'some-path'"));
}
 
Example 5
@Test
public void shouldReturnBuildOutputAsPlainText() throws Exception {
    String firstLine = "Chris sucks.\n";
    String secondLine = "Build succeeded.";
    prepareConsoleOut(firstLine + secondLine + "\n");
    Stage firstStage = pipeline.getFirstStage();
    long startLineNumber = 1L;
    ModelAndView view = artifactsController.consoleout(pipeline.getName(), pipeline.getLabel(),
            firstStage.getName(),
            "build", String.valueOf(firstStage.getCounter()), startLineNumber);

    assertThat(view.getView(), is(instanceOf(ConsoleOutView.class)));

    HttpServletResponse response = mock(HttpServletResponse.class);
    ResponseOutput output = new ResponseOutput();
    when(response.getWriter()).thenReturn(output.getWriter());
    ConsoleOutView consoleOutView = (ConsoleOutView) view.getView();
    consoleOutView.render(mock(Map.class), mock(HttpServletRequest.class), response);

    assertEquals("Build succeeded.\n", output.getOutput());
}
 
Example 6
@Test
public void shouldStartAtBeginningWhenNoStartParameterIsGiven() throws Exception {
    String firstLine = "Chris sucks.";
    String secondLine = "Build succeeded.";
    prepareConsoleOut(firstLine + "\n" + secondLine + "\n");
    Stage firstStage = pipeline.getFirstStage();
    ModelAndView view = artifactsController.consoleout(pipeline.getName(), pipeline.getLabel(),
            firstStage.getName(),
            "build", String.valueOf(firstStage.getCounter()), null);

    assertThat(view.getView(), is(instanceOf(ConsoleOutView.class)));

    HttpServletResponse response = mock(HttpServletResponse.class);
    ResponseOutput output = new ResponseOutput();
    when(response.getWriter()).thenReturn(output.getWriter());
    ConsoleOutView consoleOutView = (ConsoleOutView) view.getView();
    consoleOutView.render(mock(Map.class), mock(HttpServletRequest.class), response);

    assertEquals("Chris sucks.\nBuild succeeded.\n", output.getOutput());
}
 
Example 7
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView && ((SmartView) view).isRedirectView()) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	mavContainer.setStatus(mav.getStatus());
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 8
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView && ((SmartView) view).isRedirectView()) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	mavContainer.setStatus(mav.getStatus());
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 9
@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 10
@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 11
@Test
public void testOK() 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<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));
    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 12
@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 13
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView) {
			if (((SmartView) view).isRedirectView()) {
				mavContainer.setRedirectModelScenario(true);
			}
		}
	}
	mavContainer.setStatus(mav.getStatus());
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 14
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView) {
			if (((SmartView) view).isRedirectView()) {
				mavContainer.setRedirectModelScenario(true);
			}
		}
	}
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 15
@Test
@Ignore
public final void testHandle() {
	try
	{
		MockHttpServletRequest aReq = new MockHttpServletRequest();
		MockHttpServletResponse aResp = new MockHttpServletResponse(); 
		LiveContentRetrieverCommand aCmd = new LiveContentRetrieverCommand();
		
		aCmd.setUrl("http://www.bl.uk");
		aCmd.setContentFileName("test.html");
		
		BindException aErrors = new BindException(aCmd, "LiveContentRetrieverCommand");
		
		ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors);
		assertTrue(mav != null);
		assertEquals(mav.getModel().size(), 0);
		assertTrue(mav.getView() instanceof AttachmentView);
		AttachmentView view = (AttachmentView)mav.getView();
		
		view.render(null, aReq, aResp);
		
		assertTrue(aResp.getHeader("Content-Disposition").toString().endsWith("test.html"));
		assertTrue(aResp.getContentAsString().contains("British Library"));
		
		assertFalse(aErrors.hasErrors());
	}
	catch(Exception e)
	{
		fail(e.getMessage());
	}
}
 
Example 16
@Override
public void postHandle(
		HttpServletRequest request,
		HttpServletResponse response,
		Object handler,
		ModelAndView mv)
		throws Exception {
	if (mv == null) return;
	if (mv.getView() instanceof RedirectView) return;
	if (mv.getViewName().startsWith("redirect:")) return;

	Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
	mv.addObject("BLOG", blog);

	List<String> languages = new ArrayList<>();
	if (blog != null) {
		for (BlogLanguage blogLanguage : blog.getLanguages()) {
			languages.add(blogLanguage.getLanguage());
		}
	}

	String currentLanguage = LocaleContextHolder.getLocale().getLanguage();

	mv.addObject("LANGUAGES", languages.toArray(new String[languages.size()]));
	mv.addObject("LANGUAGE_LINKS", buildLanguageLinks(currentLanguage, languages, request));

	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	AuthorizedUser authorizedUser = null;
	if (authentication != null && authentication.getPrincipal() instanceof AuthorizedUser) {
		authorizedUser = (AuthorizedUser) authentication.getPrincipal();
	}
	mv.addObject("USER", authorizedUser);

	mv.addObject("WEBSITE_TITLE", blog != null ? blog.getTitle(currentLanguage) : null);
	mv.addObject("WEBSITE_LINK", buildGuestLink());
	mv.addObject("WEBSITE_PATH", buildGuestPath(currentLanguage, languages));

	mv.addObject("ADMIN_LINK", buildAdminLink());
	mv.addObject("ADMIN_PATH", buildAdminPath(currentLanguage));
}
 
Example 17
Source Project: gocd   File: ArtifactsControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnBadRequestIfRequiredHeadersAreMissingOnACreateArtifactRequest() throws Exception {
    MultipartHttpServletRequest multipartHttpServletRequest = new MockMultipartHttpServletRequest();

    when(systemEnvironment.isApiSafeModeEnabled()).thenReturn(true);
    ModelAndView modelAndView = artifactsController.postArtifact("pipeline", "invalid-label", "stage", "stage-counter", "job-name", 3L, "file-path", 3, multipartHttpServletRequest);
    ResponseCodeView codeView = (ResponseCodeView) modelAndView.getView();

    assertThat(codeView.getStatusCode(), is(HttpServletResponse.SC_BAD_REQUEST));
    assertThat(codeView.getContent(), is("Missing required header 'Confirm'"));

}
 
Example 18
Source Project: tutorials   File: UserInterceptor.java    License: MIT License 5 votes vote down vote up
public static boolean isRedirectView(ModelAndView mv) {

        String viewName = mv.getViewName();
        if (viewName.startsWith("redirect:/")) {
            return true;
        }

        View view = mv.getView();
        return (view != null && view instanceof SmartView && ((SmartView) view).isRedirectView());
    }