Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl.

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/sessions", method = RequestMethod.POST, params = { "endSession" })
public String endSession(Model model, @RequestParam String sessionUuid, HttpServletResponse response,
        HttpServletRequest request) throws IOException, AclsAuthenticationException {
    getFacilityStatusManager().logoutSession(sessionUuid);
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/sessions"));
    return null;/*from w w  w  .  j  a va 2s  .com*/
}

From source file:org.jamwiki.authentication.JAMWikiLogoutFilter.java

/**
 * Allow subclasses to modify the redirection message.
 *
 * @param request the request//from w w  w .java2s.  com
 * @param response the response
 * @param url the URL to redirect to
 * @throws IOException in the event of any failure
 */
protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String targetUrl = url;
    if ("/DEFAULT_VIRTUAL_WIKI".equals(url)) {
        // ugly, but a hard-coded constant seems to be the only way to
        // allow a dynamic url value
        String virtualWikiName = WikiUtil.getVirtualWikiFromURI(request);
        if (StringUtils.isBlank(virtualWikiName)) {
            virtualWikiName = WikiBase.DEFAULT_VWIKI;
        }
        String topicName = Environment.getValue(Environment.PROP_BASE_DEFAULT_TOPIC);
        try {
            VirtualWiki virtualWiki = WikiBase.getDataHandler().lookupVirtualWiki(virtualWikiName);
            topicName = virtualWiki.getDefaultTopicName();
        } catch (Exception e) {
            logger.warning("Unable to retrieve default topic for virtual wiki", e);
        }
        targetUrl = request.getContextPath() + "/" + virtualWikiName + "/" + topicName;
    } else if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
        String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
        targetUrl = request.getContextPath() + "/" + virtualWiki + url;
    }
    response.sendRedirect(response.encodeRedirectURL(targetUrl));
}

From source file:com.wso2telco.gsma.authenticators.MSISDNAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    log.info("Initiating authentication request");

    String loginPage;/*w w w .  java2  s  .c o m*/
    try {

        loginPage = getAuthEndpointUrl(context);

        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                context.getCallerSessionKey(), context.getContextIdentifier());
        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        }

        DataPublisherUtil.updateAndPublishUserStatus(
                (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM),
                DataPublisherUtil.UserState.REDIRECT_TO_CONSENT_PAGE, "Redirecting to consent page");

        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&redirect_uri="
                + request.getParameter("redirect_uri") + "&authenticators=" + getName() + ":" + "LOCAL"
                + retryParam);
    } catch (IOException e) {
        log.error("Error occurred while redirecting request", e);
        DataPublisherUtil.updateAndPublishUserStatus(
                (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM),
                DataPublisherUtil.UserState.MSISDN_AUTH_PROCESSING_FAIL, e.getMessage());
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.josso.gateway.signon.LoginAction.java

/**
 * Relay using a previously opened and valid SSO session.
 *//*from   w w  w  .ja v  a  2s . c  o  m*/
protected ActionForward relay(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    try {

        SSOGateway g = getSSOGateway();

        // 1 - Recover session and create a new assertion.
        SSOSession session = SSOContext.getCurrent().getSession();
        AuthenticationAssertion authAssertion = g.assertIdentity(session.getId());

        if (logger.isDebugEnabled())
            logger.debug("[relay()], authentication successfull.");

        // 2 - Restore BACK TO URL ...
        String back_to = this.getBackTo(request, session, authAssertion);
        if (back_to == null) {
            // Return to controller.
            return mapping.findForward("login-result");
        }

        this.clearSSOParameters(request);

        // We're going back to the partner app.
        if (logger.isDebugEnabled())
            logger.debug("[relay()], Redirecting user to : " + back_to);

        response.sendRedirect(response.encodeRedirectURL(back_to));

        return null; // No forward is needed, we perfomed a 'sendRedirect'.

    } catch (Exception e) {
        if (this.onFatalError(e, request, response))
            return null;

        return mapping.findForward("error");
    }
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

public void handleGet(HttpServletRequest request, HttpServletResponse response, String pathInContext,
        Resource resource, boolean endsWithSlash) throws ServletException, IOException {
    if (resource == null || !resource.exists())
        response.sendError(HttpResponse.__404_Not_Found);
    else {//from  w  ww . j  a  va2  s.c o  m

        // check if directory
        if (resource.isDirectory()) {
            if (!endsWithSlash && !pathInContext.equals("/")) {
                String q = request.getQueryString();
                StringBuffer buf = request.getRequestURL();
                if (q != null && q.length() != 0) {
                    buf.append('?');
                    buf.append(q);
                }
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(URI.addPaths(buf.toString(), "/")));
                return;
            }

            // See if index file exists
            String welcome = _httpContext.getWelcomeFile(resource);
            if (welcome != null) {
                String ipath = URI.addPaths(pathInContext, welcome);
                if (_redirectWelcomeFiles) {
                    // Redirect to the index
                    response.setContentLength(0);
                    response.sendRedirect(URI.addPaths(_httpContext.getContextPath(), ipath));
                } else {
                    // Forward to the index
                    RequestDispatcher dispatcher = _servletHandler.getRequestDispatcher(ipath);
                    dispatcher.forward(request, response);
                }
                return;
            }

            // Check modified dates
            if (!passConditionalHeaders(request, response, resource))
                return;

            // If we got here, no forward to index took place
            sendDirectory(request, response, resource, pathInContext.length() > 1);
        } else {
            // Check modified dates
            if (!passConditionalHeaders(request, response, resource))
                return;

            // just send it
            sendData(request, response, pathInContext, resource);
        }
    }
}

From source file:com.wso2telco.gsma.authenticators.GSMAMSISDNAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    log.info("Initiating authentication request");

    // Retrieve entry LOA and set to authentication context
    LinkedHashSet<?> acrs = getACRValues(request);
    String selectedLOA = (String) acrs.iterator().next();
    context.setProperty("entryLOA", selectedLOA);

    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();

    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    if (log.isDebugEnabled()) {
        log.debug("Query parameters : " + queryParams);
    }//from w  w w  .  ja  v  a 2s  . c o m

    try {

        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        }

        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&authenticators="
                + getName() + ":" + "LOCAL" + retryParam);

    } catch (IOException e) {
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java

/**
 * Show community home page with admin controls
 * //from  ww w. j  a  v  a2 s  .co m
 * @param context
 *            Current DSpace context
 * @param request
 *            Current HTTP request
 * @param response
 *            Current HTTP response
 */
private void showControls(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // new approach - eliminate the 'list-communities' page in favor of the
    // community home page, enhanced with admin controls. If no community,
    // or no parent community, just fall back to the community-list page
    Community community = (Community) request.getAttribute("community");
    Collection collection = (Collection) request.getAttribute("collection");

    if (collection != null) {
        response.sendRedirect(
                response.encodeRedirectURL(request.getContextPath() + "/handle/" + collection.getHandle()));
    } else if (community != null) {
        response.sendRedirect(
                response.encodeRedirectURL(request.getContextPath() + "/handle/" + community.getHandle()));
    } else {
        // see if a parent community was specified
        Community parent = (Community) request.getAttribute("parent");

        if (parent != null) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/handle/" + parent.getHandle()));
        } else {
            // fall back on community-list page
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/community-list"));
        }
    }
}

From source file:org.etudes.mneme.tool.ReviewView.java

/**
 * {@inheritDoc}//  w w w  .ja va2s. c o m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // sid and return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

    String submissionId = params[2];
    String destination = null;
    if (params.length > 3) {
        destination = "/" + StringUtil.unsplit(params, 3, params.length - 3, "/");
    }

    // if not specified, go to the main list view
    else {
        destination = "/list";
    }
    context.put("return", destination);

    // yes feedback, and we are in review
    context.put("review", Boolean.TRUE);
    context.put("actionTitle", messages.getString("question-header-review"));

    // collect the submission
    Submission submission = submissionService.getSubmission(submissionId);
    if (submission == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    boolean instructorViewWork = submission.getMayViewWork();
    context.put("viewWork", Boolean.valueOf(instructorViewWork));

    // must have permission for review, or for view work
    if ((!submissionService.allowReviewSubmission(submission)) && (!instructorViewWork)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // validity check
    if ((!submission.getAssessment().getIsValid()) && (!instructorViewWork)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // collect the other submissions from this user to the assessment
    List<? extends Submission> allSubmissions = submissionService
            .getMultipleSubmissions(submission.getAssessment(), submission.getUserId());

    // compute position within the group, pick the next and prev
    int size = allSubmissions.size();
    int position = 1;
    for (Submission s : allSubmissions) {
        if (s.equals(submission))
            break;
        position++;
    }

    // prev: wrap if needed
    Submission prev = null;
    if (position > 1) {
        prev = allSubmissions.get(position - 2);
    } else {
        prev = allSubmissions.get(size - 1);
    }

    // next: wrap if needed
    Submission next = null;
    if (position < size) {
        next = allSubmissions.get(position);
    } else {
        next = allSubmissions.get(0);
    }

    if (size > 0)
        context.put("count", Integer.valueOf(size));
    context.put("position", Integer.valueOf(position));
    if (prev != null)
        context.put("prevSubmissionId", prev.getId());
    if (next != null)
        context.put("nextSubmissionId", next.getId());

    // best is grade related, so only for assessments with points, released, and only if review is available (or we are doing instructor view)
    // also only if there are multiple submissions
    if ((size > 1) && (submission.getIsReleased().booleanValue())
            && (submission.getAssessment().getHasPoints().booleanValue())
            && (allSubmissions.get(position - 1).getBest().equals(submission))
            && (instructorViewWork || submission.getMayReview().booleanValue())) {
        context.put("best", Boolean.TRUE);
        context.put("submission", allSubmissions.get(position - 1).getBest());
    } else {
        context.put("submission", submission);
    }

    // collect all the answers for review
    List<Answer> answers = submission.getAnswers();
    context.put("answers", answers);

    // these only for student view, not instructor work view
    if (!instructorViewWork) {
        // in this special case, since there's no real action in the service to do this, we need to generate an event
        eventTrackingService.post(eventTrackingService.newEvent(MnemeService.SUBMISSION_REVIEW,
                submission.getReference(), false));

        // record the review date
        submissionService.markReviewed(submission);
    }

    if ((!instructorViewWork) && (submission.getAssessment().getReview()
            .getShowIncorrectQuestions() == ReviewShowCorrect.incorrect_only)) {
        boolean incorrectExists = false;
        // Check to see if there is at least one non-essay, non-task and non-likert-scale question
        for (Answer a : answers) {
            String questionType = a.getQuestion().getType();
            if (questionType.equals("mneme:FillBlanks") || questionType.equals("mneme:Match")
                    || questionType.equals("mneme:MultipleChoice") || questionType.equals("mneme:TrueFalse")) {
                incorrectExists = true;
                break;
            }
        }

        if (incorrectExists) {
            context.put("questionIncorrect", messages.getString("question-incorrect"));
            context.put("showIncorrect", Boolean.TRUE);
        }
    }

    SubmissionCompletionStatus subComp = submission.getCompletionStatus();
    boolean noneAnswered = false;
    if (subComp.equals(SubmissionCompletionStatus.evaluationNonSubmit)
            || ((subComp.equals(SubmissionCompletionStatus.autoComplete)
                    || subComp.equals(SubmissionCompletionStatus.userFinished))
                    && submission.getIsUnanswered() == Boolean.TRUE))
        noneAnswered = true;
    if (submission.getAssessment().getReview().getShowSummary()
            && submission.getAssessment().getReview().getShowCorrectAnswer().equals(ReviewShowCorrect.yes)
            && !noneAnswered) {
        if (submission.getAssessment().getType().equals(AssessmentType.survey)
                && submission.getAssessment().getFrozen()) {
            context.put("showsummary", Boolean.TRUE);
        }
        if (!submission.getAssessment().getType().equals(AssessmentType.survey)) {
            if ((size > 1) && (submission.getIsReleased().booleanValue())
                    && (submission.getAssessment().getHasPoints().booleanValue())
                    && (allSubmissions.get(position - 1).getBest().equals(submission))
                    && submission.getMayReview().booleanValue()) {
                context.put("showsummary", Boolean.TRUE);
            }
            if (size == 1) {
                context.put("showsummary", Boolean.TRUE);
            }
        }
    }

    // for the tool navigation
    if (this.assessmentService.allowManageAssessments(toolManager.getCurrentPlacement().getContext())) {
        context.put("maintainer", Boolean.TRUE);
    }

    // render
    uiService.render(ui, context);
}

From source file:org.ednovo.gooru.controllers.api.ResourceRestController.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_RESOURCE_READ })
@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(method = RequestMethod.GET, value = "/resource/signed-url/{gooruResourceId}")
public void downloadSignedResourceAsset(HttpServletRequest request, HttpServletResponse response,
        @PathVariable(GOORU_RESOURCE_ID) String gooruResourceId, @RequestParam String file) throws Exception {

    /*//from   w w  w . j a  v a 2 s. c  om
     * if(s3ResourceApiHandler.isResourceInGooruS3(gooruResourceId)) {
     * response.setContentType("application/pdf");
     * logger.warn("application/pdf Write file stream "); OutputStream os =
     * response.getOutputStream(); byte[] byteData =
     * s3ResourceApiHandler.downloadSignedResourceUrl(gooruResourceId,
     * file); os.write(byteData); os.close(); } else {
     */
    String targetUrl = response
            .encodeRedirectURL(s3ResourceApiHandler.generateSignedResourceUrl(gooruResourceId, file, true));
    logger.warn("Signed-URL: Redirecting to:" + targetUrl);
    response.sendRedirect(targetUrl);
    // }
}

From source file:org.apache.struts.taglib.TagUtils.java

/**
 * Compute a hyperlink URL based on the <code>forward</code>,
 * <code>href</code>, <code>action</code> or <code>page</code> parameter
 * that is not null. The returned URL will have already been passed to
 * <code>response.encodeURL()</code> for adding a session identifier.
 *
 * @param pageContext      PageContext for the tag making this call
 * @param forward          Logical forward name for which to look up the
 *                         context-relative URI (if specified)
 * @param href             URL to be utilized unmodified (if specified)
 * @param page             Module-relative page for which a URL should be
 *                         created (if specified)
 * @param action           Logical action name for which to look up the
 *                         context-relative URI (if specified)
 * @param params           Map of parameters to be dynamically included
 *                         (if any)//from www. j  a  v  a 2 s.c  o m
 * @param anchor           Anchor to be dynamically included (if any)
 * @param redirect         Is this URL for a <code>response.sendRedirect()</code>?
 * @param encodeSeparator  This is only checked if redirect is set to
 *                         false (never encoded for a redirect).  If true,
 *                         query string parameter separators are encoded
 *                         as &gt;amp;, else &amp; is used.
 * @param useLocalEncoding If set to true, urlencoding is done on the
 *                         bytes of character encoding from
 *                         ServletResponse#getCharacterEncoding. Use UTF-8
 *                         otherwise.
 * @return URL with session identifier
 * @throws java.net.MalformedURLException if a URL cannot be created for
 *                                        the specified parameters
 */
public String computeURLWithCharEncoding(PageContext pageContext, String forward, String href, String page,
        String action, String module, Map params, String anchor, boolean redirect, boolean encodeSeparator,
        boolean useLocalEncoding) throws MalformedURLException {
    String charEncoding = "UTF-8";

    if (useLocalEncoding) {
        charEncoding = pageContext.getResponse().getCharacterEncoding();
    }

    // TODO All the computeURL() methods need refactoring!
    // Validate that exactly one specifier was included
    int n = 0;

    if (forward != null) {
        n++;
    }

    if (href != null) {
        n++;
    }

    if (page != null) {
        n++;
    }

    if (action != null) {
        n++;
    }

    if (n != 1) {
        throw new MalformedURLException(messages.getMessage("computeURL.specifier"));
    }

    // Look up the module configuration for this request
    ModuleConfig moduleConfig = getModuleConfig(module, pageContext);

    // Calculate the appropriate URL
    StringBuffer url = new StringBuffer();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    if (forward != null) {
        ForwardConfig forwardConfig = moduleConfig.findForwardConfig(forward);

        if (forwardConfig == null) {
            throw new MalformedURLException(messages.getMessage("computeURL.forward", forward));
        }

        // **** removed - see bug 37817 ****
        //  if (forwardConfig.getRedirect()) {
        //      redirect = true;
        //  }

        if (forwardConfig.getPath().startsWith("/")) {
            url.append(request.getContextPath());
            url.append(RequestUtils.forwardURL(request, forwardConfig, moduleConfig));
        } else {
            url.append(forwardConfig.getPath());
        }
    } else if (href != null) {
        url.append(href);
    } else if (action != null) {
        ActionServlet servlet = (ActionServlet) pageContext.getServletContext()
                .getAttribute(Globals.ACTION_SERVLET_KEY);
        String actionIdPath = RequestUtils.actionIdURL(action, moduleConfig, servlet);
        if (actionIdPath != null) {
            action = actionIdPath;
            url.append(request.getContextPath());
            url.append(actionIdPath);
        } else {
            url.append(instance.getActionMappingURL(action, module, pageContext, false));
        }
    } else /* if (page != null) */
    {
        url.append(request.getContextPath());
        url.append(this.pageURL(request, page, moduleConfig));
    }

    // Add anchor if requested (replacing any existing anchor)
    if (anchor != null) {
        String temp = url.toString();
        int hash = temp.indexOf('#');

        if (hash >= 0) {
            url.setLength(hash);
        }

        url.append('#');
        url.append(this.encodeURL(anchor, charEncoding));
    }

    // Add dynamic parameters if requested
    if ((params != null) && (params.size() > 0)) {
        // Save any existing anchor
        String temp = url.toString();
        int hash = temp.indexOf('#');

        if (hash >= 0) {
            anchor = temp.substring(hash + 1);
            url.setLength(hash);
            temp = url.toString();
        } else {
            anchor = null;
        }

        // Define the parameter separator
        String separator = null;

        if (redirect) {
            separator = "&";
        } else if (encodeSeparator) {
            separator = "&amp;";
        } else {
            separator = "&";
        }

        // Add the required request parameters
        boolean question = temp.indexOf('?') >= 0;
        Iterator keys = params.keySet().iterator();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object value = params.get(key);

            if (value == null) {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('='); // Interpret null as "no value"
            } else if (value instanceof String) {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('=');
                url.append(this.encodeURL((String) value, charEncoding));
            } else if (value instanceof String[]) {
                String[] values = (String[]) value;

                for (int i = 0; i < values.length; i++) {
                    if (!question) {
                        url.append('?');
                        question = true;
                    } else {
                        url.append(separator);
                    }

                    url.append(this.encodeURL(key, charEncoding));
                    url.append('=');
                    url.append(this.encodeURL(values[i], charEncoding));
                }
            } else /* Convert other objects to a string */
            {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('=');
                url.append(this.encodeURL(value.toString(), charEncoding));
            }
        }

        // Re-add the saved anchor (if any)
        if (anchor != null) {
            url.append('#');
            url.append(this.encodeURL(anchor, charEncoding));
        }
    }

    // Perform URL rewriting to include our session ID (if any)
    // but only if url is not an external URL
    if ((href == null) && (pageContext.getSession() != null)) {
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

        if (redirect) {
            return (response.encodeRedirectURL(url.toString()));
        }

        return (response.encodeURL(url.toString()));
    }

    return (url.toString());
}