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.jlibrary.web.servlet.JLibraryForwardServlet.java

private void updateDocumentRelations(HttpServletRequest req, HttpServletResponse resp) {
    String id;//from   w ww  .ja v a 2 s. com
    String repositoryName;
    String[] documents = req.getParameterValues("relations");
    try {
        id = getField(req, resp, "id");
        repositoryName = getField(req, resp, "repository");
    } catch (FieldNotFoundException e) {
        return;
    }
    try {
        Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
        RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile)
                .getRepositoryService();
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);
        Document doc = repositoryService.findDocument(ticket, id);
        DocumentProperties docProperties = doc.dumpProperties();
        Set<Document> nodeRelations = doc.getRelations();
        Iterator<Document> ite = nodeRelations.iterator();
        while (ite.hasNext()) {
            Relation relation = new Relation();
            relation.setBidirectional(true);
            relation.setDestinationNode(ite.next());
            docProperties.addProperty(DocumentProperties.DOCUMENT_DELETE_RELATION, relation);
        }
        if (documents != null) {
            for (int cont = 0; documents.length > cont; cont++) {
                Relation relation = new Relation();
                relation.setBidirectional(true);
                relation.setDestinationNode(repositoryService.findDocument(ticket, documents[cont]));
                docProperties.addProperty(DocumentProperties.DOCUMENT_ADD_RELATION, relation);
            }
        }
        repositoryService.updateDocument(ticket, docProperties);

        String url = getRepositoryURL(req, repositoryName) + doc.getPath();
        resp.sendRedirect(resp.encodeRedirectURL(url));
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem adding relations.");
    }
}

From source file:cz.fi.muni.xkremser.editor.server.ScanImgServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.addDateHeader("Last-Modified", new Date().getTime());
    resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
    resp.addDateHeader("Expires", DateUtils.addMonths(new Date(), 1).getTime());
    boolean full = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_FULL));
    String topSpace = req.getParameter(Constants.URL_PARAM_TOP_SPACE);
    String urlHeight = req.getParameter(Constants.URL_PARAM_HEIGHT);

    String uuid = req.getParameter(Constants.URL_PARAM_UUID);

    if (uuid == null || "".equals(uuid)) {
        uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_SCANS_PREFIX)
                + Constants.SERVLET_SCANS_PREFIX.length() + 1);
    }/*from   ww  w .j a  va  2 s  .  c  o  m*/

    StringBuffer baseUrl = new StringBuffer();
    baseUrl.append("http");
    if (req.getProtocol().toLowerCase().contains("https")) {
        baseUrl.append('s');
    }
    baseUrl.append("://");
    if (!URLS.LOCALHOST()) {
        baseUrl.append(req.getServerName());
    } else {
        String hostname = config.getHostname();
        if (hostname.contains("://")) {
            baseUrl.append(hostname.substring(hostname.indexOf("://") + "://".length()));
        } else {
            baseUrl.append(hostname);
        }
    }
    StringBuffer sb = new StringBuffer();
    if (topSpace != null) {
        String metadata = RESTHelper.convertStreamToString(
                RESTHelper.get(baseUrl + DJATOKA_URL_GET_METADATA + uuid, null, null, true));
        String height = null;
        height = metadata.substring(metadata.indexOf("ght\": \"") + 7, metadata.indexOf("\",\n\"dw"));
        String width = metadata.substring(metadata.indexOf("dth\": \"") + 7, metadata.indexOf("\",\n\"he"));

        int intHeight = Integer.parseInt(height);
        int intUrlHeight = Integer.parseInt(urlHeight);
        int intTopSpace = Integer.parseInt(topSpace);
        boolean isLower = intTopSpace > 0 && ((intHeight - intUrlHeight) < intTopSpace);
        String region = (isLower ? intHeight - intUrlHeight : (intTopSpace < 0 ? 0 : topSpace)) + ",1,"
                + urlHeight + "," + width;

        sb.append(baseUrl.toString()).append(DJATOKA_URL_FULL_PAGE_DETAIL).append(uuid)
                .append(DJATOKA_URL_REGION).append(region);

    } else {
        sb.append(baseUrl.toString())
                .append(full ? DJATOKA_URL_FULL_IMG : DJATOKA_URL + urlHeight + DJATOKA_URL_SUFFIX)
                .append(uuid);
    }
    resp.setContentType("image/jpeg");
    resp.sendRedirect(resp.encodeRedirectURL(sb.toString()));
}

From source file:org.apereo.portal.url.UrlCanonicalizingFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    if ("GET".equals(request.getMethod())) {
        final String canonicalUrl = this.urlSyntaxProvider.getCanonicalUrl(request);

        final String canonicalUri;
        final int queryStringIndex = canonicalUrl.indexOf("?");
        if (queryStringIndex < 0) {
            canonicalUri = canonicalUrl;
        } else {//  w  w w  . j av a 2  s  .c om
            canonicalUri = canonicalUrl.substring(0, queryStringIndex);
        }

        String requestURI = request.getRequestURI();
        // If cookies are disabled and Tomcat has appended the sessionId to the URL, remove the
        // jsessionid for the purposes of comparing the request URI to the canonical URI.  This
        // allows a search indexing engine such as Googlebot to access the guest view of a uportal
        // page which typically renders OK (not guaranteed depending upon content).  See UP-4414.
        if (requestURI.contains(";jsessionid")) {
            requestURI = requestURI.substring(0, requestURI.indexOf(";"));
        }

        final int redirectCount = this.getRedirectCount(request);
        if (!canonicalUri.equals(requestURI)) {
            if (redirectCount < this.maximumRedirects) {
                this.setRedirectCount(request, response, redirectCount + 1);

                /*
                 * This is the place where we should decide if...
                 *   - (1) the user is a guest
                 *   - (2) the canonicalUrl is not the requested content
                 *   - (3) there is a strategy for external login
                 *
                 * If all of these are true, we should attempt to send the 
                 * user to external login with a properly-encoded deep-linking 
                 * service URL attached.
                 */

                String encodedTargetUrl = null;

                IPerson person = personManager.getPerson(request);
                if (/* #1 */ person.isGuest() && /* #2 */ urlSyntaxProvider
                        .doesRequestPathReferToSpecificAndDifferentContentVsCanonicalPath(requestURI,
                                canonicalUri)
                        && /* #3 */ loginRefUrlEncoder != null) {
                    encodedTargetUrl = loginRefUrlEncoder.encodeLoginAndRefUrl(request);
                }

                if (encodedTargetUrl == null) {
                    // For whatever reason, we haven't chosen to send the 
                    // user through external login, so we use the canonicalUrl
                    encodedTargetUrl = response.encodeRedirectURL(canonicalUrl);
                }

                response.sendRedirect(encodedTargetUrl);
                logger.debug("Redirecting from {} to canonicalized URL {}, redirect {}", requestURI,
                        canonicalUri, redirectCount);
                return;
            }

            this.clearRedirectCount(request, response);
            logger.debug("Not redirecting from {} to canonicalized URL {} due to limit of {} redirects",
                    requestURI, canonicalUri, redirectCount);
        } else {
            logger.trace(
                    "Requested URI {} is the canonical URL {}, "
                            + "so no (further?) redirect is necessary (after {} redirects).",
                    requestURI, canonicalUri, redirectCount);
            if (redirectCount > 0) {
                this.clearRedirectCount(request, response);
            }
        }
    }

    final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(request);
    final UrlType urlType = portalRequestInfo.getUrlType();
    final UrlState urlState = portalRequestInfo.getUrlState();

    final PortalHttpServletResponseWrapper httpServletResponseWrapper = new PortalHttpServletResponseWrapper(
            response);
    final PortalHttpServletRequestWrapper httpServletRequestWrapper = new PortalHttpServletRequestWrapper(
            request, httpServletResponseWrapper, this.userInstanceManager);

    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_TYPE_HEADER, urlType.toString());
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_STATE_HEADER, urlState.toString());

    //Hack to make PortalController work in light of https://jira.springsource.org/secure/attachment/18283/SPR7346.patch
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_TYPE_HEADER + "." + urlType,
            Boolean.TRUE.toString());
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_STATE_HEADER + "." + urlState,
            Boolean.TRUE.toString());

    filterChain.doFilter(httpServletRequestWrapper, httpServletResponseWrapper);
}

From source file:de.zib.scalaris.examples.wikipedia.bliki.WikiServlet.java

/**
 * Shows a preview of the edit operation submitted or saves the page with
 * the given <tt>title</tt> depending on what button the user clicked.
 * //w w w.j  av a2 s  .c  om
 * @param request
 *            the request of the current operation
 * @param response
 *            the response of the current operation
 * @param title
 *            the title of the article to show
 * 
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 * @throws ServletException 
 */
private void showImage(final HttpServletRequest request, final HttpServletResponse response, final String image)
        throws UnsupportedEncodingException, IOException, ServletException {
    // we need to fix the image title first, e.g. a prefix with the desired size may exist
    final String imageNoSize = MATCH_WIKI_IMAGE_PX.matcher(image).replaceFirst("");
    String realImageUrl = getWikiImageUrl(imageNoSize);
    if (realImageUrl == null) {
        // bliki may have created ".svg.png" from an original ".svg" image:
        String new_image = MATCH_WIKI_IMAGE_SVG_PNG.matcher(imageNoSize).replaceFirst(".svg");
        realImageUrl = getWikiImageUrl(new_image);
        if (imageNoSize.equals(new_image) || realImageUrl == null) {
            realImageUrl = response.encodeRedirectURL("images/image.png");
        }
    }

    for (WikiEventHandler handler : eventHandlers) {
        handler.onImageRedirect(image, realImageUrl);
    }

    response.sendRedirect(realImageUrl);
}

From source file:org.apereo.portal.security.mvc.LoginController.java

/**
 * Process the incoming HttpServletRequest.  Note that this processing occurs after
 * PortalPreAuthenticatedProcessingFilter has run and performed pre-processing.
 * @param request//w  w  w.ja  v a2  s.  c  o m
 * @param response
 * @exception ServletException
 * @exception IOException
 */
@RequestMapping
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    // create the redirect URL, adding fname and args parameters if necessary
    String redirectTarget = null;

    final String refUrl = request.getParameter(REFERER_URL_PARAM);
    final URL redirectLocation = parseLocalRefUrl(request, refUrl);
    if (redirectLocation != null) {
        redirectTarget = redirectLocation.toString();
    }

    if (redirectTarget == null) {
        /* Grab the target functional name, if any, off the login request.
         * Also any arguments for the target. We will pass them  along after authentication.
         */
        String targetFname = request.getParameter("uP_fname");

        if (targetFname == null) {
            final IPortalUrlBuilder defaultUrl = this.portalUrlProvider.getDefaultUrl(request);
            redirectTarget = defaultUrl.getUrlString();
        } else {
            try {
                final IPortalUrlBuilder urlBuilder = this.portalUrlProvider
                        .getPortalUrlBuilderByPortletFName(request, targetFname, UrlType.RENDER);

                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String paramName = e.nextElement();
                    if (!paramName.equals("uP_fname")) {
                        urlBuilder.addParameter(paramName, request.getParameterValues(paramName));
                    }
                }

                redirectTarget = urlBuilder.getUrlString();
            } catch (IllegalArgumentException e) {
                final IPortalUrlBuilder defaultUrl = this.portalUrlProvider.getDefaultUrl(request);
                redirectTarget = defaultUrl.getUrlString();
            }
        }
    }

    IPerson person = null;

    final Object authError = request.getSession(false).getAttribute(LoginController.AUTH_ERROR_KEY);
    if (authError == null || !((Boolean) authError)) {
        person = this.personManager.getPerson(request);
    }

    if (person == null || !person.getSecurityContext().isAuthenticated()) {
        if (request.getMethod().equals("POST"))
            request.getSession(false).setAttribute(AUTH_ATTEMPTED_KEY, "true");
        // Preserve the attempted username so it can be redisplayed to the user
        String attemptedUserName = request.getParameter("userName");
        if (attemptedUserName != null)
            request.getSession(false).setAttribute(ATTEMPTED_USERNAME_KEY, request.getParameter("userName"));
    }

    final String encodedRedirectURL = response.encodeRedirectURL(redirectTarget);

    if (log.isDebugEnabled()) {
        log.debug("Redirecting to " + redirectTarget);
    }

    response.sendRedirect(encodedRedirectURL);
}

From source file:org.dspace.authenticate.ShibAuthentication.java

/**
 * Get login page to which to redirect. Returns URL (as string) to which to
 * redirect to obtain credentials (either password prompt or e.g. HTTPS port
 * for client cert.); null means no redirect.
 * /*from   w ww. jav  a  2  s .  co m*/
 * @param context
 *            DSpace context, will be modified (ePerson set) upon success.
 * 
 * @param request
 *            The HTTP request that started this operation, or null if not
 *            applicable.
 * 
 * @param response
 *            The HTTP response from the servlet method.
 * 
 * @return fully-qualified URL or null
 */
@Override
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) {
    // If this server is configured for lazy sessions then use this to
    // login, otherwise default to the protected shibboleth url.

    boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession",
            false);

    if (lazySession) {
        String shibURL = configurationService.getProperty("authentication-shibboleth.lazysession.loginurl");
        boolean forceHTTPS = configurationService
                .getBooleanProperty("authentication-shibboleth.lazysession.secure", true);

        // Shibboleth authentication initiator 
        if (shibURL == null || shibURL.length() == 0)
            shibURL = "/Shibboleth.sso/Login";
        shibURL = shibURL.trim();

        // Determine the return URL, where shib will send the user after authenticating. We need it to go back
        // to DSpace's shibboleth-login url so the we will extract the user's information and locally
        // authenticate them.
        String host = request.getServerName();
        int port = request.getServerPort();
        String contextPath = request.getContextPath();

        String returnURL;
        if (request.isSecure() || forceHTTPS)
            returnURL = "https://";
        else
            returnURL = "http://";

        returnURL += host;
        if (!(port == 443 || port == 80))
            returnURL += ":" + port;
        returnURL += "/" + contextPath + "/shibboleth-login";

        try {
            shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to generate lazysession authentication", uee);
        }

        log.debug("Redirecting user to Shibboleth initiator: " + shibURL);

        return response.encodeRedirectURL(shibURL);
    } else {
        // If we are not using lazy sessions rely on the protected URL.
        return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login");
    }
}

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * Serves up a site that can be used to examine and modify active sessions.
 * //from   w  w  w.j  a v a2s .  c o  m
 * @param req The HTTP request.
 * @param res The HTTP response.
 * @throws ServletException If the processing fails.
 * @throws IOException If the connection fails.
 */
public synchronized void examine(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    String cmd = req.getParameter("cmd");
    String process = req.getParameter("process");
    String session = req.getParameter("session");
    String variable = req.getParameter("variable");
    String action = req.getParameter("action");
    String value = req.getParameter("value");
    Deployment deployment = null;
    if (process != null)
        deployment = deploymentsByPath.get(process);
    DeploymentSession deploymentSession = null;
    if (session != null)
        deploymentSession = deployment.getActiveSession(session);
    IDataObject parent = null, object = null;
    String fieldName = null;
    if (variable != null) {
        for (String token : variable.split("\\.")) {
            if (object == null)
                object = deploymentSession.getVariableRegistry().getVariable(token);
            else {
                parent = object;
                object = parent.getField(token);
            }
            fieldName = token;
        }
    }
    if ("unlock".equals(cmd)) {
        if (action.startsWith("Save")) {
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            if (object == null) {
                object = variables.createVariable(parent.getField(fieldName).getType());
                parent.setField(fieldName, object);
            }
            if (object instanceof IBooleanObject)
                ((IBooleanObject) object).setValue(value);
            else if (object instanceof IDateObject)
                ((IDateObject) object).setValue(value);
            else if (object instanceof IDecimalObject)
                ((IDecimalObject) object).setValue(value);
            else if (object instanceof INumberObject)
                ((INumberObject) object).setValue(value);
            else if (object instanceof IStringObject)
                ((IStringObject) object).setValue(value);
        }
        deploymentSession.unlock();
        res.sendRedirect(
                res.encodeRedirectURL("examine?cmd=variables&process=" + process + "&session=" + session));
    } else {
        String base = res.encodeURL("examine?cmd=");
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><title>Runtime Examination</title></head><body>");
        if ("edit".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            deploymentSession.lock();
            out.println("<form action=\"examine\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\"cmd\" value=\"unlock\" />");
            out.println("<input type=\"hidden\" name=\"process\" value=\"" + process + "\" />");
            out.println("<input type=\"hidden\" name=\"session\" value=\"" + session + "\" />");
            out.println("<input type=\"hidden\" name=\"variable\" value=\"" + variable + "\" />");
            out.println("<p>" + variable + " = ");
            out.println("<input type=\"text\" name=\"value\" value=\"");
            if (object != null)
                out.println(object.toString());
            out.println("\" /></p>");
            out.println("<p><input type=\"submit\" name=\"action\" value=\"Save & Unlock\" />&nbsp;");
            out.println("<input type=\"submit\" name=\"action\" value=\"Cancel & Unlock\" /></p>");
            out.println("</form>");
        } else if ("variables".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            out.println("<p>Select a variable to edit:</p><ul>");
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            String prefix = base + "edit&process=" + process + "&session=" + session + "&variable=";
            String[] variableNames = variables.getVariableNames();
            Arrays.sort(variableNames);
            for (String name : variableNames)
                examineVariable(out, prefix, name, variables.getVariable(name));
            out.println("</ul>");
        } else if ("sessions".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Select the session to examine:</p><ul>");
            for (DeploymentSession s : deployment.getActiveSessions()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("variables&process=");
                out.print(process);
                out.print("&session=");
                out.print(s.getSessionID());
                out.print("\">");
                out.print(s.getSessionID());
                out.print(" : ");
                out.print(s.getCurrentPosition());
                out.println("</a></li>");
            }
            out.println("</ul>");
        } else {
            out.println("<p>Select the application to examine:</p><ul>");
            for (Object o : deploymentsByPath.keySet()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("sessions&process=");
                out.print(o.toString());
                out.print("\">");
                out.print(o.toString());
                out.println("</a></li>");
            }
            out.println("</ul>");
        }
        out.println("</body></html>");
    }
}

From source file:org.hdiv.filter.ValidatorFilter.java

/**
 * Called by the container each time a request/response pair is passed through the chain due to a client request for
 * a resource at the end of the chain./*from   w  w w  .  j  a va2  s. c  o  m*/
 * 
 * @param request
 *            request object
 * @param response
 *            response object
 * @param filterChain
 *            filter chain
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *      javax.servlet.FilterChain)
 */
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    this.initDependencies();

    ResponseWrapper responseWrapper = new ResponseWrapper(response);
    RequestWrapper requestWrapper = getRequestWrapper(request);

    HttpServletRequest multipartProcessedRequest = requestWrapper;

    try {

        boolean legal = false;
        boolean isMultipartException = false;

        if (this.isMultipartContent(request.getContentType())) {

            requestWrapper.setMultipart(true);

            try {

                if (this.multipartConfig == null) {
                    throw new RuntimeException(
                            "No 'multipartConfig' configured. It is required to multipart requests.");
                }

                multipartProcessedRequest = this.multipartConfig.handleMultipartRequest(requestWrapper,
                        super.getServletContext());

            } catch (HdivMultipartException e) {
                request.setAttribute(IMultipartConfig.FILEUPLOAD_EXCEPTION, e);
                isMultipartException = true;
                legal = true;
            }
        }

        ValidatorHelperResult result = null;
        if (!isMultipartException) {
            result = this.validationHelper.validate(multipartProcessedRequest);
            legal = result.isValid();
        }

        if (legal || this.hdivConfig.isDebugMode()) {
            processRequest(multipartProcessedRequest, responseWrapper, filterChain);
        } else {

            // Call to ValidatorErrorHandler
            this.errorHandler.handleValidatorError(multipartProcessedRequest, response, result.getErrorCode());
        }

    } catch (IOException e) {
        // Internal framework exception, rethrow exception
        throw e;
    } catch (ServletException e) {
        // Internal framework exception, rethrow exception
        throw e;
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Exception in request validation:");
            log.error("Message: " + e.getMessage());

            StringBuffer buffer = new StringBuffer();
            StackTraceElement[] trace = e.getStackTrace();
            for (int i = 0; i < trace.length; i++) {
                buffer.append("\tat " + trace[i] + System.getProperty("line.separator"));
            }
            log.error("StackTrace: " + buffer.toString());
            log.error("Cause: " + e.getCause());
            log.error("Exception: " + e.toString());
        }
        // Redirect to error page
        if (!this.hdivConfig.isDebugMode()) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + this.hdivConfig.getErrorPage()));
        }
    }
}

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

/**
 * Redirect to the appropriate question screen for this submission
 * /*from   w ww  .j  a v a  2 s  .  c om*/
 * @param req
 *        Servlet request.
 * @param res
 *        Servlet response.
 * @param submission
 *        The submission.
 * @param toc
 *        if true, send to TOC if possible (not possible for linear).
 * @param instructions
 *        if true, send to section instructions for first question.
 */
protected void redirectToQuestion(HttpServletRequest req, HttpServletResponse res, Submission submission,
        boolean toc, boolean instructions) throws IOException {
    String destination = null;
    Assessment assessment = submission.getAssessment();

    // if we are random access, and allowed, send to TOC
    if (toc && assessment.getRandomAccess()) {
        destination = "/toc/" + submission.getId();
    }

    else {
        // find the first incomplete question
        Question question = submission.getFirstIncompleteQuestion();

        // if we don't have one, we will go to the toc (or final_review for linear)
        if (question == null) {
            if (!assessment.getRandomAccess()) {
                destination = "/final_review/" + submission.getId();
            } else {
                destination = "/toc/" + submission.getId();
            }
        }

        else {
            // send to the section instructions if it's a first question and by-question
            // and we are showing part presentation and we have something authored for this part
            if (instructions && (question.getPartOrdering().getIsFirst())
                    && (assessment.getParts().getShowPresentation())
                    && (!question.getPart().getPresentation().getIsEmpty())
                    && (assessment.getQuestionGrouping() == QuestionGrouping.question)) {
                // to instructions
                destination = "/part_instructions/" + submission.getId() + "/" + question.getPart().getId();
            }

            // or to the question
            else {
                if (assessment.getQuestionGrouping() == QuestionGrouping.question) {
                    destination = "/question/" + submission.getId() + "/q" + question.getId();
                } else if (assessment.getQuestionGrouping() == QuestionGrouping.part) {
                    destination = "/question/" + submission.getId() + "/p" + question.getPart().getId();

                    // include the question target if not the first quesiton in the section
                    if (!question.getPartOrdering().getIsFirst()) {
                        destination = destination + "#" + question.getId();
                    }
                } else {
                    destination = "/question/" + submission.getId() + "/a";

                    // include the question target if not the first quesiton in the assessment
                    if (!question.getAssessmentOrdering().getIsFirst().booleanValue()) {
                        destination = destination + "#" + question.getId();
                    }
                }
            }
        }
    }

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

From source file:org.bonitasoft.forms.server.filter.BPMURLSupportFilter.java

@Override
@SuppressWarnings("unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {
    try {/*from w w w. j ava  2  s.  c om*/
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        final Map<String, String[]> parameters = new HashMap<String, String[]>(
                httpServletRequest.getParameterMap());
        final List<String> supportedParameterKeysList = Arrays.asList(FORM_LOCALE_URL_PARAM, TENANT_PARAM,
                UI_MODE_PARAM, THEME_PARAM, GWT_DEBUG_PARAM, TOKEN_URL_PARAM, AUTO_LOGIN_PARAM);
        final Set<String> parameterKeys = new HashSet<String>(parameters.keySet());
        parameterKeys.removeAll(supportedParameterKeysList);
        if (!parameterKeys.isEmpty()) {
            if (parameterKeys.contains(PROCESS_NAME_PARAM)) {
                final long processDefinitionID = getProcessIDOfLatestVersion(parameters.get(PROCESS_NAME_PARAM),
                        httpServletRequest);
                if (processDefinitionID != -1) {
                    final String[] parameterValues = new String[1];
                    parameterValues[0] = String.valueOf(processDefinitionID);
                    parameters.put(PROCESS_PARAM, parameterValues);
                }
                parameters.remove(PROCESS_NAME_PARAM);
            }
            if (!parameterKeys.contains(FORM_ID_PARAM) && isForm(httpServletRequest)) {
                final String formID[] = getFormIDFromRegularURLParameters(parameters, httpServletRequest);
                if (formID != null && formID.length > 0) {
                    parameters.put(FORM_ID_PARAM, formID);
                }
            }
            final StringBuilder hashString = new StringBuilder();
            final StringBuilder queryString = new StringBuilder();
            for (final Entry<String, String[]> parameter : parameters.entrySet()) {
                final String key = parameter.getKey();
                final String[] values = parameter.getValue();
                if (supportedParameterKeysList.contains(key)) {
                    buildQueryString(queryString, key, values);
                } else {
                    buildQueryString(hashString, key, values);
                }
            }
            final StringBuilder redirectionURL = new StringBuilder();
            redirectionURL.append(httpServletRequest.getRequestURI());
            if (queryString.length() > 0) {
                redirectionURL.append("?");
                redirectionURL.append(queryString);
            }
            if (hashString.length() > 0) {
                redirectionURL.append("#");
                redirectionURL.append(hashString);
            }
            final String encodeRedirectURL = httpServletResponse.encodeRedirectURL(redirectionURL.toString());
            httpServletResponse.sendRedirect(encodeRedirectURL);
        } else {
            response.setContentType(CharEncoding.UTF_8);
            filterChain.doFilter(request, response);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Error while parsing the regular parameters into hash parameters.");
        throw new ServletException(e);
    }
}