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:org.jahia.bin.JahiaAdministration.java

/**
 * Display the login page, using doRedirect().
 *
 * @param request  Servlet request.//from w w w.j  a  v  a 2  s. com
 * @param response Servlet response.
 * @param session  Servlet session for the current user.
 */
private void displayLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException, ServletException {
    if (!response.isCommitted()) {
        request.getRequestDispatcher(Login.getServletPath() + "?redirect="
                + URLEncoder.encode((request.getContextPath() + servletPath).replaceAll("//", "/"), "UTF-8"))
                .forward(request, response);
    } else {
        response.sendRedirect(response.encodeRedirectURL(Login.getServletPath() + "?redirect="
                + URLEncoder.encode((request.getContextPath() + servletPath).replaceAll("//", "/"), "UTF-8")));
    }
}

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

/**
 * {@inheritDoc}/*ww w .j  ava2s . com*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need a single parameter (aid), then return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

    String assessmentId = 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);

    // get the assessment
    Assessment assessment = assessmentService.getAssessment(assessmentId);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // get the submissions from the user to this assessment
    Submission submission = submissionService.getNewUserAssessmentSubmission(assessment, null);
    if (submission == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // check for closed or frozen (test drive can skip this)
    if (!submission.getIsTestDrive()) {
        if (submission.getAssessment().getDates().getIsClosed().booleanValue()
                || submission.getAssessment().getFrozen().booleanValue()) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.closed)));
            return;
        }
    }

    // security check (submissions count / allowed check)
    if (!submissionService.allowSubmit(submission)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

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

    // collect information: the selected assessment (id the request)
    context.put("assessment", submission.getAssessment());

    // 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.etudes.mneme.tool.AssessmentSettingsView.java

/**
 * {@inheritDoc}//from  w  w  w  . j ava2 s.c  o m
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // aid and return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

    String assessmentId = params[2];

    String returnDestination = null;
    if (params.length > 3) {
        returnDestination = "/" + StringUtil.unsplit(params, 3, params.length - 3, "/");
    }

    // if not specified, go to the main assessment view
    else {
        returnDestination = "/assessments";
    }

    Assessment assessment = assessmentService.getAssessment(assessmentId);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // security check
    if (!assessmentService.allowEditAssessment(assessment)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // setup the model: the selected assessment
    context.put("assessment", assessment);

    // read the form
    String destination = uiService.decode(req, context);

    boolean sendResultsEmail = false;
    boolean sendEvalEmail = false;

    // if publish, set
    if ("PUBLISH".equals(destination)) {
        assessment.setPublished(Boolean.TRUE);
        destination = returnDestination;
    }

    else if ("SAVE".equals(destination)) {
        destination = context.getDestination();
    }

    else if (destination.equals("SURVEY")) {
        // change to survey
        assessment.setType(AssessmentType.survey);

        destination = context.getDestination();
    }

    else if (destination.equals("SEND")) {
        // we will do it later, after we save
        sendResultsEmail = true;

        destination = context.getDestination();
    }

    else if (destination.equals("EVALSEND")) {
        // we will do it later, after we save
        sendEvalEmail = true;

        destination = context.getDestination();
    }

    //If Show Summary of Data is checked,
    if (assessment.getReview().getShowSummary())
        assessment.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
    // commit the save
    try {
        this.assessmentService.saveAssessment(assessment);
    } catch (AssessmentPermissionException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    } catch (AssessmentPolicyException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.policy)));
        return;
    }

    // if we need to send the results email, do so after the save
    if (sendResultsEmail) {
        this.assessmentService.sendResults(assessment);
    }
    // if we need to send the evaluation email, do so after the save
    if (sendEvalEmail) {
        this.assessmentService.sendEvalNotification(assessment);
    }

    // if destination became null
    if (destination == null) {
        destination = context.getDestination();
    }

    // if destination is stay here
    else if (destination.startsWith("STAY:")) {
        String[] parts = StringUtil.splitFirst(destination, ":");
        destination = context.getDestination() + "?focus=" + parts[1];
    }

    // redirect to the next destination
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
}

From source file:org.wso2.carbon.identity.application.authenticator.fido.FIDOAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    //FIDO BE service component
    U2FService u2FService = U2FService.getInstance();
    try {/*from w w w  . ja  v a  2s  . c o  m*/
        //authentication page's URL.
        String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
        loginPage = loginPage.replace("login.do", "authentication.jsp");
        //username from basic authenticator.
        AuthenticatedUser user = getUsername(context);
        //origin as appID eg.: http://example.com:8080
        String appID = FIDOUtil.getOrigin(request);
        //calls BE service method to generate challenge.
        FIDOUser fidoUser = new FIDOUser(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain(),
                appID);
        AuthenticateRequestData data = u2FService.startAuthentication(fidoUser);
        //redirect to FIDO login page
        if (data != null) {

            response.sendRedirect(response.encodeRedirectURL(loginPage + ("?")) + "&authenticators=" + getName()
                    + ":" + "LOCAL" + "&type=fido&sessionDataKey=" + request.getParameter("sessionDataKey")
                    + "&data=" + data.toJson());
        } else {
            String redirectURL = loginPage.replace("authentication.jsp", "retry.do");
            redirectURL = response.encodeRedirectURL(redirectURL + ("?")) + "&failedUsername="
                    + URLEncoder.encode(user.getUserName(), IdentityCoreConstants.UTF_8) + "&statusMsg="
                    + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_ERROR_MESSAGE,
                            IdentityCoreConstants.UTF_8)
                    + "&status=" + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_STATUS,
                            IdentityCoreConstants.UTF_8);
            response.sendRedirect(redirectURL);
        }

    } catch (IOException e) {
        throw new AuthenticationFailedException("Could not initiate FIDO authentication request", e);
    }
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

private void shutdown(Adapter adapter, HttpSession session, Exception e, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // attempt to shutdown processor
    if (adapter != null) {
        try {/*  ww  w  .j a  va2  s  .  co m*/
            adapter.shutdown();
        } catch (XFormsException xe) {
            logger.log(Level.WARNING, "Error shutting down Chiba bean.", xe);
        }
    }

    // store exception
    session.setAttribute("chiba.exception", e);

    // redirect to error page, if set
    if (errPage != null)
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/" + errPage));
    else if (e.getMessage().startsWith("could not create document container"))
        // This specific message is so misleading, so we'll change it
        // to what it really means.
        throw new ServletException("XForms xml parsing error. " + "Please check the XForm for xml errors.", e);
    else
        throw new ServletException(e);
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    String action = request.getParameter("Action");
    String name = request.getParameter("Name");
    String value = request.getParameter("Value");
    String age = request.getParameter("MaxAge");

    String nextUrl = getURI(request) + "?R=" + redirectCount++;
    if (action.equals("New Session")) {
        session = request.getSession(true);
    } else if (session != null) {
        if (action.equals("Invalidate"))
            session.invalidate();//  w w w.j ava2 s . c o  m
        else if (action.equals("Set")) {
            session.setAttribute(name, value);
            try {
                int m = Integer.parseInt(age);
                session.setMaxInactiveInterval(m);
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }
        } else if (action.equals("Remove"))
            session.removeAttribute(name);
    }

    String encodedUrl = response.encodeRedirectURL(nextUrl);
    response.sendRedirect(encodedUrl);

}

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

/**
 * {@inheritDoc}/* w  w w  . j  a v  a 2s.c  om*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // aid and return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

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

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

    Assessment assessment = assessmentService.getAssessment(assessmentId);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // security check
    if (!assessmentService.allowEditAssessment(assessment)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // check for formal course evaluation permission
    if (assessmentService.allowSetFormalCourseEvaluation(assessment.getContext())) {
        context.put("allowEval", Boolean.TRUE);
    }

    // format an invalid message
    if ((!assessment.getIsValid()) && (!assessment.getPublished())) {
        context.put("invalidMsg", AssessmentInvalidView.formatInvalidDisplay(assessment, this.messages));
    }

    // format part list of zero parts
    if (assessment.getHasPoints()) {
        boolean showWarning = false;
        StringBuilder buf = new StringBuilder("<ul>");
        Object args[] = new Object[1];
        for (Part part : assessment.getParts().getParts()) {
            // for valid, 0 point parts that are not all survey questions (i.e. that have details that support points)
            if ((part.getTotalPoints().floatValue() == 0f) && (part.getIsValid())) {
                for (PartDetail detail : part.getDetails()) {
                    if (detail.getHasPoints()) {
                        args[0] = part.getTitle();
                        if (args[0] == null)
                            args[0] = part.getOrdering().getPosition().toString();
                        buf.append("<li>" + this.messages.getFormattedMessage("part", args) + "</li>");
                        showWarning = true;
                        break;
                    }
                }
            }
        }

        if (showWarning) {
            buf.append("</ul>");
            context.put("zeroMsg", buf.toString());
        }
    }

    try {
        Site site = this.siteService.getSite(toolManager.getCurrentPlacement().getContext());
        ToolConfiguration config = site.getToolForCommonId("sakai.mneme");
        if (config != null)
            toolId = config.getId();
        context.put("toolId", toolId);
    } catch (IdUnusedException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // collect information: the selected assessment
    context.put("assessment", assessment);

    // check if we have gradebook
    context.put("gradebookAvailable", this.gradesService.available(assessment.getContext()));

    // if we have a focus parameter
    String focus = req.getParameter("focus");
    if (focus != null)
        context.addFocusId(focus);
    new CKSetup().setCKCollectionAttrib(getDocsPath(), toolManager.getCurrentPlacement().getContext());

    // if coming from edit, offer prev/next based on the archived list
    if (destination.startsWith("/assessment_edit")) {
        figurePrevNext(context, destination, assessment, true);
    }

    // if coming from assessments, we offer prev/next
    // assessments/0A
    else if (destination.startsWith("/assessments")) {
        figurePrevNext(context, destination, assessment, false);
    }

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

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

private ModelAndView serveRedirectToSitePath(SitePath toSitePath, int redirectStatus,
        HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

    SiteBasePath siteBasePath = SiteBasePathResolver.resolveSiteBasePath(httpRequest, toSitePath.getSiteKey());
    SiteBasePathAndSitePath siteBasePathAndSitePath = new SiteBasePathAndSitePath(siteBasePath, toSitePath);

    SiteBasePathAndSitePathToStringBuilder siteBasePathAndSitePathToStringBuilder = new SiteBasePathAndSitePathToStringBuilder();
    siteBasePathAndSitePathToStringBuilder.setEncoding("UTF-8");
    siteBasePathAndSitePathToStringBuilder.setHtmlEscapeParameterAmps(false);
    siteBasePathAndSitePathToStringBuilder.setIncludeFragment(true);
    siteBasePathAndSitePathToStringBuilder.setIncludeParamsInPath(true);
    siteBasePathAndSitePathToStringBuilder.setUrlEncodePath(true);
    String redirectUrl = siteBasePathAndSitePathToStringBuilder.toString(siteBasePathAndSitePath);

    String encodedRedirectUrl = httpResponse.encodeRedirectURL(redirectUrl);

    if (redirectStatus == HttpServletResponse.SC_MOVED_PERMANENTLY) {
        httpResponse.setStatus(redirectStatus);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    } else {/*  w  w w . j  a  v a2  s.  c  o m*/
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    }
}

From source file:org.muse.mneme.tool.AttachmentsView.java

/**
 * {@inheritDoc}/*from ww  w .  j  a  v a2 s. c o  m*/
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // one parameter
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String type = params[2];

    // get getting called twice for some reason...
    if (type.equals("null")) {
        M_log.warn("post: /null detected");
        return;
    }

    // for the upload of attachments
    Upload upload = new Upload(this.toolManager.getCurrentPlacement().getContext(), AttachmentService.DOCS_AREA,
            false, this.attachmentService);
    context.put("upload", upload);

    // read the form
    String destination = uiService.decode(req, context);

    // check for file upload error
    boolean uploadError = ((req.getAttribute("upload.status") != null)
            && (!req.getAttribute("upload.status").equals("ok")));

    // save the attachments upload
    if (upload.getUpload() != null) {
        Reference ref = upload.getUpload();
    }

    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
}

From source file:org.muse.mneme.tool.SelectAddPartQuestionsView.java

/**
 * {@inheritDoc}//from  w  ww.  j av a  2 s .  c  om
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2]sort for /assessment, [3]aid |[4] pid |optional->| [5]our sort, [6]our page, [7] our type filter,
    // [8] our pool filter [9] our survey filter (B-both, A-assessment, S-survey)
    if (params.length < 5 || params.length > 10)
        throw new IllegalArgumentException();

    // assessment view sort
    String assessmentSort = params[2];
    context.put("assessmentSort", assessmentSort);

    // assessment
    String assessmentId = params[3];
    Assessment assessment = assessmentService.getAssessment(params[3]);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }
    context.put("assessment", assessment);

    // security check
    if (!assessmentService.allowEditAssessment(assessment)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // part
    String partId = params[4];
    ManualPart part = (ManualPart) assessment.getParts().getPart(params[4]);
    if (part == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }
    context.put("part", part);

    // sort
    String sortCode = "0A";
    if (params.length > 5)
        sortCode = params[5];
    if ((sortCode == null) || (sortCode.length() != 2)) {
        throw new IllegalArgumentException();
    }
    context.put("sort_column", sortCode.charAt(0));
    context.put("sort_direction", sortCode.charAt(1));
    QuestionService.FindQuestionsSort sort = findQuestionSortCode(sortCode);

    String typeFilter = (params.length > 7) ? params[7] : "0";
    context.put("typeFilter", typeFilter);

    // the question types
    List<QuestionPlugin> questionTypes = this.mnemeService.getQuestionPlugins();
    context.put("questionTypes", questionTypes);

    String poolFilter = (params.length > 8) ? params[8] : "0";
    context.put("poolFilter", poolFilter);
    Pool pool = poolFilter.equals("0") ? null : this.poolService.getPool(poolFilter);

    String surveyFilter = (params.length > 9) ? params[9] : "B";
    context.put("surveyFilter", surveyFilter);

    // the pools
    List<Pool> pools = this.poolService.getPools(toolManager.getCurrentPlacement().getContext());
    context.put("pools", pools);

    // survey filter
    Boolean surveyFilterValue = null;
    if ("A".equals(surveyFilter)) {
        surveyFilterValue = Boolean.FALSE;
    } else if ("S".equals(surveyFilter)) {
        surveyFilterValue = Boolean.TRUE;
    }

    // paging
    Integer maxQuestions = null;
    if (pool == null) {
        maxQuestions = this.questionService.countQuestions(this.toolManager.getCurrentPlacement().getContext(),
                null, (typeFilter.equals("0") ? null : typeFilter), surveyFilterValue, Boolean.TRUE);
    } else {
        maxQuestions = this.questionService.countQuestions(pool, null,
                (typeFilter.equals("0") ? null : typeFilter), surveyFilterValue, Boolean.TRUE);
    }
    String pagingParameter = "1-" + Integer.toString(this.pageSizes.get(0));
    if (params.length > 6)
        pagingParameter = params[6];
    Paging paging = uiService.newPaging();
    paging.setMaxItems(maxQuestions);
    paging.setCurrentAndSize(pagingParameter);
    context.put("paging", paging);

    // get questions
    List<Question> questions = null;

    if (pool == null) {
        questions = questionService.findQuestions(this.toolManager.getCurrentPlacement().getContext(), sort,
                null, (typeFilter.equals("0") ? null : typeFilter),
                paging.getSize() == 0 ? null : paging.getCurrent(),
                paging.getSize() == 0 ? null : paging.getSize(), surveyFilterValue, Boolean.TRUE);
    } else {
        questions = questionService.findQuestions(pool, sort, null,
                (typeFilter.equals("0") ? null : typeFilter),
                paging.getSize() == 0 ? null : paging.getCurrent(),
                paging.getSize() == 0 ? null : paging.getSize(), surveyFilterValue, Boolean.TRUE);
    }
    context.put("questions", questions);

    // compute the current destination, except for being at page one
    // this will match "current" in the filter dropdown values, which are all set to send to page one.
    // [2]sort for /assessment, [3]aid |[4] pid |optional->| [5]our sort, [6]our page, [7] our type filter, [8] our pool filter, [9] survey filter
    String newDestination = "/" + params[1] + "/" + params[2] + "/" + params[3] + "/" + params[4] + "/"
            + sortCode + "/" + "1" + "-" + paging.getSize().toString() + "/" + typeFilter + "/" + poolFilter
            + "/" + surveyFilter;

    // for the selected question type
    Value value = this.uiService.newValue();
    value.setValue(newDestination);
    context.put("selectedQuestionType", value);

    // for the selected pool
    value = this.uiService.newValue();
    value.setValue(newDestination);
    context.put("selectedPool", value);

    // for the survey filter
    value = this.uiService.newValue();
    value.setValue(newDestination);
    context.put("selectedQuestionSurvey", value);

    // pages sizes
    if (this.pageSizes.size() > 1) {
        context.put("pageSizes", this.pageSizes);
    }

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