@GetMapping("/signup") public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) { String providerId = null; try { Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest); providerId = connection.getKey().getProviderId(); socialService.createSocialUser(connection, langKey.replace("\"", "")); return redirect(URIBuilder .fromUri(TenantUtil.getApplicationUrl() + "/social-register/" + connection.getKey().getProviderId()) .queryParam("success", "true").build().toString()); } catch (Exception e) { log.error("Exception creating social user: ", e); return redirectOnError(providerId); } }
private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory, NativeWebRequest request) { List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection); if (userIds.isEmpty()) { ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection); sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt); return redirect(getSignUpUrl()); } else if (userIds.size() == 1) { usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection); String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request); return originalUrl != null ? redirect(originalUrl) : redirect(POST_SIGN_IN_URL); } else { log.error("Find more than one user with connection key: {}", connection.getKey()); return redirectOnError(connection.getKey().getProviderId()); } }
/** * Method to delete the RegisteredService by its ID. * @param request the HttpServletRequest * @param response the HttpServletResponse * @return the Model and View to go to after the service is deleted. */ public ModelAndView deleteRegisteredService( final HttpServletRequest request, final HttpServletResponse response) { final String id = request.getParameter("id"); final long idAsLong = Long.parseLong(id); final ModelAndView modelAndView = new ModelAndView(new RedirectView( "manage.html", true), "status", "deleted"); final RegisteredService r = this.servicesManager.delete(idAsLong); modelAndView.addObject("serviceName", r != null ? r.getName() : ""); return modelAndView; }
@RequestMapping ( "/find-service/{releasePackage}/{serviceName}" ) public ModelAndView servicePortalFind ( @PathVariable String serviceName, @PathVariable String releasePackage ) { ModelAndView mav = new ModelAndView(); mav.setView( new RedirectView( CsapCoreService.ADMIN_URL, true, false, true ) ); logger.info( "Redirecting based on package {} and service {}", releasePackage, serviceName ); mav.getModel().put( CSAP.PACKAGE_PARAM, releasePackage ); // use the first instance to determine the default admin service ServiceInstance instance = application .serviceInstancesByName( releasePackage, serviceName ) .stream() .findFirst() .get(); mav.getModel().put( CSAP.SERVICE_PORT_PARAM, instance.getServiceName_Port() ); mav.getModel().put( CSAP.HOST_PARAM, instance.getHostName() ); return mav; }
/** * Registers a new {@link User} for the data provided by the given {@link UserForm}. Note, how an interface is used to * bind request parameters. * * @param userForm the request data bound to the {@link UserForm} instance. * @param binding the result of the binding operation. * @param model the Spring MVC {@link Model}. * @return */ @RequestMapping(method = RequestMethod.POST) public Object register(UserForm userForm, BindingResult binding, Model model) { userForm.validate(binding, userManagement); if (binding.hasErrors()) { return "users"; } userManagement.register(new Username(userForm.getUsername()), Password.raw(userForm.getPassword())); RedirectView redirectView = new RedirectView("redirect:/users"); redirectView.setPropagateQueryParams(true); return redirectView; }
@PostMapping("/") public RedirectView startCreditApplicationProcess() { //Create Credit Application Number UUID creditApplicationNumber = UUID.randomUUID(); Date applicationTime = new Date(); LOGGER.info("Created a new Credit Application Number: " + creditApplicationNumber.toString()); // We are saving the initial status CreditApplicationStatus status = new CreditApplicationStatus(creditApplicationNumber.toString(), applicationTime); repository.save(status); LOGGER.info("Saved " + status.toString()); // We are sending a CreditApplicationNumberGeneratedEvent CreditApplicationNumberGeneratedEvent event = new CreditApplicationNumberGeneratedEvent(); event.setApplicationNumber(creditApplicationNumber.toString()); event.setCreationTime(applicationTime); applicationProcessChannels.creditApplicationNumberGeneratedOut() .send(MessageBuilder.withPayload(event).build()); LOGGER.info("Sent " + event.toString()); return new RedirectView(nextProcessStepUrl + creditApplicationNumber.toString()); }
@RequestMapping(method = RequestMethod.GET) protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Player player = playerService.getPlayer(request, response); List<TransferStatus> statuses = statusService.getStreamStatusesForPlayer(player); MediaFile current = statuses.isEmpty() ? null : mediaFileService.getMediaFile(statuses.get(0).getFile()); MediaFile dir = current == null ? null : mediaFileService.getParentOf(current); String url; if (dir != null && !mediaFileService.isRoot(dir)) { url = "main.view?id=" + dir.getId(); } else { url = "home.view"; } return new ModelAndView(new RedirectView(url)); }
@RequestMapping(method = RequestMethod.GET) protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<>(); int id = ServletRequestUtils.getRequiredIntParameter(request, "id"); User user = securityService.getCurrentUser(request); String username = user.getUsername(); UserSettings userSettings = settingsService.getUserSettings(username); Player player = playerService.getPlayer(request, response); Playlist playlist = playlistService.getPlaylist(id); if (playlist == null) { return new ModelAndView(new RedirectView("notFound")); } map.put("playlist", playlist); map.put("user", user); map.put("player", player); map.put("editAllowed", username.equals(playlist.getUsername()) || securityService.isAdmin(username)); map.put("partyMode", userSettings.isPartyModeEnabled()); return new ModelAndView("playlist","model",map); }
@RequestMapping("/playChallenge/{challengeId}") public RedirectView playChallenge(RedirectAttributes redirectAttributes, @PathVariable long challengeId) { logger.debug("Playing challenge " + challengeId); Challenge currentChallenge = challengeService.findOne(challengeId); if (currentChallenge == null) { redirectAttributes.addFlashAttribute("message", "challenge not found"); return new RedirectView("/error"); } User player = userService.getCurrentUser(); TaskInstance unfinished = taskInstanceService.getUnfinishedInstanceInChallenge( currentChallenge, player); if (unfinished != null) { logger.debug("Found unfinished instance. Redirecting to /task."); return new RedirectView("/task/" + unfinished.getId()); } if (currentChallenge.getType() == ChallengeType.ARCADE) { return playArcade(redirectAttributes, currentChallenge); } else if (currentChallenge.getIsOpen()) { return playLive(currentChallenge, redirectAttributes); } return playPractice(redirectAttributes, currentChallenge); }
@RequestMapping("/closeChallenge/{challengeId}") public RedirectView closeChallenge(@PathVariable Long challengeId, RedirectAttributes redirectAttributes) { logger.debug("Closing challenge"); Challenge currentChallenge = challengeService.findOne(challengeId); if (!challengeService.isParticipating(currentChallenge, userService.getCurrentUser())) { logger.debug("User trying to close somebody else's challenge. Redirecting to /error."); redirectAttributes.addFlashAttribute("message", "user not in challenge"); return new RedirectView("/error"); } challengeService.closeChallenge(currentChallenge); redirectAttributes.addFlashAttribute("message", "Challenge closed."); return new RedirectView("/user"); }
@RequestMapping("/newArcadeSession") public RedirectView newArcadeSession(RedirectAttributes redirectAttributes, @RequestParam String realm) { logger.debug("Request to /newArcadeSession"); Realm currentRealm = null; try { logger.debug("Trying to get realm: {}", realm); currentRealm = Realm.valueOf(realm.toUpperCase()); } catch (Exception e) { logger.debug("Realm {} does not exist. Redirecting to /error.", realm); return new RedirectView("/error"); } Challenge challenge = arcadeChallengeService.getArcadeChallenge(currentRealm); return playArcade(redirectAttributes, challenge); }
private RedirectView playImplementationTurn(RedirectAttributes redirectAttributes, Challenge currentChallenge) { logger.debug("Playing implementation turn"); Task implTask = liveChallengeService .getTopmostImplementationTask(currentChallenge); logger.debug("implementation task: " + implTask.toString()); Task testTask = liveChallengeService .getTopmostTestTask(currentChallenge); logger.debug("test task: " + testTask.toString()); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.debug("Found uneven number of completed taskinstances, " + "current user has turn, " + "creating new task instance, redirecting to /task."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); }
private RedirectView playArcade(RedirectAttributes redirectAttributes, Challenge challenge) { logger.debug("Playing arcade"); if (taskInstanceService.getNumberOfDoneTaskInstancesInChallenge(challenge) % 2 == 0) { logger.debug("User has test turn. Redirecting to /newtaskpair."); return new RedirectView("/newtaskpair/" + challenge.getId()); } else { Task implTask = arcadeChallengeService .getRandomImplementationTask(challenge); Task testTask = taskService.getCorrespondingTask(implTask); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.debug("User has implementation turn."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); } }
@RequestMapping(value = "/task", method = RequestMethod.POST) public RedirectView task(String submissionCode, long taskInstanceId, RedirectAttributes redirectAttributes) throws IOException, ArchiveException { logger.debug("Submitting task"); TaskInstance taskInstance = taskInstanceService.findOne(taskInstanceId); Challenge currentChallenge = taskInstance.getTask().getChallenge(); Submission submission = submitToTmc(taskInstance, currentChallenge, submissionCode); redirectAttributes.addFlashAttribute("submissionId", submission.getId().toString()); redirectAttributes.addFlashAttribute("taskInstance", taskInstance); redirectAttributes.addFlashAttribute("challenge", currentChallenge); redirectAttributes.addFlashAttribute("user", userService.getCurrentUser()); // Save user's answer from left editor taskInstanceService.updateTaskInstanceCode(taskInstanceId, submissionCode); logger.debug("Redirecting to feedback"); return new RedirectView("/feedback"); }
@RequestMapping("/skip/{taskInstanceId}") public RedirectView skip(RedirectAttributes redirectAttributes, @PathVariable long taskInstanceId) { logger.debug("Request to /skip/{}", taskInstanceId); TaskInstance skippedTaskInstance = taskInstanceService.findOne(taskInstanceId); if (!gameplayService.canPlayOrSkip(skippedTaskInstance, userService.getCurrentUser())) { logger.debug("Can't play or skip"); return new RedirectView("/error"); } Challenge currentChallenge = skippedTaskInstance.getChallenge(); if (currentChallenge.getType() == ChallengeType.ARCADE || !currentChallenge.getIsOpen()) { logger.debug("Dropping arcade challenge"); skippedTaskInstance.setStatus(CodeStatus.DROPPED); taskInstanceService.save(skippedTaskInstance); return new RedirectView("/playChallenge/" + currentChallenge.getId()); } logger.debug("Redirecting to error"); return new RedirectView("/error"); }
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { if (exception instanceof FlowExecutionRepositoryException && !(exception instanceof BadlyFormattedFlowExecutionKeyException)) { String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : ""); log.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); Map<String, Object> model = new HashMap(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); } else if (exception instanceof AbstractFlowExecutionException) { if (log.isDebugEnabled()) { log.error("Flow execution error", exception); } else { log.error("Flow execution error: {}", exception.getMessage()); } return ((AbstractFlowExecutionException) exception).getModelAndView(); } else { log.debug("Ignoring the received exception due to a type mismatch", exception); return null; } }
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public View uploadFile(@RequestParam("file") MultipartFile file) { try { InputStream input = file.getInputStream(); this.messageManagementService.importFromExcel(input); } catch (Exception e) { LOG.error("error on uploading messages", e); return new RedirectView("../files.html?uploadSuccess=no&message=" + e.getMessage().toString()); } return new RedirectView("../files.html?uploadSuccess=yes"); }
@PostMapping("topic") public View addAnswer(@RequestParam("content") String content, @RequestParam("code") String code, @RequestParam("id_topic") String id_topic, @RequestParam("id_user") String id_user, HttpServletRequest request) { Answer answer = new Answer(); answer.setContent(content); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(code, "")) answer.setCode(null); else answer.setCode(code); answer.setCreatedDate(LocalDateTime.now()); answer.setUseful(false); answer.setTopic(topicRepository.findTopicById(Long.valueOf(id_topic))); answer.setUser(userRepository.getUserById(Long.parseLong(id_user))); answerRepository.save(answer); String contextPath = request.getContextPath(); return new RedirectView(contextPath + "/topic/" + id_topic); }
@PostMapping("profile") public View addTask(@RequestParam("category") String category, @RequestParam("title") String title, @RequestParam("content") String content, @RequestParam("code") String code, @RequestParam("id_user") String id_user, HttpServletRequest request) { Topic topic = new Topic(); topic.setCategory(category); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(code, "")) topic.setCode(null); else topic.setCode(code); topic.setContent(content); topic.setTitle(title); topic.setCreatedDate(LocalDateTime.now()); topic.setUser(userRepository.getUserById(Long.parseLong(id_user))); topicRepository.save(topic); String contextPath = request.getContextPath(); return new RedirectView(contextPath + "/profile"); }
@PostMapping("register") public View registerUser(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("introduction") String introduction, HttpServletRequest request) { String contextPath = request.getContextPath(); User user = new User(); if (userRepository.getUserByUsername(username) == null) { user.setUsername(username); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(introduction, "")) user.setIntroduction(null); else user.setIntroduction(introduction); user.setPassword(password); user.setPassword(passwordEncoder.encode(password)); user.setCreatedDate(LocalDateTime.now()); userRepository.save(user); return new RedirectView(contextPath + "/login"); } else return new RedirectView(contextPath + "/register"); }
@PostMapping(value = "/signin/{providerId}") public RedirectView signIn(@PathVariable String providerId, NativeWebRequest request) { try { ConnectionFactory<?> connectionFactory = connectionFactoryLocator.getConnectionFactory(providerId); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); return redirectAbsolute(connectSupport.buildOAuthUrl(connectionFactory, request, parameters)); } catch (Exception e) { log.error("Exception while building authorization URL: ", e); return redirectOnError(providerId); } }
@GetMapping(value = "/signin/{providerId}", params = "oauth_token") public RedirectView oauth1Callback(@PathVariable String providerId, NativeWebRequest request) { try { OAuth1ConnectionFactory<?> connectionFactory = (OAuth1ConnectionFactory<?>) connectionFactoryLocator .getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { log.error("Exception while completing OAuth 1.0(a) connection: ", e); return redirectOnError(providerId); } }
@GetMapping(value = "/signin/{providerId}", params = "code") public RedirectView oauth2Callback(@PathVariable String providerId, @RequestParam("code") String code, NativeWebRequest request) { try { OAuth2ConnectionFactory<?> connectionFactory = (OAuth2ConnectionFactory<?>) connectionFactoryLocator .getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { log.error("Exception while completing OAuth 2 connection: ", e); return redirectOnError(providerId); } }
@GetMapping("/signup") public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) { try { Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest); socialService.createSocialUser(connection, langKey.replace("\"", "")); return new RedirectView(URIBuilder.fromUri("/#/social-register/" + connection.getKey().getProviderId()) .queryParam("success", "true") .build().toString(), true); } catch (Exception e) { log.error("Exception creating social user: ", e); return new RedirectView(URIBuilder.fromUri("/#/social-register/no-provider") .queryParam("success", "false") .build().toString(), true); } }
@RequestMapping(value="/jump_page.html", method=RequestMethod.POST) public RedirectView sendRedirection(RedirectAttributes atts, @RequestParam("username") String username, @RequestParam("password") String password){ atts.addFlashAttribute("username", username); atts.addFlashAttribute("password", password); atts.addAttribute("request", "loginForm"); return new RedirectView("/redirectviewOld.html",true); }
@Override public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception exception) { /* * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other * error cases we would likely want to hide from the user, it seems reasonable to check for * FlowExecutionRepositoryException. * * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler * because redirecting to the requested URI with this exception may cause an infinite * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string */ if (!(exception instanceof FlowExecutionRepositoryException) || exception instanceof BadlyFormattedFlowExecutionKeyException) { logger.debug("Ignoring the received exception due to a type mismatch", exception); return null; } final String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : ""); logger.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); final Map<String, Object> model = new HashMap<>(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); }
@Test public void verifyOK() throws Exception { clearAllServices(); 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(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager().save(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); final Controller c = ((OAuth20WrapperController) oauth20WrapperController).getAuthorizeController(); ((OAuth20AuthorizeController) c).setLoginUrl(CAS_URL); 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); }
@Test public void verifyOKWithState() throws Exception { clearAllServices(); 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(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager().save(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); final Controller c = ((OAuth20WrapperController) oauth20WrapperController).getAuthorizeController(); ((OAuth20AuthorizeController) c).setLoginUrl(CAS_URL); 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); }
@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); }
@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); }
@Test public void verifyNoSuchFlowExecutionException() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("test"); ModelAndView model = this.resolver.resolveException(request, new MockHttpServletResponse(), null, new NoSuchFlowExecutionException(new FlowExecutionKey(){ private static final long serialVersionUID = 1443616250214416520L; @Override public String toString() { return "test"; } @Override public boolean equals(final Object o) { return true; } @Override public int hashCode() { return 0; } }, new RuntimeException())); assertEquals(request.getRequestURI(), ((RedirectView) model.getView()) .getUrl()); }
@Test public void verifyNoSuchFlowExecutionExeptionWithQueryString() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("test"); request.setQueryString("test=test"); ModelAndView model = this.resolver.resolveException(request, new MockHttpServletResponse(), null, new NoSuchFlowExecutionException(new FlowExecutionKey(){ private static final long serialVersionUID = -4750073902540974152L; @Override public String toString() { return "test"; } @Override public boolean equals(final Object o) { return true; } @Override public int hashCode() { return 0; } }, new RuntimeException())); assertEquals(request.getRequestURI() + "?" + request.getQueryString(), ((RedirectView) model.getView()) .getUrl()); }
@Override public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { if (!StringUtils.isEmpty(request.getQueryString()) && request.getQueryString().contains(CasProtocolConstants.PARAMETER_TICKET)) { final RedirectView v = new RedirectView(request.getRequestURL().toString()); v.setExposeModelAttributes(false); v.setExposePathVariables(false); modelAndView.setView(v); } }
@Bean protected Controller rootController() { return new ParameterizableViewController() { @Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String queryString = request.getQueryString(); final String url = request.getContextPath() + "/login" + (queryString != null ? '?' + queryString : StringUtils.EMPTY); return new ModelAndView(new RedirectView(response.encodeURL(url))); } }; }
@Override public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { if (StringUtils.isNotBlank(request.getQueryString()) && request.getQueryString().contains(CasProtocolConstants.PARAMETER_TICKET) && modelAndView != null) { final RedirectView v = new RedirectView(request.getRequestURL().toString()); v.setExposeModelAttributes(false); v.setExposePathVariables(false); modelAndView.setView(v); } }
@RequestMapping(value = "delete/{id}", method = RequestMethod.POST) public RedirectView deleteFromButton(@PathVariable Long id, Model model, RedirectAttributes red) { Category category = categoriesService.findOne(id); if (category == null) red.addFlashAttribute("msg", "not found"); else { categoriesService.delete(category); red.addFlashAttribute("msg", "Succes"); } Iterable<Category> categories = categoriesService.findAll(); model.addAttribute("categories", categories); return new RedirectView(ApplicationProperties.PROJECT_NAME + "administratorSite/categories/delete"); }
@Override public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception exception) { /* * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other * error cases we would likely want to hide from the user, it seems reasonable to check for * FlowExecutionRepositoryException. * * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler * because redirecting to the requested URI with this exception may cause an infinite * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string */ if (!(exception instanceof FlowExecutionRepositoryException) || exception instanceof BadlyFormattedFlowExecutionKeyException) { LOGGER.debug("Ignoring the received exception due to a type mismatch", exception); return null; } final String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : StringUtils.EMPTY); LOGGER.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); final Map<String, Object> model = new HashMap<>(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); }