@ExceptionHandler public RedirectView handle(PostMovedException moved) { RedirectView redirect = new RedirectView(); redirect.setStatusCode(HttpStatus.MOVED_PERMANENTLY); redirect.setUrl("/blog/" + moved.getPublicSlug()); return redirect; }
@Test public void updateTargetUrlWithContextLoader() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class); MockServletContext servletContext = new MockServletContext(); ContextLoader contextLoader = new ContextLoader(wac); contextLoader.initWebApplicationContext(servletContext); try { RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); wac.getBean(RequestDataValueProcessorWrapper.class) .setRequestDataValueProcessor(mockProcessor); RedirectView rv = new RedirectView(); rv.setUrl("/path"); MockHttpServletRequest request = createRequest(); HttpServletResponse response = new MockHttpServletResponse(); given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123"); rv.render(new ModelMap(), request, response); verify(mockProcessor).processUrl(request, "/path"); } finally { contextLoader.closeWebApplicationContext(servletContext); } }
@Test public void explicitStatusCodeHttp10() throws Exception { RedirectView rv = new RedirectView(); rv.setUrl("http://url.somewhere.com"); rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY); MockHttpServletRequest request = createRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); rv.render(new HashMap<String, Object>(), request, response); assertEquals(301, response.getStatus()); assertEquals("http://url.somewhere.com", response.getHeader("Location")); }
@Test public void attributeStatusCodeHttp11() throws Exception { RedirectView rv = new RedirectView(); rv.setUrl("http://url.somewhere.com"); rv.setHttp10Compatible(false); MockHttpServletRequest request = createRequest(); request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.CREATED); MockHttpServletResponse response = new MockHttpServletResponse(); rv.render(new HashMap<String, Object>(), request, response); assertEquals(201, response.getStatus()); assertEquals("http://url.somewhere.com", response.getHeader("Location")); }
/** * Resolves the view from the advanced search form, from search form under the menu in start page, * from categories or from tags AND from links to next/previous page and so on. * * @param advancedSearchData * @param bindingResult * @param model * @return * @throws UnsupportedEncodingException */ @RequestMapping(value = "/advanced_search/results", method = RequestMethod.GET) public ModelAndView getAdvancedSearchResults( @ModelAttribute("advancedSearchData") SearchData advancedSearchData, BindingResult bindingResult, Model model, HttpServletRequest httpRequest) throws UnsupportedEncodingException { LOG.debug( "------ getAdvancedSearchResults : get SEARCH RESULTS based on advanced search form -----"); if (advancedSearchData.getSearchTarget() == null) advancedSearchData.setSearchTarget("episodes"); SearchResult searchResult = searchService.getResultsForSearchCriteria(advancedSearchData); String redirectUrl = null; String tilesDef = null; ModelAndView mv; // no results found if (searchResult.getResults().isEmpty()) { bindingResult.rejectValue("queryText", "notFound", "not found"); redirectUrl = "/search/advanced_search?noResultsFound=true"; } else if (searchResult.getResults().size() > 1) { String query = httpRequest.getQueryString(); query = query.substring(0, query.lastIndexOf("¤tPage=")); model.addAttribute("queryString", query.replaceAll("&", "&")); model.addAttribute("advancedSearchResult", searchResult); tilesDef = "search_results_def"; } else { // exactly one result found (either podcast or episode), redirect to it redirectUrl = searchResult.getResults().get(0).getRelativeLink(); } if (tilesDef != null) { mv = new ModelAndView(); mv.setViewName(tilesDef); } else { // must be a redirect RedirectView rv = new RedirectView(); rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY); rv.setUrl(redirectUrl); mv = new ModelAndView(rv); } return mv; }
@Test public void http11() throws Exception { RedirectView rv = new RedirectView(); rv.setUrl("http://url.somewhere.com"); rv.setHttp10Compatible(false); MockHttpServletRequest request = createRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); request.setAttribute( DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE, new SessionFlashMapManager()); rv.render(new HashMap<String, Object>(), request, response); assertEquals(303, response.getStatus()); assertEquals("http://url.somewhere.com", response.getHeader("Location")); }
@RequestMapping("/tracker.jsp") public View trackerOldUrl( @RequestParam(value = "filter", defaultValue = "all") String filterAction) throws UnsupportedEncodingException { RedirectView redirectView = new RedirectView("/tracker/"); redirectView.setExposeModelAttributes(false); if (filterValues.contains(filterAction) && !filterAction.equals("all")) { redirectView.setUrl("/tracker/?filter=" + URLEncoder.encode(filterAction, "UTF-8")); } return redirectView; }
@Test public void flashMap() throws Exception { RedirectView rv = new RedirectView(); rv.setUrl("http://url.somewhere.com/path"); rv.setHttp10Compatible(false); MockHttpServletRequest request = createRequest(); HttpServletResponse response = new MockHttpServletResponse(); FlashMap flashMap = new FlashMap(); flashMap.put("successMessage", "yay!"); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, flashMap); ModelMap model = new ModelMap("id", "1"); rv.render(model, request, response); assertEquals(303, response.getStatus()); assertEquals("http://url.somewhere.com/path?id=1", response.getHeader("Location")); assertEquals("/path", flashMap.getTargetRequestPath()); assertEquals(model, flashMap.getTargetRequestParams().toSingleValueMap()); }
@Test public void updateTargetUrl() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class); wac.setServletContext(new MockServletContext()); wac.refresh(); RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor); RedirectView rv = new RedirectView(); rv.setApplicationContext(wac); // Init RedirectView with WebAppCxt rv.setUrl("/path"); MockHttpServletRequest request = createRequest(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); HttpServletResponse response = new MockHttpServletResponse(); given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123"); rv.render(new ModelMap(), request, response); verify(mockProcessor).processUrl(request, "/path"); }
@RequestMapping public View restorePassword(HttpServletRequest request) throws IOException { RedirectView rv = new RedirectView(); Map<String, String> attributes = new HashMap<String, String>(); EmailExtractedData extractedData = null; try { extractedData = extractEmailData(request); } catch (CryptoException cryptoEx) { log.error("Could not extract data from URL", cryptoEx); cryptoEx.printStackTrace(); attributes.put(FlowsConstatns.ERR_HEADER, "URL IS INVALID"); attributes.put( FlowsConstatns.ERR_MSG, "URL IS INVALID" + " exception message: " + cryptoEx.getMessage()); // adding attributes to the redirect return value: rv.setAttributesMap(attributes); rv.setUrl("login/error.jsp"); return rv; } if (extractedData.expired) { log.error("user " + extractedData.userEmail + " tried to use an expired link"); attributes.put(FlowsConstatns.ERR_HEADER, "URL IS EXPIRED"); attributes.put(FlowsConstatns.ERR_MSG, "URL IS Expired"); // adding attributes to the redirect return value: rv.setAttributesMap(attributes); rv.setUrl("login/error.jsp"); return rv; } else { // we send also the signed-email, so no one can change the email and set-new-password for // another user: String encodedEmailAndTimestamp = FlowsUtil.getParamsUserAndTimestamp(request); Date lastChange = processor.getPasswordLastChangeDate(extractedData.userEmail); Date emailCreationDate = extractedData.emailCreationDate; request.getSession().invalidate(); request.getSession(true); SecurityContextHolder.getContext().setAuthentication(null); String redirectUri = extractedData.redirectUri; // if password was changed AFTER the email creation (that is AFTER the user initiated "4got // password" flow) - // it means the request is irrelevant if (lastChange.after(emailCreationDate)) { log.error( "user " + extractedData.userEmail + " tried to use an expired link: password was already changed AFTER the timestamp of the link"); attributes.put(FlowsConstatns.ERR_HEADER, "Cannot set new password"); attributes.put( FlowsConstatns.ERR_MSG, "Cannot set new password, because it was set AFTER the link was created."); // adding attributes to the redirect return value: rv.setAttributesMap(attributes); rv.setUrl("login/error.jsp"); return rv; } // String encoded = URLEncoder.encode(redirectUri, "utf-8"); //returns something like: // https%3A%2F%2Foauthsubdomain.ohad.sealdoc // String escaped = StringEscapeUtils.escapeHtml4( redirectUri ); // after all the checks, all look good (link not expired, etc). so show the user the "set new // password" page. // if "secret question" is implemented, here you get the secret Q and show the user the screen // to answer it. then // check the answer, etc. // attributes.put(FlowsConstatns.ERR_HEADER, "URL IS EXPIRED"); // attributes.put(FlowsConstatns.ERR_MSG, "URL IS Expired"); // adding attributes to the redirect return value: // rv.setAttributesMap(attributes); rv.setUrl( "login/setNewPassword.jsp" + "?" + FlowsConstatns.HASH_PARAM_NAME + "=" + encodedEmailAndTimestamp); } return rv; }