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:jease.cms.web.servlet.JeaseController.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    String uri = request.getRequestURI();

    // Strip jsessionid from URI.
    int jsessionidIndex = uri.indexOf(";jsessionid=");
    if (jsessionidIndex != -1) {
        uri = uri.substring(0, jsessionidIndex);
    }//ww  w . j a  va2  s.c o m

    // Process internal context prefix
    int tilde = uri.indexOf("~");
    if (tilde != -1) {
        String path = uri.substring(tilde + 1);
        response.sendRedirect(response
                .encodeRedirectURL(buildURI(request.getContextPath() + path, request.getQueryString())));
        return;
    }

    // Try to resolve node from URI (without context path).
    String nodePath = uri.substring(request.getContextPath().length());
    Node node = Nodes.getByPath(nodePath);

    // Process redirect rules
    if (node == null && !servlets.matcher(nodePath).matches()) {
        String sourceURI = buildURI(nodePath, request.getQueryString());
        String targetURI = rewriteURI(sourceURI);
        if (!targetURI.equals(sourceURI)) {
            if (targetURI.contains("://")) {
                response.sendRedirect(response.encodeRedirectURL(targetURI));
            } else {
                response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + targetURI));
            }
            return;
        }
    }

    // Save "virtual" root node. Per default it is the absolute root of the
    // instance.
    // If a node with the server name exists, this node is used as virtual
    // root.
    if (request.getAttribute("Root") == null) {
        String server = Servlets.getServerName(request).replaceFirst("www.", "");
        Node root = Nodes.getRoot() != null ? Nodes.getRoot().getChild(server) : null;
        if (root == null) {
            root = Nodes.getRoot();
        }
        if (node != null) {
            if (node.getParent() == root && locales.contains(node.getId())) {
                root = node;
            } else {
                for (Node parent : node.getParents()) {
                    if (parent.getParent() == root && locales.contains(parent.getId())) {
                        root = parent;
                        break;
                    }
                }
            }
        }
        request.setAttribute("Root", root);
        if (node != null && root.getParent() == node) {
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + root.getPath()));
            return;
        }
    }

    // If no node is found, process filter chain.
    if (node == null) {
        chain.doFilter(request, response);
        return;
    }

    // Redirect if trailing slash is missing for containers.
    if (node.isContainer() && !uri.endsWith("/")) {
        response.sendRedirect(response.encodeRedirectURL(buildURI(uri + "/", request.getQueryString())));
    } else {
        // Set node into request scope and forward to dispatcher
        request.setAttribute(Node.class.getSimpleName(), node);
        request.setAttribute(Names.JEASE_SITE_DISPATCHER, dispatcher);
        Function<String, String> rewriter = StringUtils.isNotBlank(
                Registry.getParameter(Names.JEASE_SITE_REWRITER)) ? Database.query(rewriterSupplier) : null;
        request.getRequestDispatcher(dispatcher).forward(request,
                rewriter != null ? new ResponseRewriter(response, rewriter) : response);
    }
}

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

/**
 * {@inheritDoc}//from ww  w. ja v  a2 s.  c o  m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // 0 or 1 parameters
    if ((params.length != 2) && (params.length != 3)) {
        throw new IllegalArgumentException();
    }

    // optional sort parameter
    String sortCode = null;
    if (params.length == 3) {
        sortCode = params[2];
    }

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

    // SORT: 0|1|2|3 A|D - 2 chars, column | direction
    if ((sortCode != null) && (sortCode.length() != 2)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    SubmissionService.GetUserContextSubmissionsSort sort = SubmissionService.GetUserContextSubmissionsSort.title_a;
    if (sortCode != null) {
        context.put("sort_column", sortCode.charAt(0));
        context.put("sort_direction", sortCode.charAt(1));

        // 0 is title
        if ((sortCode.charAt(0) == '0') && (sortCode.charAt(1) == 'A')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.title_a;
        } else if ((sortCode.charAt(0) == '0') && (sortCode.charAt(1) == 'D')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.title_d;
        }

        // 1 is status
        else if ((sortCode.charAt(0) == '1') && (sortCode.charAt(1) == 'A')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.status_a;
        } else if ((sortCode.charAt(0) == '1') && (sortCode.charAt(1) == 'D')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.status_d;
        }

        // 2 is due date
        else if ((sortCode.charAt(0) == '2') && (sortCode.charAt(1) == 'A')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.dueDate_a;
        } else if ((sortCode.charAt(0) == '2') && (sortCode.charAt(1) == 'D')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.dueDate_d;
        }

        // 3 is type
        else if ((sortCode.charAt(0) == '3') && (sortCode.charAt(1) == 'A')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.type_a;
        } else if ((sortCode.charAt(0) == '3') && (sortCode.charAt(1) == 'D')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.type_d;
        }

        // 4 is published status
        else if ((sortCode.charAt(0) == '4') && (sortCode.charAt(1) == 'A')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.published_a;
        } else if ((sortCode.charAt(0) == '4') && (sortCode.charAt(1) == 'D')) {
            sort = SubmissionService.GetUserContextSubmissionsSort.published_d;
        }

        else {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        }
    }

    // default sort: status descending
    if (sortCode == null) {
        context.put("sort_column", '1');
        context.put("sort_direction", 'D');
        sort = SubmissionService.GetUserContextSubmissionsSort.status_d;
    }

    // collect information: submissions / assessments
    // TODO: get unpublished as well for test drive
    List<Submission> submissions = this.submissionService
            .getUserContextSubmissions(toolManager.getCurrentPlacement().getContext(), null, sort);

    context.put("submissions", submissions);

    // disable the tool navigation to this view
    context.put("disableDelivery", 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.etudes.mneme.tool.EnterView.java

/**
 * Send the user into the submission./*from   ww  w.jav a  2  s  . c  o m*/
 * 
 * @param req
 *        Servlet request.
 * @param res
 *        Servlet response.
 * @param submission
 *        The submission set for the user to the assessment so far.
 * @param returnDestination
 *        The final return destination path.
 * @throws IOException
 */
protected void enterSubmission(HttpServletRequest req, HttpServletResponse res, Submission submission,
        String returnDestination) throws IOException {
    Submission enterSubmission = null;
    try {
        enterSubmission = submissionService.enterSubmission(submission);
    } catch (AssessmentClosedException e) {
    } catch (AssessmentCompletedException e) {
    } catch (AssessmentPermissionException e) {
    }

    if (enterSubmission == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    redirectToQuestion(req, res, enterSubmission, false, true, returnDestination);
}

From source file:com.swdouglass.joid.server.OpenIdServlet.java

private void returnError(String query, HttpServletResponse response) throws ServletException, IOException {
    Map map = MessageFactory.parseQuery(query);
    String returnTo = (String) map.get("openid.return_to");
    boolean goodReturnTo = false;
    try {/* w  ww  .j  a v a  2 s  . com*/
        URL url = new URL(returnTo);
        goodReturnTo = true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    if (goodReturnTo) {
        String s = "?openid.ns:http://specs.openid.net/auth/2.0"
                + "&openid.mode=error&openid.error=BAD_REQUEST";
        s = response.encodeRedirectURL(returnTo + s);
        response.sendRedirect(s);
    } else {
        PrintWriter out = response.getWriter();
        // response.setContentLength() seems to be broken,
        // so set the header manually
        String s = "ns:http://specs.openid.net/auth/2.0\n" + "&mode:error" + "&error:BAD_REQUEST\n";
        int len = s.length();
        response.setHeader("Content-Length", Integer.toString(len));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(s);
        out.flush();
    }
}

From source file:org.egov.ptis.actions.search.GisSearchPropertyAction.java

@SkipValidation
public void gisFormRedirect() {
    LOGGER.debug("Entered into gisFormRedirect method : GISVERSION : " + GISVERSION + " GISCITY : " + GISCITY);
    final HttpServletResponse response = ServletActionContext.getResponse();
    try {/* ww  w. ja va2  s .c  o m*/
        response.sendRedirect(response.encodeRedirectURL(
                GISVERSION + GISCITY + "/ajaxtiledviewersample.jsp?DomainName=" + GISCITY + "&mode=PTIS"));
    } catch (final IOException e) {
        LOGGER.error("Exception in Gis Search Property : ", e);
        throw new ApplicationRuntimeException("Exception : " + e);
    }
    LOGGER.debug("Exit from gisFormRedirect method");
}

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

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

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

    // default is due date, ascending
    String sortCode = (params.length > 2) ? params[2] : "0A";
    if (sortCode.length() != 2) {
        throw new IllegalArgumentException();
    }

    AssessmentService.AssessmentsSort sort = figureSort(sortCode);
    context.put("sort_column", sortCode.charAt(0));
    context.put("sort_direction", sortCode.charAt(1));

    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 the assessments in this context
    List<Assessment> assessments = this.assessmentService
            .getContextAssessments(this.toolManager.getCurrentPlacement().getContext(), sort, Boolean.FALSE);
    context.put("assessments", assessments);

    // disable the tool navigation to this view
    context.put("disableAssessments", Boolean.TRUE);

    // pre-read question counts per pool
    this.questionService.preCountContextQuestions(toolManager.getCurrentPlacement().getContext());

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

From source file:com.egt.core.jsf.JSF.java

public static void redirect(String url, boolean encode) throws IOException {
    Bitacora.trace(JSF.class, "redirect", "url=" + url, "encode=" + encode);
    if (StringUtils.isBlank(url)) {
        return;/*from  w ww.j a va2 s .  c om*/
    }
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext == null) {
        return;
    }
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    url = StringUtils.trimToEmpty(url);
    url = encode ? response.encodeRedirectURL(url) : url;
    Bitacora.trace(url);
    try {
        response.sendRedirect(url);
        facesContext.responseComplete();
    } catch (Exception ex) {
        // TODO: manejar el java.lang.IllegalStateException?
        Bitacora.logTrace(ex);
    }
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.ReloadController.java

@RequestMapping(method = RequestMethod.GET)
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Entering 'execute' method");
    }// ww  w.  j av a  2  s  .  c o m

    StartupListener.setupContext(request.getSession().getServletContext());

    String referer = request.getHeader("Referer");

    if (referer != null) {
        log.info("reload complete, reloading user back to: " + referer);
        List<String> messages = (List) request.getSession().getAttribute(BaseFormController.MESSAGES_KEY);

        if (messages == null) {
            messages = new ArrayList();
        }

        messages.add("Reloading options completed successfully.");
        request.getSession().setAttribute(BaseFormController.MESSAGES_KEY, messages);

        response.sendRedirect(response.encodeRedirectURL(referer));
        return null;
    } else {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Context Reloaded</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<script type=\"text/javascript\">");
        out.println("alert('Context Reload Succeeded! Click OK to continue.');");
        out.println("history.back();");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
    }

    return null;
}

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

/**
 * {@inheritDoc}//from w ww .  j a  v  a  2s . com
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // pool id, sort, paging, all the rest is return parameters
    if (params.length < 6) {
        throw new IllegalArgumentException();
    }

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

    boolean fixMode = params[1].equals("pool_fix");

    // pool
    String pid = params[2];
    Pool pool = this.poolService.getPool(pid);
    if (pool == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // for the selected questions to delete
    Values values = this.uiService.newValues();
    context.put("questionids", values);

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

    try {
        this.poolService.savePool(pool);
    } catch (AssessmentPermissionException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    if ((!fixMode) && destination.equals("DELETE")) {
        for (String id : values.getValues()) {
            Question question = this.questionService.getQuestion(id);
            if (question != null) {
                try {
                    this.questionService.removeQuestion(question);
                } catch (AssessmentPermissionException e) {
                    // redirect to error
                    res.sendRedirect(
                            res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
                    return;
                }
            }
        }

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

    else if ((!fixMode) && destination.trim().startsWith("DUPLICATE:")) {
        String[] parts = StringUtil.split(destination, ":");
        if (parts.length != 2) {
            throw new IllegalArgumentException();
        }
        String qid = parts[1];
        try {
            Question question = this.questionService.getQuestion(qid);
            if (question != null) {
                // copy within the same pool
                this.questionService.copyQuestion(question, null);
            }

            // stay here
            destination = context.getDestination();
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }
    }

    else if ((!fixMode)
            && ((destination.trim().startsWith("/question_copy"))
                    || (destination.trim().startsWith("/question_move")))
            || (destination.trim().startsWith("/question_preview"))) {
        // add the selected ids to the destination
        StringBuilder buf = new StringBuilder();
        buf.append(destination);
        buf.append("/");
        for (String id : values.getValues()) {
            buf.append(id);
            buf.append("+");
        }
        buf.setLength(buf.length() - 1);

        // also add default sort parameter placeholder (for move and copy)
        if (!destination.trim().startsWith("/question_preview")) {
            buf.append("/-");
        }

        destination = buf.toString();
    }

    else if ((!fixMode) && "ADD".equals(destination)) {
        // create a question - type? TODO:
        String type = "mneme:MultipleChoice";
        // create the question of the appropriate type (all the way to save)
        Question newQuestion = null;
        try {
            newQuestion = this.questionService.newQuestion(pool, type);
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }

        String returnDest = StringUtil.unsplit(params, "/");

        // create URL for add questions /select_question_type/POOL/RETURN
        destination = "/question_edit/" + newQuestion.getId() + "/0/0" + returnDest;
    }

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

From source file:org.xwoot.xwootApp.web.filters.BaseFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) srequest;
    HttpServletResponse response = (HttpServletResponse) sresponse;

    LOG.debug(MessageFormat.format("Received request from {0}@{1} for {2}", request.getRemoteAddr(),
            request.getRemotePort(), request.getRequestURL()));

    XWootSite site = XWootSite.getInstance();
    XWootAPI xwoot = site.getXWootEngine();

    String requestedServletPath = request.getServletPath();
    String requestedContextPath = request.getContextPath();

    // While the XWoot site is not fully configured, ensure the proper flow.
    if (!site.isStarted()) {
        LOG.debug("Site is not started yet, starting the wizard.");
        if (!"/bootstrap.do".equals(requestedServletPath)) {
            response.sendRedirect(response.encodeRedirectURL(requestedContextPath + "/bootstrap.do"));
            return;
        }// ww  w .j a va  2s  .c  o  m
    } else if (!xwoot.isConnectedToP2PNetwork()) {
        LOG.debug("Site is not connected to a network yet, opening network bootstrap.");
        if (!"/bootstrapNetwork.do".equals(requestedServletPath)
                && !"/synchronize.do".equals(requestedServletPath)
                && "p2pnetworkconnection".equals(request.getParameter("action"))) {
            response.sendRedirect(response.encodeRedirectURL(requestedContextPath + "/bootstrapNetwork.do"));
            return;
        }
    } else if (!xwoot.getPeer().hasJoinedAGroup()/*isConnectedToP2PGroup()*/) {
        LOG.debug("Site has not joined a group yet, opening group bootstrap.");
        // We don't force redirect if we are already there or if we changed our mind and went back one step. 
        if (!"/bootstrapGroup.do".equals(requestedServletPath)
                && !"/bootstrapNetwork.do".equals(requestedServletPath)) {
            response.sendRedirect(response.encodeRedirectURL(requestedContextPath + "/bootstrapGroup.do"));
            return;
        }
    } else if (!xwoot.isStateComputed()) {
        LOG.debug("Site does not have a state yet, opening stateManagement.");
        if (!"/stateManagement.do".equals(requestedServletPath)
                && !"/bootstrapGroup.do".equals(requestedServletPath)) {
            response.sendRedirect(response.encodeRedirectURL(requestedContextPath + "/stateManagement.do"));
            return;
        }
    }

    // Add a header to inform about the presence of the xwoot service.
    response.addHeader("XWOOT_SERVICE", "xwoot service");

    // Let the request be further processed.
    chain.doFilter(request, response);

    LOG.debug("Base Filter applied");

}