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

/**
 * {@inheritDoc}//w ww.j a  va  2  s.co  m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need an aid, then any number of parameters to form the return destination
    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 page
    else {
        destination = "/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;
    }

    context.put("assessment", assessment);
    context.put("return", destination);

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

    // if coming from restore, offer prev/next based on the archived list
    if (destination.startsWith("/assessments_restore")) {
        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:org.etudes.mneme.tool.DetailMoveView.java

/**
 * {@inheritDoc}/*from ww w  .  j a va 2s . c  om*/
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need a aid[2], detail ids[3], then any number of parameters to form the return destination
    if (params.length < 4) {
        throw new IllegalArgumentException();
    }

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

    // if not specified, go to the main pools page
    else {
        returnDest = "/pools";
    }

    String assessmentId = params[2];
    String detailIds = params[3];

    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;
    }

    // for the selected part
    Value value = this.uiService.newValue();
    context.put("selectedPartId", value);

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

    if (destination.equals("MOVE")) {
        String selectedPartId = value.getValue();
        if (selectedPartId != null) {
            try {
                Part selectedPart = assessment.getParts().getPart(selectedPartId);
                if (selectedPart != null) {
                    String dIds[] = StringUtil.split(detailIds, "+");
                    assessment.getParts().moveDetails(dIds, selectedPart);
                    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;
            }
            // back to where we came from
            destination = returnDest;
        }
    }

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

From source file:org.tsm.concharto.web.filter.LoginFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    //Has the user signed in?
    if (handleRememberMeCookie(httpRequest)) {
        //redirect to get rid of the jsessionid crap on the URL string
        //TODO - Ugh! this is the only way I know how to get rid of jsessionid.  
        //NOTE this doesn't work when you have a server port other than 80 (e.g. test server).  Not sure why.
        //There is probably another way
        //NOTE: this doesn't work for URLs that will be redirected (e.g. our "link to here" urls
        //that contain get strings.  This all incoming links with remember me cookies must not redirect.  UGH!
        if (StringUtils.isEmpty(httpRequest.getQueryString())) {
            httpResponse.sendRedirect(httpResponse.encodeRedirectURL(httpRequest.getRequestURL().toString()));
        } else {// w  w  w  . j  av a2  s  .c o  m
            String url = httpRequest.getRequestURL().toString();
            url += "?" + httpRequest.getQueryString();
            httpResponse.sendRedirect(url);
        }
        if (AuthHelper.isUserInSession(httpRequest)) {
            log.info("user " + httpRequest.getSession().getAttribute(AuthConstants.SESSION_AUTH_USERNAME)
                    + " signed in via cookie");
        }
    }

    //Does this page require authentication
    if (requiresAuthentication(httpRequest)) {
        if (!isAuthenticated(httpRequest)) {
            httpResponse.sendRedirect(
                    httpResponse.encodeRedirectURL(httpRequest.getContextPath() + REDIRECT_LOGIN));
        }
        //ok, is the user authorized for this URL
        else if (!isAuthorized(httpRequest)) {
            httpResponse.sendRedirect(
                    httpResponse.encodeRedirectURL(httpRequest.getContextPath() + REDIRECT_NOTAUTHORIZED));
        }
    }
    //setup the user context for those who can't get user and role data from
    //the session (e.g. audit interceptor)
    HttpSession session = httpRequest.getSession();
    UserContext userContext = new UserContext();
    userContext.setUsername((String) session.getAttribute(AuthConstants.SESSION_AUTH_USERNAME));
    userContext.setRoles((String) session.getAttribute(AuthConstants.SESSION_AUTH_ROLES));
    ThreadLocalUserContext.setUserContext(userContext);
    chain.doFilter(request, response);
}

From source file:ubc.pavlab.aspiredb.server.controller.SignupController.java

/**
 * This is hit when a user clicks on the confirmation link they received by email.
 * //from w w w .j  a va2  s  .c o m
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping("/confirmRegistration.html")
public void confirmRegistration(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String username = request.getParameter("username");
    String key = request.getParameter("key");

    if (StringUtils.isBlank(username) || StringUtils.isBlank(key)) {
        throw new IllegalArgumentException(
                "The confirmation url was not valid; it must contain the key and username");
    }

    boolean ok = userManager.validateSignupToken(username, key);

    if (ok) {
        super.saveMessage(request, "Your account is now enabled. Log in to continue");
        response.sendRedirect(response.encodeRedirectURL(ConfigUtils.getBaseUrl() + "home.html"));
    } else {
        super.saveMessage(request, "Sorry, your registration could not be validated. Please register again.");
        response.sendRedirect(response.encodeRedirectURL(ConfigUtils.getBaseUrl() + "home.html"));
    }

}

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

/**
 * {@inheritDoc}//from   w  w w . j  a v a  2  s  .c om
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // sort (optional)
    if ((params.length != 2) && (params.length != 3)) {
        throw new IllegalArgumentException();
    }

    // security check
    if (!assessmentService.allowManageAssessments(this.toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // default is due date, ascending
    String sort = (params.length > 2) ? params[2] : "0A";

    // for the selected select
    Values values = this.uiService.newValues();
    context.put("ids", values);

    // for the dates
    final AssessmentService assessmentService = this.assessmentService;
    PopulatingSet assessments = uiService.newPopulatingSet(new Factory() {
        public Object get(String id) {
            // add a draw to the part
            Assessment assessment = assessmentService.getAssessment(id);
            return assessment;
        }
    }, new Id() {
        public String getId(Object o) {
            return ((Assessment) o).getId();
        }
    });
    context.put("assessments", assessments);

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

    // save the dates
    for (Iterator i = assessments.getSet().iterator(); i.hasNext();) {
        Assessment assessment = (Assessment) i.next();
        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;
        }
    }

    // for an add
    if (destination.equals("ADD")) {
        try {
            Assessment assessment = this.assessmentService
                    .newAssessment(this.toolManager.getCurrentPlacement().getContext());
            destination = "/assessment_edit/" + assessment.getId() + "/assessments/" + sort;
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }
    }

    else if (destination.equals("ARCHIVE")) {
        for (String id : values.getValues()) {
            Assessment assessment = this.assessmentService.getAssessment(id);
            if (assessment != null) {
                assessment.setArchived(Boolean.TRUE);
                try {
                    this.assessmentService.saveAssessment(assessment);
                    destination = context.getDestination();
                } 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;
                }
            }
        }
    }

    else if (destination.equals("PUBLISH")) {
        for (String id : values.getValues()) {
            Assessment assessment = this.assessmentService.getAssessment(id);
            if (assessment != null) {
                try {
                    // for invalid assessments, the setPublished will be ignored
                    assessment.setPublished(Boolean.TRUE);
                    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;
                }
            }
        }

        destination = context.getDestination();
    }

    else if (destination.equals("UNPUBLISH")) {
        for (String id : values.getValues()) {
            Assessment assessment = this.assessmentService.getAssessment(id);
            if (assessment != null) {
                try {
                    assessment.setPublished(Boolean.FALSE);
                    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;
                }
            }
        }

        destination = context.getDestination();
    }

    else if (destination.equals("DELETE")) {
        for (String id : values.getValues()) {
            Assessment assessment = this.assessmentService.getAssessment(id);
            if (assessment != null) {
                try {
                    if (this.assessmentService.allowRemoveAssessment(assessment)) {
                        this.assessmentService.removeAssessment(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;
                }
            }
        }

        destination = context.getDestination();
    }

    else if (destination.startsWith("DUPLICATE:")) {
        String[] parts = StringUtil.split(destination, ":");
        if (parts.length != 2) {
            throw new IllegalArgumentException();
        }
        String aid = parts[1];
        try {
            Assessment assessment = this.assessmentService.getAssessment(aid);
            if (assessment == null) {
                throw new IllegalArgumentException();
            }
            this.assessmentService.copyAssessment(toolManager.getCurrentPlacement().getContext(), assessment);
            destination = context.getDestination();
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }
    } else if (destination.equals("/assmt_settings_choice")) {
        // add the selected ids to the destination
        StringBuilder buf = new StringBuilder();
        buf.append(destination);
        buf.append("/" + sort);
        buf.append("/");
        for (String id : values.getValues()) {
            buf.append(id);
            buf.append("+");
        }
        buf.setLength(buf.length() - 1);
        destination = buf.toString();
    } else if (destination.trim().startsWith("/assessment_export")) {
        // add the selected ids to the destination
        StringBuilder buf = new StringBuilder();
        buf.append("/assessment_export/");

        String[] ids = values.getValues();
        int count = 1;
        for (String id : ids) {
            buf.append(id);
            if (count != ids.length)
                buf.append("+");
            count++;
        }
        buf.append("/" + sort);
        buf.setLength(buf.length());
        destination = buf.toString();
    }
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
}

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

/**
 * {@inheritDoc}//from   www. java2  s .c o  m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    String subId;

    // [2]sort for /grades, [3]aid
    if (params.length < 4 || params.length > 5)
        throw new IllegalArgumentException();

    // grades sort parameter
    String gradesSortCode = params[2];
    context.put("sort_grades", gradesSortCode);

    if (params.length == 5) {
        subId = params[4];
        context.put("submissionId", subId);
        Submission submission = this.submissionService.getSubmission(subId);
        context.put("submission", submission.getBest());
    }

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

    if (this.submissionService.allowEvaluate(assessment.getContext())) {
        context.put("allowEval", Boolean.TRUE);
        context.put("grading", Boolean.TRUE);
    } else {
        context.put("allowEval", Boolean.FALSE);
    }

    // check that the assessment is not a formal course evaluation
    if (assessment.getFormalCourseEval()) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // check that if a survey, the assessment has been frozen
    if ((assessment.getType() == AssessmentType.survey) && (!assessment.getFrozen())) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

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

    context.put("assessment", assessment);

    // collect all the submissions for the assessment
    List<Submission> submissions = this.submissionService.findAssessmentSubmissions(assessment,
            SubmissionService.FindAssessmentSubmissionsSort.sdate_a, Boolean.TRUE, null, null, null, null);
    context.put("submissions", submissions);

    computePercentComplete(assessment, submissions, context);

    String userId = sessionManager.getCurrentSessionUserId();
    context.put("currentUserId", userId);

    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 = { "/signed/resource/url/{gooruResourceId}" })
public void getSignedResourceAsset(HttpServletRequest request, HttpServletResponse response,
        @PathVariable(GOORU_RESOURCE_ID) String gooruResourceId, @RequestParam String file,
        @RequestParam(value = SESSIONTOKEN, required = false) String sessionToken) throws Exception {
    String targetUrl = response
            .encodeRedirectURL(s3ResourceApiHandler.generateSignedResourceUrl(gooruResourceId, file));
    logger.warn("Signed-URL: Redirecting to:" + targetUrl);
    response.sendRedirect(targetUrl);//  w ww  .j  a  va  2 s.  c  o  m
}

From source file:cn.org.pomer.web.DirectResult.java

private void doRedirect(ActionInvocation invocation, HttpServletRequest request, HttpServletResponse response,
        String redirectLocation) throws IOException {
    if (isPathUrl(redirectLocation)) {
        if (!redirectLocation.startsWith("/")) {
            String namespace = invocation.getProxy().getNamespace();
            if ((namespace != null) && (namespace.length() > 0) && (!"/".equals(namespace))) {
                redirectLocation = namespace + "/" + redirectLocation;
            } else {
                redirectLocation = "/" + redirectLocation;
            }/* www. j  a v  a 2 s .com*/
        }
        if (prependServletContext && (request.getContextPath() != null)
                && (request.getContextPath().length() > 0)) {
            redirectLocation = request.getContextPath() + redirectLocation;
        }
    }

    if (_log.isInfoEnabled())
        _log.info("Redirect to location:" + redirectLocation);
    response.sendRedirect(response.encodeRedirectURL(redirectLocation));
}

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

/**
 * {@inheritDoc}//w  ww . j  a v  a 2  s.co m
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] source context - rest the return destination
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }
    String sourceContext = params[2];
    String returnDestination = null;

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

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

    String toolContext = toolManager.getCurrentPlacement().getContext();

    // TODO: change to assessment service ...
    if (!this.poolService.allowManagePools(toolContext)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    Values selectedAssessments = this.uiService.newValues();
    context.put("selectedAssessments", selectedAssessments);

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

    // import the assessments
    if ("IMPORT".equals(destination)) {
        Set<String> assessmentIds = new HashSet<String>();
        for (String id : selectedAssessments.getValues()) {
            assessmentIds.add(id);
        }

        try {
            this.importService.importMneme(assessmentIds, sourceContext, toolContext);
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }

        destination = returnDestination;
    }

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

From source file:org.wso2.carbon.identity.sample.extension.auth.DemoFingerprintAuthenticator.java

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

    String loginPage = IdentityUtil.getServerURL("sample-auth", true, true) + "/fpt.jsp";
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());
    try {//from www .  j a  v a 2  s  . co m
        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        }
        String callbackUrl = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
        callbackUrl = callbackUrl + "?sessionDataKey=" + context.getContextIdentifier() + "&authenticatorName="
                + getName();
        String encodedUrl = URLEncoder.encode(callbackUrl, StandardCharsets.UTF_8.name());
        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&callbackUrl="
                + encodedUrl + "&authenticators=DemoFingerprintAuthenticator:" + "LOCAL" + retryParam);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Authentication failed for the Demo Fingerprint Authenticator.",
                e);
    }
}