List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl
@Deprecated
public String encodeRedirectUrl(String url);
From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java
private void addComment(HttpServletRequest req, HttpServletResponse resp) { String id;/* www.j a v a2 s. c om*/ String repositoryName; String text; try { id = getField(req, resp, "document"); repositoryName = getField(req, resp, "repository"); text = getField(req, resp, "text"); } catch (FieldNotFoundException e) { return; } Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName); RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService(); try { Document document = repositoryService.findDocument(ticket, id); Note note = new Note(); note.setCreator(ticket.getUser().getId()); note.setDate(new Date()); note.setNode(document); note.setNote(processNote(text)); document.addNote(note); repositoryService.updateDocument(ticket, document.dumpProperties()); statsService.incComments(); String refererURL = req.getHeader("referer"); resp.sendRedirect(resp.encodeRedirectURL(refererURL)); } catch (RepositoryException e) { if ((e.getCause() != null) && (e.getCause() instanceof SecurityException)) { logErrorAndForward(req, resp, repositoryName, e, "Sorry, but you need to be logged in to add comments!"); } else { logErrorAndForward(req, resp, repositoryName, e, "There was a problem adding the comment."); } } catch (Exception e) { logErrorAndForward(req, resp, repositoryName, e, "There was a problem adding the comment."); } }
From source file:com.xpn.xwiki.user.impl.xwiki.MyFormAuthenticator.java
/** * Process any login information passed in parameter (username, password). Returns true if SecurityFilter should * abort further processing after the method completes (for example, if a redirect was sent as part of the login * processing)./*from w ww .j a v a 2 s .c om*/ * * @param request * @param response * @return true if the filter should return after this method ends, false otherwise */ public boolean processLogin(String username, String password, String rememberme, SecurityRequestWrapper request, HttpServletResponse response, XWikiContext context) throws Exception { Principal principal = authenticate(username, password, context); if (principal != null) { // login successful if (LOGGER.isInfoEnabled()) { LOGGER.info("User " + principal.getName() + " has been logged-in"); } // invalidate old session if the user was already authenticated, and they logged in as a different user if (request.getUserPrincipal() != null && !username.equals(request.getRemoteUser())) { request.getSession().invalidate(); } // manage persistent login info, if persistent login management is enabled if (this.persistentLoginManager != null) { // did the user request that their login be persistent? if (rememberme != null) { // remember login this.persistentLoginManager.rememberLogin(request, response, username, password); } else { // forget login this.persistentLoginManager.forgetLogin(request, response); } } // make sure the Principal contains wiki name information if (!StringUtils.contains(principal.getName(), ':')) { principal = new SimplePrincipal(context.getDatabase() + ":" + principal.getName()); } request.setUserPrincipal(principal); Boolean bAjax = (Boolean) context.get("ajax"); if ((bAjax == null) || (!bAjax.booleanValue())) { String continueToURL = getContinueToURL(request); // This is the url that the user was initially accessing before being prompted for login. response.sendRedirect(response.encodeRedirectURL(continueToURL)); } } else { // login failed // set response status and forward to error page if (LOGGER.isInfoEnabled()) { LOGGER.info("User " + username + " login has failed"); } String returnCode = context.getWiki().Param("xwiki.authentication.unauthorized_code"); int rCode = HttpServletResponse.SC_UNAUTHORIZED; if ((returnCode != null) && (!returnCode.equals(""))) { try { rCode = Integer.parseInt(returnCode); } catch (Exception e) { rCode = HttpServletResponse.SC_UNAUTHORIZED; } } response.setStatus(rCode); // TODO: Does this work? (200 in case of error) } return true; }
From source file:org.pentaho.platform.web.http.security.HttpSessionReuseDetectionFilter.java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException(); }//w w w . j a v a 2s .c om if (!(response instanceof HttpServletResponse)) { throw new ServletException(); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (requiresAuthentication(httpRequest, httpResponse)) { if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) { HttpSessionReuseDetectionFilter.logger.debug( Messages.getInstance().getString("HttpSessionReuseDetectionFilter.DEBUG_PROCESS_AUTHN")); //$NON-NLS-1$ } // TODO: this should use LogoutHandlers in latest Spring Security if (null != httpRequest) { String remoteUser = httpRequest.getRemoteUser(); if ((null != remoteUser) && (remoteUser.length() > 0)) { if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) { HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance().getString( "HttpSessionReuseDetectionFilter.DEBUG_USER_ALREADY_LOGGED_IN", remoteUser)); //$NON-NLS-1$ } HttpSession session = httpRequest.getSession(false); if (null != session) { if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) { HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance() .getString("HttpSessionReuseDetectionFilter.DEBUG_INVALIDATING_SESSION")); //$NON-NLS-1$ } session.invalidate(); } SecurityContextHolder.clearContext(); if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) { HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance().getString( "HttpSessionReuseDetectionFilter.DEBUG_REDIRECTING", sessionReuseDetectedUrl)); //$NON-NLS-1$ } httpResponse.sendRedirect( httpResponse.encodeRedirectURL(httpRequest.getContextPath() + sessionReuseDetectedUrl)); return; } } } chain.doFilter(request, response); }
From source file:org.jasig.portal.security.mvc.LogoutController.java
/** * Process the incoming request and response. * @param request HttpServletRequest object * @param response HttpServletResponse object * @throws ServletException/*from w w w. jav a 2 s. co m*/ * @throws IOException */ @RequestMapping public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String redirect = this.getRedirectionUrl(request); final HttpSession session = request.getSession(false); if (session != null) { // Record that an authenticated user is requesting to log out try { final IPerson person = personManager.getPerson(request); if (person != null && person.getSecurityContext().isAuthenticated()) { this.portalEventFactory.publishLogoutEvent(request, this, person); } } catch (final Exception e) { log.error("Exception recording logout " + "associated with request " + request, e); } final String originalUid = this.identitySwapperManager.getOriginalUsername(session); //Logging out from a swapped user, just redirect to the Login servlet if (originalUid != null) { redirect = request.getContextPath() + "/Login"; } else { // Clear out the existing session for the user try { session.invalidate(); } catch (final IllegalStateException ise) { // IllegalStateException indicates session was already invalidated. // This is fine. LogoutController is looking to guarantee the logged out session is invalid; // it need not insist that it be the one to perform the invalidating. if (log.isTraceEnabled()) { log.trace( "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session.", ise); } } } } // Send the user back to the guest page final String encodedRedirectURL = response.encodeRedirectURL(redirect); response.sendRedirect(encodedRedirectURL); }
From source file:com.expressflow.servlets.ExecProcessServlet.java
private void performRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user != null) { StringBuilder sb = new StringBuilder(request.getRequestURI()); String processID = sb.substring(6, sb.length()); if (processID != null) { try { // TaskQueues do not support UserService functions... // Add the process to the flow-processing queue TaskOptions taskOptions = TaskOptions.Builder.withUrl("/_ah/queue/flowprocessor"); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String parameterName = (String) parameterNames.nextElement(); String[] paramValues = request.getParameterValues(parameterName); if (paramValues.length == 1) { taskOptions.param(parameterName, paramValues[0]); } else { System.err.print(parameterName + " has more values?!"); }/*w ww . j a v a 2s.c o m*/ } // Map<String, String[]> parameterMap = request.getParameterMap(); // for (Map.Entry<String, String[]> parameter : parameterMap.entrySet()) { // for(String value : parameter.getValue()){ // taskOptions.param(parameter.getKey(), value); // } // } Queue queue = QueueFactory.getQueue("flowprocessor"); queue.add(taskOptions.param("key", processID)); } catch (Exception e) { log.info(e.getMessage()); } } } else { response.sendRedirect(response.encodeRedirectURL(userService.createLoginURL(request.getRequestURI()))); } }
From source file:org.sakaiproject.portal.tool.ToolPortal.java
/** * Process a tool request/*from w w w.ja v a2 s . com*/ * * @param req * @param res * @param session * @param placementId * @param toolContextPath * @param toolPathInfo * @return true if the processing was successful, false if nt * @throws ToolException * @throws IOException */ protected boolean doTool(HttpServletRequest req, HttpServletResponse res, Session session, String placementId, String toolContextPath, String toolPathInfo) throws ToolException, IOException { // find the tool from some site // TODO: all placements are from sites? -ggolden ToolConfiguration siteTool = SiteService.findTool(placementId); if (siteTool == null) return false; // find the tool registered for this ActiveTool tool = ActiveToolManager.getActiveTool(siteTool.getToolId()); if (tool == null) return false; // permission check - visit the site (unless the tool is configured to // bypass) if (tool.getAccessSecurity() == Tool.AccessSecurity.PORTAL) { Site site = null; try { site = SiteService.getSiteVisit(siteTool.getSiteId()); } catch (IdUnusedException e) { return false; } catch (PermissionException e) { // TODO: login here? return false; } } // if the path is not set, and we are expecting one, we need to compute // the path and redirect // we expect a path only if the tool has a registered home -ggolden if ((toolPathInfo == null) && (tool.getHome() != null)) { // what path? The one last visited, or home ToolSession toolSession = SessionManager.getCurrentSession().getToolSession(placementId); String redirectPath = (String) toolSession.getAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION); if (redirectPath == null) { redirectPath = tool.getHome(); } // redirect with this tool path String redirectUrl = ServerConfigurationService.getServerUrl() + toolContextPath + redirectPath; res.sendRedirect(res.encodeRedirectURL(redirectUrl)); return true; } // store the path as the current path, if we are doing this if (tool.getHome() != null) { ToolSession toolSession = SessionManager.getCurrentSession().getToolSession(placementId); toolSession.setAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION, toolPathInfo); } // prepare for the forward setupForward(req, res, siteTool, siteTool.getSkin()); req.setAttribute(ToolURL.MANAGER, new ToolURLManagerImpl(res)); // let the tool do the the work (forward) tool.forward(req, res, siteTool, toolContextPath, toolPathInfo); return true; }
From source file:com.wso2telco.gsma.authenticators.ussd.USSDAuthenticator.java
@Override protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { log.info("Initiating authentication request"); UserStatus userStatus = (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM); String loginPage;// www.j a va2 s . com String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); String msisdn = (String) context.getProperty(Constants.MSISDN); boolean isUserExists = !(boolean) context.getProperty(Constants.IS_REGISTERING); String serviceProviderName = context.getSequenceConfig().getApplicationConfig().getApplicationName(); if (log.isDebugEnabled()) { log.debug("MSISDN : " + msisdn); log.debug("Service provider : " + serviceProviderName); log.debug("User exist : " + isUserExists); log.debug("Query parameters : " + queryParams); } try { String retryParam = ""; loginPage = getAuthEndpointUrl(context); if (serviceProviderName.equals("wso2_sp_dashboard")) { serviceProviderName = configurationService.getDataHolder().getMobileConnectConfig().getUssdConfig() .getDashBoard(); } String operator = (String) context.getProperty(Constants.OPERATOR); DBUtils.insertAuthFlowStatus(msisdn, Constants.STATUS_PENDING, context.getContextIdentifier()); sendUssd(context, msisdn, serviceProviderName, operator, isUserExists); if (log.isDebugEnabled()) { log.debug("Operator : " + operator); log.debug("Redirect URI : " + context.getProperty("redirectURI")); } response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&redirect_uri=" + (String) context.getProperty("redirectURI") + "&authenticators=" + getName() + ":" + "LOCAL" + retryParam); } catch (IOException | SQLException | AuthenticatorException e) { DataPublisherUtil.updateAndPublishUserStatus(userStatus, DataPublisherUtil.UserState.USSD_AUTH_PROCESSING_FAIL, e.getMessage()); throw new AuthenticationFailedException(e.getMessage(), e); } }
From source file:org.etudes.ambrosia.impl.UiServiceImpl.java
/** * {@inheritDoc}//from ww w . j a v a 2 s.c om */ public boolean redirectToCurrentDestination(HttpServletRequest req, HttpServletResponse res, String home) throws IOException { // get the Tool session ToolSession toolSession = m_sessionManager.getCurrentToolSession(); // check the path in the request - if null, we will either send them home or to the current destination String destination = req.getPathInfo(); if (destination == null) { // do we have a current destination? destination = (String) toolSession.getAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION); // if not, set it to home if (destination == null) { destination = "/" + ((home != null) ? home : ""); } // redirect res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination))); return true; } return false; }
From source file:org.etudes.mneme.tool.QuestionView.java
/** * {@inheritDoc}//from ww w .jav a 2 s .co m */ public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params) throws IOException { // sid/question selector/anchor and return // question selector may end in "!" for "last chance" - linear repeat question when it was not answered if (params.length < 5) { throw new IllegalArgumentException(); } String submissionId = params[2]; String questionSelector = params[3]; boolean lastChance = false; if (questionSelector.endsWith("!")) { questionSelector = questionSelector.substring(0, questionSelector.length() - 1); lastChance = true; } String anchor = params[4]; if (anchor.equals("-")) anchor = null; String destination = null; if (params.length > 5) { destination = "/" + StringUtil.unsplit(params, 5, params.length - 5, "/"); } // if not specified, go to the main list view else { destination = "/list"; } context.put("return", destination); // adjust the current destination to remove the anchor params[4] = "-"; String curDestination = "/" + StringUtil.unsplit(params, 1, params.length - 1, "/"); context.put("curDestination", curDestination); Submission submission = submissionService.getSubmission(submissionId); if (submission == null) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid))); return; } // if not in-progress (i.e. already closed) if (submission.getIsComplete()) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.over))); return; } // validity check if (!submission.getAssessment().getIsValid()) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized))); return; } // handle our 'z' selector - redirect to the appropriate question to re-enter this submission if ("z".equals(questionSelector)) { try { // Note: enterSubmission() can create a new submission, if the submission is not in progress. // Our submission has no sibling count (=0), since we used getSubmission(), which does not set it. // enterSubmission() will think there are no other submissions, so would create one even if the max allowed // for the user has been exceeded. Since we check getIsComplete() above, this should be avoided -ggolden this.submissionService.enterSubmission(submission); } catch (AssessmentPermissionException e) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized))); return; } catch (AssessmentClosedException e) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid))); return; } catch (AssessmentCompletedException e) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid))); return; } redirectToQuestion(req, res, submission, true, false, destination); return; } // if the submission has past a hard deadline or ran out of time, close it and tell the user if (submission.completeIfOver()) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.over))); return; } context.put("actionTitle", messages.getString("question-header-work")); // collect the questions (actually their answers) to put on the page List<Answer> answers = new ArrayList<Answer>(); Errors err = questionSetup(submission, questionSelector, context, answers, true); if (err != null) { // redirect to error res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + err + "/" + submissionId))); return; } // for the tool navigation if (this.assessmentService.allowManageAssessments(toolManager.getCurrentPlacement().getContext())) { context.put("maintainer", Boolean.TRUE); } if (anchor != null) context.put("anchor", anchor); if (lastChance) context.put("lastChance", Boolean.TRUE); new CKSetup().setCKCollectionAttrib(getDocsPath(), toolManager.getCurrentPlacement().getContext()); // render uiService.render(ui, context); }
From source file:org.apereo.portal.security.mvc.LogoutController.java
/** * Process the incoming request and response. * @param request HttpServletRequest object * @param response HttpServletResponse object * @throws ServletException/*from w w w .j a v a 2 s . c o m*/ * @throws IOException */ @RequestMapping public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String redirect = this.getRedirectionUrl(request); final HttpSession session = request.getSession(false); if (session != null) { // Record that an authenticated user is requesting to log out try { final IPerson person = personManager.getPerson(request); if (person != null && person.getSecurityContext().isAuthenticated()) { this.portalEventFactory.publishLogoutEvent(request, this, person); } } catch (final Exception e) { log.error("Exception recording logout " + "associated with request " + request, e); } final String originalUid = this.identitySwapperManager.getOriginalUsername(session); //Logging out from a swapped user, just redirect to the Login servlet if (originalUid != null) { redirect = request.getContextPath() + "/Login"; } else { // Clear out the existing session for the user try { session.invalidate(); } catch (final IllegalStateException ise) { // IllegalStateException indicates session was already invalidated. // This is fine. LogoutController is looking to guarantee the logged out session is invalid; // it need not insist that it be the one to perform the invalidating. if (log.isTraceEnabled()) { log.trace( "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session.", ise); } } } } if (log.isTraceEnabled()) { log.trace("Redirecting to " + redirect + " to send the user back to the guest page."); } final String encodedRedirectURL = response.encodeRedirectURL(redirect); response.sendRedirect(encodedRedirectURL); }