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.codehaus.groovy.grails.plugins.springsecurity.AjaxAwareAccessDeniedHandler.java

/**
 * {@inheritDoc}/*from w  w w.ja  v  a  2 s.com*/
 * @see org.springframework.security.web.access.AccessDeniedHandler#handle(
 *    javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
 *    org.springframework.security.access.AccessDeniedException)
 */
public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Acegi won't save the original request
        request.getSession().setAttribute(WebAttributes.SAVED_REQUEST,
                new DefaultSavedRequest(request, portResolver));
    }

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    boolean includePort = true;
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = portResolver.getServerPort(request);
    String contextPath = request.getContextPath();
    boolean inHttp = "http".equals(scheme.toLowerCase());
    boolean inHttps = "https".equals(scheme.toLowerCase());

    if (inHttp && (serverPort == 80)) {
        includePort = false;
    } else if (inHttps && (serverPort == 443)) {
        includePort = false;
    }

    String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

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

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

    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  a2  s.co  m

    try {

        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        } else {
            // Insert entry to DB only if this is not a retry
            DBUtils.insertUserResponse(context.getContextIdentifier(),
                    String.valueOf(MSSAuthenticator.UserResponse.PENDING));
        }

        //MSISDN will be saved in the context in the MSISDNAuthenticator
        String msisdn = (String) context.getProperty("msisdn");
        MSSRequest mssRequest = new MSSRequest();
        mssRequest.setMsisdnNo("+" + msisdn);
        mssRequest.setSendString(
                configurationService.getDataHolder().getMobileConnectConfig().getMSS().getMssText());

        String contextIdentifier = context.getContextIdentifier();
        MSSRestClient mssRestClient = new MSSRestClient(contextIdentifier, mssRequest);
        mssRestClient.start();

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

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

}

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

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

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

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

    if (log.isDebugEnabled()) {
        log.debug("Query parameters : " + queryParams);
    }/*  www. j a  va2 s . com*/

    try {

        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        } else {
            // Insert entry to DB only if this is not a retry
            DBUtils.insertUserResponse(context.getContextIdentifier(),
                    String.valueOf(MSSPinAuthenticator.UserResponse.PENDING));
        }

        //MSISDN will be saved in the context in the MSISDNAuthenticator
        String msisdn = (String) context.getProperty("msisdn");
        MSSRequest mssRequest = new MSSRequest();
        mssRequest.setMsisdnNo("+" + msisdn);
        mssRequest.setSendString(
                configurationService.getDataHolder().getMobileConnectConfig().getMSS().getMssPinTest());

        String contextIdentifier = context.getContextIdentifier();
        MSSRestClient mssRestClient = new MSSRestClient(contextIdentifier, mssRequest);
        mssRestClient.start();

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

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

From source file:gov.nih.nci.evs.browser.servlet.RedirectServlet.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 *
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *///  w  w w.ja  v a2s  .com

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean");
    if (licenseBean == null) {
        licenseBean = new LicenseBean();
        request.getSession().setAttribute("licenseBean", licenseBean);
    }

    String nciterm_browser_url = NCImBrowserProperties.getTermBrowserURL();

    //KLO, 020413
    String action = HTTPUtils.cleanXSS((String) request.getParameter("action"));
    String dictionary = HTTPUtils.cleanXSS((String) request.getParameter("dictionary"));
    String code = HTTPUtils.cleanXSS((String) request.getParameter("code"));
    String term_source = HTTPUtils.cleanXSS((String) request.getParameter("sab"));
    String type = HTTPUtils.cleanXSS((String) request.getParameter("type"));

    boolean licenseAgreementAccepted = false;
    String formal_name = MetadataUtils.getSABFormalName(term_source);
    boolean isLicensed = DataUtils.checkIsLicensed(term_source);

    String cs_name = Constants.CODING_SCHEME_NAME;

    if (term_source != null && isLicensed) {
        //formal_name = MetadataUtils.getSABFormalName(term_source);
        licenseAgreementAccepted = licenseBean.licenseAgreementAccepted(formal_name);
    }

    if (!isLicensed) {
        licenseAgreementAccepted = true;
    }

    if (action.equals("details")) {
        if (!licenseAgreementAccepted) {
            String url = request.getContextPath() + "/pages/accept_license.jsf?" + "dictionary=" + formal_name
                    + "&code=" + code;
            response.sendRedirect(response.encodeRedirectURL(url));

        } else {

            String url = nciterm_browser_url + "/ConceptReport.jsp?" + "dictionary=" + formal_name + "&code="
                    + code + "&type=" + type + "&sortBy=name#SynonymsDetails";

            response.sendRedirect(response.encodeRedirectURL(url));
        }

    } else if (action.equals("tree")) {
        if (!licenseAgreementAccepted) {

            String url = request.getContextPath() + "/pages/accept_license.jsf?" + "dictionary=" + formal_name
                    + "&code=" + code + "&sab=" + term_source + "&type=hierarchy";

            response.sendRedirect(response.encodeRedirectURL(url));

        } else {
            String url = request.getContextPath() + "/pages/source_hierarchy.jsf?" + "dictionary=" + dictionary
                    + "&code=" + code + "&sab=" + term_source + "&type=hierarchy";

            response.sendRedirect(response.encodeRedirectURL(url));

        }
    }
}

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

/**
 * {@inheritDoc}// ww  w .ja va  2 s .  com
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need two parameters (sid/question selector) and optional anchor
    if ((params.length != 4) && (params.length != 5)) {
        throw new IllegalArgumentException();
    }

    String submissionId = params[2];
    String questionSelector = params[3];
    String anchor = (params.length == 5) ? params[4] : null;

    // adjust the current destination to remove the anchor
    String curDestination = context.getDestination();
    if (anchor != null) {
        int pos = curDestination.lastIndexOf("/");
        curDestination = curDestination.substring(0, pos);
    }

    // if (!context.getPostExpected())
    // {
    // // redirect to error
    // res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unexpected)));
    // return;
    // }

    // collect the questions (actually their answers) to put on the page
    List<Answer> answers = new ArrayList<Answer>();

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

    // setup receiving context
    Errors err = questionSetup(submission, questionSelector, context, answers, false);
    if (Errors.invalid == err)
        err = Errors.invalidpost;
    if (err != null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + err)));
        return;
    }

    // read 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")));

    // if we are going to submitted, we must complete the submission (unless there was an upload error)
    Boolean complete = Boolean.valueOf((!uploadError) && destination.startsWith("/submitted"));

    // unless we are going to list, instructions, or this very same question, or we have a file upload error, mark the
    // answers as complete
    Boolean answersComplete = Boolean.valueOf(!(uploadError || destination.startsWith("/list")
            || destination.startsWith("STAY") || destination.startsWith("/instructions")
            || destination.equals(context.getPreviousDestination())));

    // and if we are working in a random access test, answers are always complete
    if (submission.getAssessment().getRandomAccess())
        answersComplete = Boolean.TRUE;

    // post-process the answers
    for (Answer answer : answers) {
        answer.getTypeSpecificAnswer().consolidate(destination);
    }

    // where are we going?
    destination = questionChooseDestination(context, destination, questionSelector, submissionId,
            curDestination);

    // submit all answers
    try {
        submissionService.submitAnswers(answers, answersComplete, complete);

        // if there was an upload error, send to the upload error
        if ((req.getAttribute("upload.status") != null) && (!req.getAttribute("upload.status").equals("ok"))) {
            res.sendRedirect(res.encodeRedirectURL(
                    Web.returnUrl(req, "/error/" + Errors.upload + "/" + req.getAttribute("upload.limit"))));
            return;
        }

        if (destination.equals("SUBMIT")) {
            // get the submission again, to make sure that the answers we just posted are reflected
            submission = submissionService.getSubmission(submissionId);

            // if linear, or the submission is all answered, we can complete the submission and go to submitted
            if ((!submission.getAssessment().getRandomAccess()) || (submission.getIsAnswered())) {
                submissionService.completeSubmission(submission);

                destination = "/submitted/" + submissionId;
            }

            // if not linear, and there are unanswered parts, send to final review
            else {
                destination = "/final_review/" + submissionId;
            }
        }

        // redirect to the next destination
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
        return;
    } catch (AssessmentClosedException e) {
    } catch (SubmissionCompletedException e) {
    } catch (AssessmentPermissionException e) {
    }

    // redirect to error
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
}

From source file:org.dspace.app.webui.servlet.HandleServlet.java

/**
 * Check to see if a browse or search button has been pressed on a community
 * or collection home page. If so, redirect to the appropriate URL.
 * //from  w w w.ja v a  2 s.  c o m
 * @param request
 *            HTTP request
 * @param response
 *            HTTP response
 * @param handle
 *            Handle of the community/collection home page
 * 
 * @return true if a browse/search button was pressed and the user was
 *         redirected
 */
private boolean handleButton(HttpServletRequest request, HttpServletResponse response, String handle)
        throws IOException {
    String button = UIUtil.getSubmitButton(request, "");
    String location = request.getParameter("location");
    String prefix = "/";
    String url = null;

    if (location == null) {
        return false;
    }

    /*
     * Work out the "prefix" to which to redirect If "/", scope is all of
     * DSpace, so prefix is "/" If prefix is a handle, scope is a community
     * or collection, so "/handle/1721.x/xxxx/" is the prefix.
     */
    if (!location.equals("/")) {
        prefix = "/handle/" + location + "/";
    }

    if (button.equals("submit_search") || (request.getParameter("query") != null)) {
        /*
         * Have to check for search button and query - in some browsers,
         * typing a query into the box and hitting return doesn't produce a
         * submit button parameter. Redirect to appropriate search page
         */
        url = request.getContextPath() + prefix + "simple-search?query="
                + URLEncoder.encode(request.getParameter("query"), Constants.DEFAULT_ENCODING);
    }

    // If a button was pressed, redirect to appropriate page
    if (url != null) {
        response.sendRedirect(response.encodeRedirectURL(url));

        return true;
    }

    return false;
}

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

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

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

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

    boolean fixMode = params[1].equals("question_fix");
    String questionId = params[2];
    String assessmentId = params[3];
    String partId = params[4];

    String origPartId = partId;
    Assessment assessment = null;
    Part origPart = null;
    Part part = null;

    // get the assessment if specified
    if ((!"0".equals(assessmentId)) && (!"-".equals(assessmentId))) {
        assessment = this.assessmentService.getAssessment(assessmentId);
        if (assessment == null) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        }

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

        // get part id if specified
        if ((!"0".equals(partId)) && (!"-".equals(partId))) {
            origPart = assessment.getParts().getPart(partId);
            if (origPart == null) {
                // redirect to error
                res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
                return;
            }
            part = origPart;
        }
    }

    // get the question to work on
    Question question = this.questionService.getQuestion(questionId);
    if (question == null)
        throw new IllegalArgumentException();

    // put the question in the context
    context.put("question", question);

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

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

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

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

    // save the attachments upload
    if (upload.getUpload() != null) {
        question.getPresentation().addAttachment(upload.getUpload());
    }

    // handle an attachments remove
    if (destination.startsWith("REMOVE:")) {
        String[] parts = StringUtil.split(destination, ":");
        if (parts.length != 2) {
            throw new IllegalArgumentException();
        }
        String refString = parts[1];
        Reference ref = this.entityManager.newReference(refString);

        // remove from the assessment, but since the attachment was in the site's mneme docs and generally available, don't remove it
        question.getPresentation().removeAttachment(ref);
        // this.attachmentService.removeAttachment(ref);

        // stay here
        destination = context.getDestination();
    }

    // consolidate the question
    destination = question.getTypeSpecificQuestion().consolidate(destination);

    try {
        // save
        if ((!fixMode) && "RETYPE".equals(destination)) {
            // save and re-type
            this.questionService.saveQuestionAsType(question, newType.getValue());
        }

        else {
            // just save - even if historical
            Boolean changed = question.getIsChanged();
            this.questionService.saveQuestion(question, Boolean.TRUE);

            // possible re-score needed if the assessment is locked
            if (fixMode && changed && (assessment != null) && assessment.getIsLocked()) {
                this.assessmentService.rescoreAssessment(assessment);
            }
        }

        // update the assessment part details if the question is not mint (not for fix)
        if ((!fixMode) && (assessment != null) && (origPart != null) && (!question.getMint())) {
            // see if the user changed the part from the original
            String newPartId = value.getValue();
            if (!origPart.getId().equals(newPartId)) {
                // see if the user wants a new part
                if ("0".equals(newPartId)) {
                    // create the new part
                    try {
                        Part created = assessment.getParts().addPart();
                        this.assessmentService.saveAssessment(assessment);

                        // here's the new id
                        newPartId = created.getId();
                    } 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;
                    }
                }

                // get the desired part
                Part newPart = assessment.getParts().getPart(newPartId);
                if (newPart != null) {
                    // remove the question from the old part (fails quietly if it was not there)
                    part.removePickDetail(question);
                    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;
                    }

                    // set part and partId to the desired part
                    part = newPart;
                    partId = part.getId();
                }
            }

            // add to the desired part
            if (part != null) {
                part.addPickDetail(question);
                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 ((!fixMode) && "ADD".equals(destination)) {
            destination = null;

            // setup a new question of the same type in the same pool
            try {
                Question newQuestion = this.questionService.newQuestion(question.getPool(), question.getType());

                // edit it
                destination = "/" + params[1] + "/" + newQuestion.getId() + "/" + assessmentId + "/" + partId
                        + "/" + returnDestination;
            } catch (AssessmentPermissionException e) {
                // redirect to error
                res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
                return;
            }
        }
    } catch (AssessmentPermissionException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    } catch (GradesRejectsAssessmentException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    if (("NEXT".equals(destination) || "PREV".equals(destination))) {
        // figure out the question id
        String returnDestParts[] = StringUtil.split(returnDestination, "/");
        String sortCode = "0A";
        if (!"-".equals(returnDestParts[3]))
            sortCode = returnDestParts[3];

        QuestionService.FindQuestionsSort sort = PoolEditView.findSort(sortCode);

        // get questions
        List<Question> questions = questionService.findQuestions(question.getPool(), sort, null, null, null,
                null, null, null);

        // find this one
        int pos = 0;
        for (Question q : questions) {
            if (q.equals(question)) {
                break;
            }
            pos++;
        }

        // find next/prev w/ wrapping
        if ("NEXT".equals(destination)) {
            if (pos == questions.size() - 1) {
                pos = 0;
            } else {
                pos++;
            }
        } else {
            if (pos == 0) {
                pos = questions.size() - 1;
            } else {
                pos--;
            }
        }

        String qid = questionId;
        if ((pos >= 0) && (pos <= questions.size() - 1)) {
            qid = questions.get(pos).getId();
        }

        destination = "/" + params[1] + "/" + qid + "/" + assessmentId + "/" + partId + "/" + returnDestination;
    }

    // if destination became null, or is the stay here
    if ((destination == null) || ("STAY".equals(destination) || "RETYPE".equals(destination))) {
        destination = context.getDestination();
    }

    // adjust destination for proper part
    if ((!fixMode) && (!partId.equals(origPartId))) {
        String[] destParts = StringUtil.split(destination, "/");
        if (destParts[1].equals(params[1])) {
            destParts[4] = part.getId();
            destination = StringUtil.unsplit(destParts, 0, destParts.length, "/");
        }
    }

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

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

/**
 * Allow subclasses to modify the redirection message.
 *
 * @param request the request/*from   w  w  w . j  av  a2s .  c  om*/
 * @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 {
    // FIXME - this method is a mess.  clean it up.
    if (!url.equals(this.getAuthenticationFailureUrl()) && !url.equals("/DEFAULT_VIRTUAL_WIKI")) {
        // if Acegi has saved a redirect URL then use that
        super.sendRedirect(request, response, url);
        return;
    }
    String target = request.getParameter("target");
    String targetUrl = url;
    if (url.equals("/DEFAULT_VIRTUAL_WIKI")) {
        // 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;
        }
        if (StringUtils.isBlank(target)) {
            target = Environment.getValue(Environment.PROP_BASE_DEFAULT_TOPIC);
            try {
                VirtualWiki virtualWiki = WikiBase.getDataHandler().lookupVirtualWiki(virtualWikiName);
                target = virtualWiki.getDefaultTopicName();
            } catch (Exception e) {
                logger.warning("Unable to retrieve default topic for virtual wiki", e);
            }
        }
        targetUrl = request.getContextPath() + "/" + virtualWikiName + "/" + target;
    } else if (!url.startsWith("http://") && !url.startsWith("https://")) {
        String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
        targetUrl = request.getContextPath() + "/" + virtualWiki + url;
        if (!StringUtils.isBlank(target)) {
            targetUrl += (url.indexOf('?') == -1) ? "?" : "&";
            targetUrl += "target=" + URLEncoder.encode(target, "UTF-8");
        }
    }
    response.sendRedirect(response.encodeRedirectURL(targetUrl));
}

From source file:org.wso2.carbon.identity.authenticator.tiqr.TiqrAuthenticator.java

/**
 * initiate the authentication request/*from w w w  .  ja  v a  2s . c  om*/
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    try {
        Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
        if (authenticatorProperties != null) {
            String retryParam = "";
            if (context.isRetrying()) {
                retryParam = "&authFailure=true";
                if (request.getParameter(TiqrConstants.TIQR_ACTION)
                        .equals(TiqrConstants.TIQR_ACTION_ENROLLMENT)) {
                    retryParam = retryParam + "&authFailureMsg=enrollment.fail.message";
                } else {
                    retryParam = retryParam + "&authFailureMsg=authentication.fail.message";
                }
            }
            String enrollmentPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL()
                    .replace(TiqrConstants.LOGIN_PAGE, TiqrConstants.TIQR_PAGE);
            String tiqrAction = StringUtils.isEmpty(request.getParameter(TiqrConstants.TIQR_ACTION))
                    ? TiqrConstants.TIQR_ACTION_AUTHENTICATION
                    : request.getParameter(TiqrConstants.TIQR_ACTION);
            String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                    context.getCallerSessionKey(), context.getContextIdentifier());
            response.sendRedirect(response.encodeRedirectURL(enrollmentPage + ("?" + queryParams))
                    + TiqrConstants.AUTHENTICATORS + getName() + ":" + TiqrConstants.LOCAL + "&"
                    + TiqrConstants.TIQR_CLIENT_IP + "="
                    + authenticatorProperties.get(TiqrConstants.TIQR_CLIENT_IP) + "&"
                    + TiqrConstants.TIQR_CLIENT_PORT + "="
                    + authenticatorProperties.get(TiqrConstants.TIQR_CLIENT_PORT) + "&"
                    + TiqrConstants.TIQR_ACTION + "=" + tiqrAction + retryParam);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Error while retrieving properties. Authenticator Properties cannot be null");
            }
            throw new AuthenticationFailedException(
                    "Error while retrieving properties. Authenticator Properties cannot be null");
        }
    } catch (IOException e) {
        throw new AuthenticationFailedException("Exception while redirecting the page: " + e.getMessage(), e);
    }
}

From source file:org.opennms.web.asset.ImportAssetsServlet.java

/**
 * {@inheritDoc}/*from  w  w  w . j  av  a2  s  .c om*/
 *
 * Acknowledge the events specified in the POST and then redirect the client
 * to an appropriate URL for display.
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String assetsText = request.getParameter("assetsText");

    if (assetsText == null) {
        logger.error("assetsText was null");
        throw new MissingParameterException("assetsText");
    }

    try {
        List<Asset> assets = this.decodeAssetsText(assetsText);
        List<Integer> nodesWithAssets = this.getCurrentAssetNodesList();

        for (Asset asset : assets) {
            // update with the current information
            asset.setUserLastModified(request.getRemoteUser());
            asset.setLastModifiedDate(new Date());

            if (nodesWithAssets.contains(Integer.valueOf(asset.getNodeId()))) {
                logger.debug("modifyAsset call for asset:'{}'", asset);
                this.model.modifyAsset(asset);
            } else {
                logger.debug("createAsset:'{}'", asset);
                this.model.createAsset(asset);
            }
        }

        StringBuffer messageText = new StringBuffer();
        messageText.append("Successfully imported ").append(assets.size()).append(" asset");
        if (assets.size() > 1) {
            messageText.append("s");
        }
        messageText.append(".");

        if (errors.size() > 0) {
            messageText.append("  ").append(errors.size()).append(" non-fatal errors occurred:");
            for (String error : errors) {
                messageText.append("<br />").append(error);
            }
        }

        request.getSession().setAttribute("message", messageText.toString());
        response.sendRedirect(response.encodeRedirectURL(this.redirectSuccess + "&showMessage=true"));
    } catch (AssetException e) {
        String message = "Error importing assets: " + e.getMessage();
        redirectWithErrorMessage(request, response, e, message);
    } catch (SQLException e) {
        String message = "Database exception importing assets: " + e.getMessage();
        redirectWithErrorMessage(request, response, e, message);
    }
}