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.ImportQtiView.java

/**
 * {@inheritDoc}//from w  w w.j  a v  a2 s.  c om
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {

    String returnUrl = (params.length > 3) ? params[2] : "";
    String sort = (params.length > 3) ? params[3] : "0A";

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

    // an XML uploader for the QTI file
    UploadXml upload = new UploadXml();
    context.put("upload", upload);

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

    // import the pools
    if ("IMPORT".equals(destination)) {
        // the DOM is in the upload
        Document doc = upload.getUpload();

        try {
            String unzipBackUpLocation = upload.getUnzipLocation();
            if ("".equals(unzipBackUpLocation)) {
                this.importQtiService.importPool(doc, toolManager.getCurrentPlacement().getContext());
            } else {
                //QTI 1 zip file 
                boolean doneQTI1 = false;
                doneQTI1 = this.importQtiService.importPool(doc, toolManager.getCurrentPlacement().getContext(),
                        unzipBackUpLocation);
                // QTI 2 zip file
                if (!doneQTI1)
                    this.importQti2Service.importPool(doc, toolManager.getCurrentPlacement().getContext(),
                            unzipBackUpLocation);
                upload.deleteFiles(new File(unzipBackUpLocation));
            }
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }
        destination = "/" + returnUrl + "/" + sort;
    }
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));

}

From source file:edu.hawaii.its.hudson.security.Cas1SecurityRealm.java

@Override
public Filter createFilter(FilterConfig filterConfig) {
    AuthenticationFilter authenticationFilter = new AuthenticationFilter();
    authenticationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml
    authenticationFilter.setRenew(forceRenewal);
    authenticationFilter.setGateway(false);
    authenticationFilter.setCasServerLoginUrl(casServerUrl + "/login");
    authenticationFilter.setServerName(hudsonHostName);

    Cas10TicketValidationFilter validationFilter = new Cas10TicketValidationFilter();
    validationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml
    validationFilter.setRedirectAfterValidation(true);
    validationFilter.setServerName(hudsonHostName);
    validationFilter.setTicketValidator(new AbstractCasProtocolUrlBasedTicketValidator(casServerUrl) {

        protected String getUrlSuffix() {
            return "validate"; // version 1 protocol
        }/*w w w.j a va  2s  .c  o  m*/

        protected Assertion parseResponseFromServer(final String response) throws TicketValidationException {
            if (!response.startsWith("yes")) {
                throw new TicketValidationException("CAS could not validate ticket.");
            }

            try {
                final BufferedReader reader = new BufferedReader(new StringReader(response));
                String mustBeYes = reader.readLine();
                assert mustBeYes.equals("yes") : mustBeYes;
                String username = reader.readLine();

                // parse optional extra validation attributes
                Collection roles = parseRolesFromValidationResponse(getParsedScript(), response);

                Map<String, Object> attributes = new HashMap<String, Object>();
                attributes.put(AUTH_KEY, new Cas1Authentication(username, roles)); // Acegi Authentication
                // CAS saves this Assertion in the session; we'll use the Authentication it's carrying.
                return new AssertionImpl(new AttributePrincipalImpl(username), attributes);
            } catch (final IOException e) {
                throw new TicketValidationException("Unable to parse CAS response.", e);
            }
        }
    });

    Filter casToAcegiContext = new OnlyDoFilter() {
        /**
         * Gets the authentication out of the session and puts it in Acegi's ThreadLocal on every request.
         * If we've made it this far down this FilterChain without a redirect,
         * then there must be a session with an authentication in it.
         * Using an Acegi filter to do this would require implementing more of the Acegi framework.
         */
        public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
                final FilterChain filterChain) throws IOException, ServletException {
            final HttpServletRequest request = (HttpServletRequest) servletRequest;
            final HttpSession session = request.getSession(false);
            final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

            try {
                Cas1Authentication auth = (Cas1Authentication) assertion.getAttributes().get(AUTH_KEY);
                SecurityContextHolder.getContext().setAuthentication(auth);
                filterChain.doFilter(servletRequest, servletResponse);
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }
    };

    Filter jettyJsessionidRedirect = new OnlyDoFilter() {
        private final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();

        /**
         * Redirects to remove a jsessionid that a servlet container leaves in the URI if it's also in a cookie.
         * Jetty's getRequestURI() fails to remove the jsessionid (whether or not it's also in a cookie),
         * and this messes up Hudson's Stapler (as of version 1.323, at least).  CAS tickles this bug because
         * Jetty's encodeRedirectURL() is adding jsessionid on redirect after validation,
         * if it wasn't in a cookie on the request.  However, apparently Jetty also puts it in a cookie
         * on the redirect response, and Firefox accepts it.  This is a work-around to redirect that jsessionid
         * off the URL, since the cookie is enough, and the whole point of CAS redirect after validation is
         * to get a clean URL anyway (for bookmarks or restored browser tabs).
         * Other servlet containers and browser combinations may behave differently.
         * <p/>
         * This work-around does not attempt to make Hudson work in Jetty without cookies.
         * A potential approach for that would be for this filter to install an HttpServletRequestWrapper
         * that cleans jsessionid out of getRequestURI().  However, Hudson would also need to rewrite
         * all its URLs with the jsessionid, and I have no idea whether it does that.  That is an issue
         * between Hudson and Jetty, and we can just use cookies anyway.
         */
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                if (httpRequest.getRequestURI().contains(";jsessionid=")
                        && httpRequest.isRequestedSessionIdFromCookie()) {
                    // without (i.e., with relative) protocol, host, and port
                    String decodedCleanedUrl = URL_PATH_HELPER.getRequestUri(httpRequest);
                    if (StringUtils.isNotBlank(httpRequest.getQueryString())) {
                        decodedCleanedUrl += "?" + URL_PATH_HELPER.decodeRequestString(httpRequest,
                                httpRequest.getQueryString());
                    }
                    HttpServletResponse httpResponse = (HttpServletResponse) response;
                    httpResponse.sendRedirect(httpResponse.encodeRedirectURL(decodedCleanedUrl));
                    return;
                }
            }
            filterChain.doFilter(request, response);
        }
    };

    // todo: Exclude paths in Hudson#getTarget() from CAS filtering/Authorization?
    // todo: Add SecurityFilters.commonProviders?
    // todo: Or, is all that just to support on-demand authentication (upgrade)?

    return new ChainedServletFilter(authenticationFilter, validationFilter, casToAcegiContext,
            jettyJsessionidRedirect);
}

From source file:org.xwoot.xwootApp.web.servlets.Bootstrap.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.getServletContext().log("Bootstrap opened.");

    try {//from w  w w .j a v  a  2 s  . co m
        if (XWootSite.getInstance().isStarted()) {
            this.getServletContext().log("Site: " + XWootSite.getInstance().getXWootEngine().getXWootPeerId()
                    + " Bootstrap - instance already started");
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/synchronize.do"));
            return;
        }

        String errors = "";
        String xwikiPropertiesFile = request.getSession().getServletContext()
                .getRealPath(XWootSite.XWIKI_PROPERTIES_FILENAME);
        String xwootPropertiesFile = request.getSession().getServletContext()
                .getRealPath(XWootSite.XWOOT_PROPERTIES_FILENAME);
        //TODO better properties management 
        String contentManagerPropertiesFile = request.getSession().getServletContext()
                .getRealPath(XWootSite.CONTENT_MANAGER_PROPERTIES_FILENAME);

        // If filled the bootstrap form, process the values and move on if all ok.
        if (request.getParameter("update") != null) {
            this.getServletContext().log("Processing data.");

            errors = XWootSite.getInstance().updatePropertiesFiles(request, xwikiPropertiesFile,
                    xwootPropertiesFile);

            // Start the XWoot server if the properties were correctly
            // saved.
            if (StringUtils.isBlank(errors)) {
                this.getServletContext().log("No errors found.");

                Properties p_xwiki = XWootSite.getProperties(xwikiPropertiesFile);
                Properties p_xwoot = XWootSite.getProperties(xwootPropertiesFile);

                this.getServletContext().log("Bootstrap - starting instance -");
                XWootSite.getInstance().init((String) p_xwoot.get(XWootSite.XWOOT_SERVER_NAME),
                        (String) p_xwoot.get(XWootSite.XWOOT_WORKING_DIR),
                        (String) p_xwiki.get(XWootSite.XWIKI_ENDPOINT),
                        (String) p_xwiki.get(XWootSite.XWIKI_USERNAME),
                        (String) p_xwiki.get(XWootSite.XWIKI_PASSWORD), contentManagerPropertiesFile);

                this.getServletContext()
                        .log("Site :" + XWootSite.getInstance().getXWootEngine().getXWootPeerId()
                                + " Bootstrap - moving on to network bootstrap -");
                response.sendRedirect(
                        response.encodeRedirectURL(request.getContextPath() + "/bootstrapNetwork.do"));
                return;
            } else {
                this.getServletContext().log("Errors found.");
            }

            // There are errors, display the bootstrap page again.
            errors = errors.replaceAll("\n", "<br/>");
            request.setAttribute("errors", errors);
        } else {
            this.getServletContext().log("Bootstrap page just opened.");
        }

        // If just opened the bootstrap form or an error occurred, init the form fields with default data found in the properties files.
        if (!StringUtils.isBlank(xwikiPropertiesFile) && !StringUtils.isBlank(xwootPropertiesFile)) {
            Properties p_xwiki = XWootSite.getProperties(xwikiPropertiesFile);
            Properties p_xwoot = XWootSite.getProperties(xwootPropertiesFile);

            request.setAttribute("xwiki_properties", p_xwiki);
            request.setAttribute("xwoot_properties", p_xwoot);
        }

        request.getRequestDispatcher("/pages/Bootstrap.jsp").forward(request, response);
        return;
    } catch (Exception e) {
        this.getServletContext().log("Bootstrap failed:\n", e);
        request.setAttribute("error", e.getMessage());
        request.getRequestDispatcher("/pages/Bootstrap.jsp").forward(request, response);
        return;
    }
}

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

/**
 * {@inheritDoc}/*from  w ww  .  ja  v a 2s  .co m*/
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] pools sort
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String poolsSort = params[2];

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

    // for the text
    Value textValue = this.uiService.newValue();
    context.put("text", textValue);

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

    // the text
    String text = textValue.getValue();

    // import the pools
    if ("IMPORT".equals(destination)) {
        try {
            this.importTextService.importQuestions(toolManager.getCurrentPlacement().getContext(), null, text);
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }

        destination = "/pools/" + poolsSort;
    }

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

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

/**
 * {@inheritDoc}/* www  . ja v a 2s .  c  om*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] pools sort
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String poolsSort = params[2];
    context.put("poolsSort", poolsSort);

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

    // the list of site for this user with Assignment access
    List<Ent> sites = this.importService.getAssignmentSites(null);
    context.put("sites", sites);

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

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

/**
 * {@inheritDoc}//from   www  .j ava  2  s. co  m
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] pools sort
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String poolsSort = params[2];

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

    // for the text
    Value textValue = this.uiService.newValue();
    context.put("text", textValue);

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

    // the text
    String text = textValue.getValue();

    // import the pools
    if ("IMPORT".equals(destination)) {
        try {
            this.importeCollegeTextService.importQuestions(toolManager.getCurrentPlacement().getContext(), null,
                    text);
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }

        destination = "/pools/" + poolsSort;
    }

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

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

/**
 * {@inheritDoc}/*from ww w  .j  a v  a 2s .  co m*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] pools sort
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String poolsSort = params[2];
    context.put("poolsSort", poolsSort);

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

    // the list of site for this user with Samigo access
    List<Ent> sites = this.importService.getSamigoSites(null);
    context.put("sites", sites);

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

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

/**
 * {@inheritDoc}/*from   ww  w.j  a  v a 2s.co  m*/
 */
@SuppressWarnings("unchecked")
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // check for user permission to access the assessments for grading
    if (!this.submissionService.allowEvaluate(toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    ToolSession toolSession = m_sessionManager.getCurrentToolSession();
    List<GradeImportSet> importSets = (List<GradeImportSet>) toolSession.getAttribute(GradeImportSet.ATTR_NAME);
    if (importSets == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // return destination - or the main assessments view if not specified
    String destination = null;
    if (params.length > 2) {
        int len = params.length - 2;
        destination = "/" + StringUtil.unsplit(params, 2, len, "/");
    } else {
        destination = "/assessments";
    }
    context.put("return", destination);

    context.put("targets", importSets);

    uiService.render(ui, context);
}

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

/**
 * {@inheritDoc}/*from ww w .  j av a 2  s. c  o  m*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2] pools sort
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }
    String poolsSort = params[2];
    context.put("poolsSort", poolsSort);

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

    // the list of importable pools for this user
    List<Ent> pools = this.importService.getSamigoPools(null);
    context.put("pools", pools);

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

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

/**
 * {@inheritDoc}/*from  ww  w  .j  a  v  a2 s .c o  m*/
 */
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.submissionService.allowEvaluate(toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

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

    // collect the assessments in this context
    List<Assessment> assessments = this.assessmentService
            .getContextAssessments(this.toolManager.getCurrentPlacement().getContext(), sort, Boolean.TRUE);
    context.put("assessments", assessments);

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

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