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.jasig.portal.security.mvc.LoginController.java

/**
 * Process the incoming HttpServletRequest
 * @param request/*from   w  w  w  .j  ava  2s  .com*/
 * @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);
    if (refUrl != null) {
        if (refUrl.startsWith("/")) {
            redirectTarget = refUrl;
        } else {
            log.warn("Refernce URL passed in does not start with a / and will be ignored: " + refUrl);
        }
    }

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

                @SuppressWarnings("unchecked")
                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 by CLogin
        String attemptedUserName = request.getParameter("userName");
        if (attemptedUserName != null)
            request.getSession(false).setAttribute(ATTEMPTED_USERNAME_KEY, request.getParameter("userName"));
    }

    final String encodedRedirectURL = response.encodeRedirectURL(redirectTarget);
    response.sendRedirect(encodedRedirectURL);

}

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

/**
 * Redirect to the appropriate question screen for this submission
 * //from  www .j  a  v  a2 s.c  o  m
 * @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 part 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 part instructions if it's a first question and by-question
            if (instructions && (question.getPartOrdering().getIsFirst())
                    && (assessment.getParts().getShowPresentation())
                    && (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 question in the part
                    if (!question.getPartOrdering().getIsFirst()) {
                        destination = destination + "/" + question.getId();
                    }
                } else {
                    destination = "/question/" + submission.getId() + "/a";

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

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

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

/**
 * DOCUMENT ME!/*from  w  w  w  . j ava 2s . c om*/
 * 
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 */
@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    System.out.print(
            "Site " + XWootSite.getInstance().getXWootEngine().getXWootPeerId() + " : Synchronize page -");

    XWootAPI xwootEngine = XWootSite.getInstance().getXWootEngine();

    // synchronize
    if ("synchronize".equals(request.getParameter("action"))
            && XWootSite.getInstance().getXWootEngine().isContentManagerConnected()) {
        this.log("Synchronization requested.");
        try {
            XWootSite.getInstance().getXWootEngine().synchronize();
        } catch (Exception e) {
            this.log("Error while synchronizing.\n", e);

            // FIXME: bring back the "errors" mechanism for this page as well instead of throwing servlet exceptions.
            throw new ServletException(e);
        }
    }

    // anti entropy
    else if ("antiEntropy".equals(request.getParameter("action"))
            && XWootSite.getInstance().getXWootEngine().isConnectedToP2PNetwork()) {
        String neighbor = request.getParameter("neighbor");
        try {
            XWootSite.getInstance().getXWootEngine().doAntiEntropy(neighbor);
        } catch (Exception e) {
            this.log("Problems while doing anti-entropy with " + neighbor, e);

            //FIXME: bring back the "errors" mechanism for this page as well instead of throwing servlet exceptions.
            throw new ServletException(e);
        }
    }

    // p2p connection
    else if ("p2pnetworkconnection".equals(request.getParameter("action"))) {
        this.log("P2P connection gestion ...");
        try {
            //                String mode = request.getParameter("switch");
            //                if ("on".equals(mode)
            //                    && !XWootSite.getInstance().getXWootEngine().isConnectedToP2PNetwork()) {
            //                    XWootSite.getInstance().getXWootEngine().reconnectToP2PNetwork();
            //                } else if ("off".equals(mode)
            //                    && XWootSite.getInstance().getXWootEngine().isConnectedToP2PNetwork()) {
            //                    XWootSite.getInstance().getXWootEngine().disconnectFromP2PNetwork();
            //                } else {
            if (xwootEngine.isConnectedToP2PNetwork()) {
                xwootEngine.disconnectFromP2PNetwork();

                // Stop auto-synchronization. We don't need redundant patches.
                XWootSite.getInstance().getAutoSynchronizationThread().stopThread();
            } else {
                if (xwootEngine.getPeer().isJxtaStarted()) {
                    // Network was trying to reconnect.
                    xwootEngine.disconnectFromP2PNetwork();
                } else {
                    xwootEngine.reconnectToP2PNetwork();
                    response.sendRedirect(
                            response.encodeRedirectURL(request.getContextPath() + "/bootstrapGroup.do"));

                    //                        // Redirect to network bootstrap which will automatically rejoin the existing network configuration.
                    //                        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/bootstrapNetwork.do"));
                    return;
                }
            }
            //                }
        } catch (Exception e) {
            // Disconnecting/Reconnecting failed, do nothing, make the user try again.
            //  We should show an error or something.
            //throw new ServletException(e);
        }
    }

    // cp connection
    else if ("cpconnection".equals(request.getParameter("action"))) {
        this.log("Content Provider connection gestion ...");
        try {
            if (XWootSite.getInstance().getXWootEngine().isConnectedToP2PGroup()) {
                XWootSite.getInstance().getXWootEngine().doAntiEntropyWithAllNeighbors();
            }
            String mode = request.getParameter("switch");
            if (StringUtils.equals(mode, "on")
                    && !XWootSite.getInstance().getXWootEngine().isContentManagerConnected()) {
                XWootSite.getInstance().getXWootEngine().connectToContentManager();
            } else if (StringUtils.equals(mode, "off")
                    && XWootSite.getInstance().getXWootEngine().isContentManagerConnected()) {
                XWootSite.getInstance().getXWootEngine().disconnectFromContentManager();
            } else {
                if (XWootSite.getInstance().getXWootEngine().isContentManagerConnected()) {
                    XWootSite.getInstance().getXWootEngine().disconnectFromContentManager();
                } else {
                    XWootSite.getInstance().getXWootEngine().connectToContentManager();
                }
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    else {
        this.log(" no action ! -");
    }

    // view neighbors list
    Collection<PipeAdvertisement> neighbors = null;
    try {
        neighbors = xwootEngine.getNeighborsList();
    } catch (Exception e) {
        // remove this with new xwootAPI adapted to XWoot3.
    }

    if (neighbors != null) {
        HashMap<PipeAdvertisement, Boolean> result = new HashMap<PipeAdvertisement, Boolean>();
        for (PipeAdvertisement n : neighbors) {

            // send to the UI a lighter, copy version having a human-readable name.
            PipeAdvertisement original = n;
            n = (PipeAdvertisement) AdvertisementFactory
                    .newAdvertisement(PipeAdvertisement.getAdvertisementType());
            n.setPipeID(original.getPipeID());
            n.setName(JxtaPeer.getPeerNameFromBackChannelPipeName(original.getName()));
            n.setType(original.getType());

            if (!XWootSite.getInstance().getXWootEngine().isConnectedToP2PNetwork()) {
                this.log(n + " Site " + n + " is not connected because we are disconnected.");
                result.put(n, Boolean.FALSE);
            } else {
                //TODO: implement a ping mechanism.
                /*URL to = new URL(n + "/synchronize.do?test=true");
                try {
                HttpURLConnection init = (HttpURLConnection) to.openConnection();
                result.put(n, Boolean.valueOf(init.getResponseMessage().contains("OK")));
                init.disconnect();
                } catch (Exception e) {
                System.out.println(n + " Neighbor " + n + " is not connected");
                result.put(n, Boolean.FALSE);
                }*/
                result.put(n, Boolean.TRUE);
            }
        }
        request.setAttribute("noneighbor", Boolean.valueOf(neighbors.size() == 0));
        request.setAttribute("neighbors", result);
    } else {
        request.setAttribute("noneighbor", true);
    }

    int groupConnection = -1;
    if (xwootEngine.isConnectedToP2PNetwork()) {
        RendezVousService rdvStatus = xwootEngine.getPeer().getCurrentJoinedPeerGroup().getRendezVousService();
        boolean isGroupRDV = rdvStatus.isRendezVous();
        // Check number of connected clients or connected rdvs
        boolean isConnectedToPeers = rdvStatus.getConnectedPeerIDs().size() > 0;
        // Check number of known rdvs in the network (If RDV peer).
        isConnectedToPeers |= rdvStatus.getLocalWalkView().size() > 0;

        if (isConnectedToPeers) {
            groupConnection = 1;
        } else if (isGroupRDV) {
            groupConnection = 0;
        }
    } else {
        // -1 by default, when network is down.
    }

    int networkConnection = -1;
    if (xwootEngine.isConnectedToP2PNetwork()) {
        RendezVousService rdvStatus = xwootEngine.getPeer().getDefaultGroup().getRendezVousService();
        boolean isGroupRDV = rdvStatus.isRendezVous();
        // Check number of connected clients or connected rdvs
        boolean isConnectedToPeers = rdvStatus.getConnectedPeerIDs().size() > 0;
        // Check number of known rdvs in the network (If RDV peer).
        isConnectedToPeers |= rdvStatus.getLocalWalkView().size() > 0;

        if (isConnectedToPeers) {
            networkConnection = 1;
        } else if (isGroupRDV) {
            networkConnection = 0;
        }
    } else {
        // -1 by default, when network is down.
    }

    //Boolean reconnectingToNetwork = xwootEngine.getPeer().isJxtaStarted() && !xwootEngine.isConnectedToP2PNetwork();
    //Boolean connectedToNetwork = xwootEngine.isConnectedToP2PNetwork() || reconnectingToNetwork;

    request.setAttribute("content_provider", XWootSite.getInstance().getXWootEngine().getContentProvider());
    request.setAttribute("xwiki_url", XWootSite.getInstance().getXWootEngine().getContentManagerURL());
    request.setAttribute("p2pconnection", xwootEngine.getPeer().isJxtaStarted());
    request.setAttribute("groupConnection", groupConnection);
    request.setAttribute("networkConnection", networkConnection);
    request.setAttribute("cpconnection",
            Boolean.valueOf(XWootSite.getInstance().getXWootEngine().isContentManagerConnected()));
    request.getRequestDispatcher("/pages/Synchronize.jsp").forward(request, response);

    return;
}

From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java

/**
 * Create/update community metadata from a posted form
 * //from  ww  w  . j  a  v a 2  s.c  o  m
 * @param context
 *            DSpace context
 * @param request
 *            the HTTP request containing posted info
 * @param response
 *            the HTTP response
 * @param community
 *            the community to update (or null for creation)
 */
private void processConfirmEditCommunity(Context context, HttpServletRequest request,
        HttpServletResponse response, Community community)
        throws ServletException, IOException, SQLException, AuthorizeException {
    if (request.getParameter("create").equals("true")) {
        // if there is a parent community id specified, create community
        // as its child; otherwise, create it as a top-level community
        int parentCommunityID = UIUtil.getIntParameter(request, "parent_community_id");

        if (parentCommunityID != -1) {
            Community parent = Community.find(context, parentCommunityID);

            if (parent != null) {
                community = parent.createSubcommunity();
            }
        } else {
            community = Community.create(null, context);
        }

        // Set attribute
        request.setAttribute("community", community);
    }

    storeAuthorizeAttributeCommunityEdit(context, request, community);

    community.setMetadata("name", request.getParameter("name"));
    community.setMetadata("short_description", request.getParameter("short_description"));

    String intro = request.getParameter("introductory_text");

    if (intro.equals("")) {
        intro = null;
    }

    String copy = request.getParameter("copyright_text");

    if (copy.equals("")) {
        copy = null;
    }

    String side = request.getParameter("side_bar_text");

    if (side.equals("")) {
        side = null;
    }

    community.setMetadata("introductory_text", intro);
    community.setMetadata("copyright_text", copy);
    community.setMetadata("side_bar_text", side);
    community.update();

    // Which button was pressed?
    String button = UIUtil.getSubmitButton(request, "submit");

    if (button.equals("submit_set_logo")) {
        // Change the logo - delete any that might be there first
        community.setLogo(null);
        community.update();

        // Display "upload logo" page. Necessary attributes already set by
        // doDSPost()
        JSPManager.showJSP(request, response, "/dspace-admin/upload-logo.jsp");
    } else if (button.equals("submit_delete_logo")) {
        // Simply delete logo
        community.setLogo(null);
        community.update();

        // Show edit page again - attributes set in doDSPost()
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");
    } else if (button.equals("submit_authorization_edit")) {
        // Forward to policy edit page
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath()
                + "/tools/authorize?community_id=" + community.getID() + "&submit_community_select=1"));
    } else if (button.equals("submit_admins_create")) {
        // Create new group
        Group newGroup = community.createAdministrators();
        community.update();

        // Forward to group edit page
        response.sendRedirect(response.encodeRedirectURL(
                request.getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID()));
    } else if (button.equals("submit_admins_remove")) {
        Group g = community.getAdministrators();
        community.removeAdministrators();
        community.update();
        g.delete();
        // Show edit page again - attributes set in doDSPost()
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");
    } else if (button.equals("submit_admins_edit")) {
        // Edit 'community administrators' group
        Group g = community.getAdministrators();
        response.sendRedirect(response
                .encodeRedirectURL(request.getContextPath() + "/tools/group-edit?group_id=" + g.getID()));
    } else {
        // Button at bottom clicked - show main control page
        showControls(context, request, response);
    }

    // Commit changes to DB
    context.complete();
}

From source file:fll.web.report.finalist.StoreFinalistSchedule.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {/*from   www .j a va2  s .  c  o  m*/
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final int tournament = Queries.getCurrentTournament(connection);

        // get parameters
        final String schedDataStr = request.getParameter("sched_data");
        if (null == schedDataStr || "".equals(schedDataStr)) {
            throw new FLLRuntimeException("Parameter 'sched_data' cannot be null");
        }

        final String categoryDataStr = request.getParameter("category_data");
        if (null == categoryDataStr || "".equals(categoryDataStr)) {
            throw new FLLRuntimeException("Parameter 'category_data' cannot be null");
        }

        final String division = request.getParameter("division_data");
        if (null == division || "".equals(division)) {
            throw new FLLRuntimeException("Parameter 'division_data' cannot be null");
        }

        final String nomineesStr = request.getParameter("non-numeric-nominees_data");
        if (null == nomineesStr || "".equals(nomineesStr)) {
            throw new FLLRuntimeException("Parameter 'non-numeric-nominees_data' cannot be null");
        }

        // decode JSON
        final ObjectMapper jsonMapper = new ObjectMapper();

        final Collection<FinalistDBRow> rows = jsonMapper.readValue(schedDataStr,
                FinalistScheduleTypeInformation.INSTANCE);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Sched Data has " + rows.size() + " rows");
            for (final FinalistDBRow row : rows) {
                LOGGER.trace("row category: " + row.getCategoryName() + " time: " + row.getTime() + " team: "
                        + row.getTeamNumber());
            }
        }

        final Collection<FinalistCategory> categories = jsonMapper.readValue(categoryDataStr,
                FinalistCategoriesTypeInformation.INSTANCE);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Category Data has " + rows.size() + " rows");
        }

        final FinalistSchedule schedule = new FinalistSchedule(tournament, division, categories, rows);
        schedule.store(connection);

        final Collection<NonNumericNominees> nominees = jsonMapper.readValue(nomineesStr,
                NonNumericNomineesTypeInformation.INSTANCE);
        for (final NonNumericNominees nominee : nominees) {
            nominee.store(connection, tournament);
        }

        message.append("<p id='success'>Finalist schedule saved to the database</p>");

    } catch (final SQLException e) {
        message.append("<p class='error'>Error saving finalist schedule into the database: " + e.getMessage()
                + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("schedule-saved.jsp"));

}

From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.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.j av  a  2s .c o  m

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // Determine request by attributes
    String action = (String) request.getParameter("action");
    String type = (String) request.getParameter("type");

    System.out.println("(*) UploadServlet ...action " + action);
    if (action == null) {
        action = "upload_data";
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    //fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                //String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

            } else {
                //Handle Uploaded files.
                System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());

                String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

                request.getSession().setAttribute("action", action);

                if (action.compareTo("upload_data") == 0) {
                    request.getSession().setAttribute("codes", s);
                } else {
                    Mapping mapping = new Mapping().toMapping(s);

                    System.out.println("Mapping " + mapping.getMappingName() + " uploaded.");
                    System.out.println("Mapping version: " + mapping.getMappingVersion());

                    MappingObject obj = mapping.toMappingObject();
                    HashMap mappings = (HashMap) request.getSession().getAttribute("mappings");
                    if (mappings == null) {
                        mappings = new HashMap();
                    }
                    mappings.put(obj.getKey(), obj);
                    request.getSession().setAttribute("mappings", mappings);
                }
            }
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

    //long ms = System.currentTimeMillis();

    if (action.compareTo("upload_data") == 0) {
        if (type.compareTo("codingscheme") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/codingscheme_data.jsf"));
        } else if (type.compareTo("ncimeta") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/ncimeta_data.jsf"));
        } else if (type.compareTo("valueset") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/valueset_data.jsf"));
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/pages/home.jsf"));
    }

}

From source file:org.sakaiproject.login.tool.SkinnableLogin.java

@SuppressWarnings(value = "HRS_REQUEST_PARAMETER_TO_HTTP_HEADER", justification = "Looks like the data is already URL encoded")
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // get the session
    Session session = SessionManager.getCurrentSession();

    // get my tool registration
    Tool tool = (Tool) req.getAttribute(Tool.TOOL);

    // recognize what to do from the path
    String option = req.getPathInfo();

    // maybe we don't want to do the container this time
    boolean skipContainer = false;

    // flag for whether we should show the auth choice page
    boolean showAuthChoice = false;

    // if missing, set it to "/login"
    if ((option == null) || ("/".equals(option))) {
        option = "/login";
    }//from  ww  w. j a v a2s. c  o m

    // look for the extreme login (i.e. to skip container checks)
    else if ("/xlogin".equals(option)) {
        option = "/login";
        skipContainer = true;
    }

    // get the parts (the first will be "", second will be "login" or "logout")
    String[] parts = option.split("/");

    if (parts[1].equals("logout")) {

        // if this is an impersonation, then reset the users old session and
        if (isImpersonating()) {
            UsageSession oldSession = (UsageSession) session
                    .getAttribute(UsageSessionService.USAGE_SESSION_KEY);
            String impersonatingEid = session.getUserEid();
            String userId = oldSession.getUserId();
            String userEid = oldSession.getUserEid();
            log.info("Exiting impersonation of " + impersonatingEid + " and returning to " + userEid);
            ArrayList<String> saveAttributes = new ArrayList<>();
            saveAttributes.add(UsageSessionService.USAGE_SESSION_KEY);
            saveAttributes.add(UsageSessionService.SAKAI_CSRF_SESSION_ATTRIBUTE);
            session.clearExcept(saveAttributes);

            // login - set the user id and eid into session, and refresh this user's authz information
            session.setUserId(userId);
            session.setUserEid(userEid);
            authzGroupService.refreshUser(userId);

            try {
                res.sendRedirect(serverConfigurationService.getString("portalPath", "/portal"));
                res.getWriter().close();
            } catch (IOException e) {
                log.error("failed to redirect after impersonating", e);
            }

            return;
        }

        // get the session info complete needs, since the logout will invalidate and clear the session
        String containerLogoutUrl = serverConfigurationService.getString("login.container.logout.url", null);
        String containerLogout = getServletConfig().getInitParameter("container-logout");
        if (containerLogoutUrl != null && session.getAttribute(ATTR_CONTAINER_SUCCESS) != null
                && containerLogout != null) {
            res.sendRedirect(res.encodeRedirectURL(containerLogout));
        } else {
            String returnUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);
            // logout the user
            UsageSessionService.logout();
            complete(returnUrl, null, tool, res);
        }
        return;
    }

    //SAK-29092 if an auth is specified in the URL, skip any other checks and go straight to it
    String authPreferred = req.getParameter("auth");
    log.debug("authPreferred: " + authPreferred);

    if (StringUtils.equalsIgnoreCase(authPreferred, AuthChoices.XLOGIN.toString())) {
        log.debug("Going straight to xlogin");
        skipContainer = true;
    }

    // see if we need to check container
    boolean checkContainer = serverConfigurationService.getBoolean("container.login", false);
    if (checkContainer && !skipContainer) {
        // if we have not checked the container yet, check it now
        if (session.getAttribute(ATTR_CONTAINER_CHECKED) == null) {
            // save our return path
            session.setAttribute(ATTR_RETURN_URL, Web.returnUrl(req, null));

            String containerCheckPath = this.getServletConfig().getInitParameter("container");
            String containerCheckUrl = Web.serverUrl(req) + containerCheckPath;

            // support query parms in url for container auth
            String queryString = req.getQueryString();
            if (queryString != null)
                containerCheckUrl = containerCheckUrl + "?" + queryString;

            /*
             * FindBugs: HRS_REQUEST_PARAMETER_TO_HTTP_HEADER Looks like the
             * data is already URL encoded. Had to @SuppressWarnings
             * the entire method.
             */

            //SAK-21498 choice page for selecting auth sources
            showAuthChoice = serverConfigurationService.getBoolean("login.auth.choice", false);
            URL helperUrl = null;
            // /portal/relogin doesn't explicitly set a HELPER_DONE_URL so we can't be sure it's there.
            if (session.getAttribute(Tool.HELPER_DONE_URL) != null) {
                helperUrl = new URL((String) session.getAttribute(Tool.HELPER_DONE_URL));
            }
            String helperPath = helperUrl == null ? null : helperUrl.getPath();

            if (StringUtils.equalsIgnoreCase(authPreferred, AuthChoices.CONTAINER.toString())) {
                log.debug("Going straight to container login");
                showAuthChoice = false;
            }

            if (showAuthChoice && !(StringUtils.isEmpty(helperPath) || helperPath.equals("/portal")
                    || helperPath.equals("/portal/"))) {
                String xloginUrl = serverConfigurationService.getPortalUrl() + "/xlogin";

                // Present the choice template
                LoginRenderContext rcontext = startChoiceContext("", req, res);
                rcontext.put("containerLoginUrl", containerCheckUrl);
                rcontext.put("xloginUrl", xloginUrl);

                sendResponse(rcontext, res, "choice", null);

            } else {
                //go straight to container check
                res.sendRedirect(res.encodeRedirectURL(containerCheckUrl));
            }
            return;
        }
    }

    String portalUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);

    // Present the xlogin template
    LoginRenderContext rcontext = startPageContext("", req, res);

    // Decide whether or not to put up the Cancel
    String actualPortal = serverConfigurationService.getPortalUrl();
    if (portalUrl != null && portalUrl.indexOf("/site/") < 1 && portalUrl.startsWith(actualPortal)) {
        rcontext.put("doCancel", Boolean.TRUE);
    }

    sendResponse(rcontext, res, "xlogin", null);
}

From source file:at.gv.egiz.bku.online.webapp.WebRequestHandler.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {

    BindingProcessorManager bindingProcessorManager = (BindingProcessorManager) getServletContext()
            .getAttribute("bindingProcessorManager");
    if (bindingProcessorManager == null) {
        String msg = "Configuration error: BindingProcessorManager missing!";
        log.error(msg);//from  w w  w  . j  ava 2 s  .com
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    Configuration conf = ((BindingProcessorManagerImpl) bindingProcessorManager).getConfiguration();
    if (conf == null)
        log.error("No configuration");
    else
        MoccaParameterBean.setP3PHeader(conf, resp);

    Id id = (Id) req.getAttribute("id");
    if (id == null) {
        String msg = "No request id! Configuration error: ServletFilter missing?";
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    // if binding processor with same id is present: remove
    bindingProcessorManager.removeBindingProcessor(id);

    Locale locale = AcceptLanguage.getLocale(req.getHeader("Accept-Language"));
    if (log.isInfoEnabled()) {
        log.info("Received request (Accept-Language locale: {}).", locale);
    }

    // create new binding processor
    String protocol = MoccaParameterBean.getInitParameter("protocol", getServletConfig(), getServletContext());
    if (protocol == null || protocol.isEmpty()) {
        protocol = req.getScheme();
    }
    HTTPBindingProcessor bindingProcessor = (HTTPBindingProcessor) bindingProcessorManager
            .createBindingProcessor(protocol, locale);

    // set headers
    LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
    if (req.getHeaderNames() != null) {
        for (Enumeration<?> headerName = req.getHeaderNames(); headerName.hasMoreElements();) {
            String name = (String) headerName.nextElement();
            // Account for multiple headers with the same field-name, but
            // they are very rare, so we are not using a StringBuffer.
            Enumeration<?> headers = req.getHeaders(name);
            String value = null;
            while (headers.hasMoreElements()) {
                value = (value == null) ? (String) headers.nextElement() : value + ", " + headers.nextElement();
            }
            headerMap.put(name, value);
        }
    }

    // set request stream 
    InputStream inputStream;
    if (req.getMethod().equals("POST")) {
        inputStream = req.getInputStream();
    } else {
        headerMap.put(HttpUtil.HTTP_HEADER_CONTENT_TYPE, InputDecoderFactory.URL_ENCODED);
        String queryString = req.getQueryString();
        if (queryString != null) {
            inputStream = new ByteArrayInputStream(queryString.getBytes("UTF-8"));
        } else {
            inputStream = new ByteArrayInputStream(new byte[] {});
        }
    }

    bindingProcessor.setHTTPHeaders(headerMap);
    bindingProcessor.consumeRequestStream(req.getRequestURL().toString(), inputStream);
    inputStream.close();

    // process
    bindingProcessorManager.process(id, bindingProcessor);

    log.debug("Sending redirect to user interface.");
    resp.sendRedirect(resp.encodeRedirectURL(uiRedirectUrl));

}

From source file:org.wso2.carbon.identity.policy.consent.UserConsentEnforcerOnExpiration.java

/**
 * this will prompt user to consent to the terms and conditions if they have not already
 *
 * @param request  the request/*from  ww w .  j  a v  a2s  .c o m*/
 * @param response the response
 * @param context  the authentication context
 */
protected AuthenticatorFlowStatus initiateAuthRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context, String errorMessage) throws AuthenticationFailedException {
    String username;
    String tenantDomain;
    String userStoreDomain;
    int tenantId;
    String tenantAwareUsername;
    String fullyQualifiedUsername;
    //        long passwordChangedTime = 0;
    //        int daysDifference = 0;
    String userConsent;
    //        long currentTimeMillis;

    // find the authenticated user.
    AuthenticatedUser authenticatedUser = getUsername(context);
    if (authenticatedUser == null) {
        throw new AuthenticationFailedException(
                "Authentication failed!. Cannot proceed further without identifying the user");
    }
    username = authenticatedUser.getAuthenticatedSubjectIdentifier();
    tenantDomain = authenticatedUser.getTenantDomain();
    userStoreDomain = authenticatedUser.getUserStoreDomain();
    tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    fullyQualifiedUsername = UserCoreUtil.addTenantDomainToEntry(tenantAwareUsername, tenantDomain);
    tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
    RealmService realmService = IdentityTenantUtil.getRealmService();
    UserRealm userRealm;
    UserStoreManager userStoreManager;
    try {
        userRealm = realmService.getTenantUserRealm(tenantId);
        userStoreManager = (UserStoreManager) userRealm.getUserStoreManager();
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Error occurred while loading user manager from user realm", e);
    }
    //        currentTimeMillis = System.currentTimeMillis();
    try {
        userConsent = userStoreManager.getUserClaimValue(tenantAwareUsername,
                UserConsentUtils.USER_CONSENT_CLAIM, null);
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        throw new AuthenticationFailedException(
                "Error occurred while loading user claim - " + UserConsentUtils.USER_CONSENT_CLAIM, e);
    }
    //        if (passwordLastChangedTime != null) {
    //            passwordChangedTime = Long.parseLong(passwordLastChangedTime);
    //        }
    //        if (passwordChangedTime > 0) {
    //            Calendar currentTime = Calendar.getInstance();
    //            currentTime.add(Calendar.DATE, (int) currentTime.getTimeInMillis());
    //            daysDifference = (int) ((currentTimeMillis - passwordChangedTime) / (1000 * 60 * 60 * 24));
    //        }
    if (userConsent == null) {
        // the user has not consented to the terms and conditions, so display the Terms and Conditions Consent page.
        String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL().replace("login.do",
                "user-consent.jsp");
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                context.getCallerSessionKey(), context.getContextIdentifier());
        try {
            String retryParam = "";
            if (context.isRetrying()) {
                retryParam = "&authFailure=true&authFailureMsg=" + errorMessage;
            }
            response.sendRedirect(response
                    .encodeRedirectURL(loginPage + ("?" + queryParams + "&username=" + fullyQualifiedUsername))
                    + "&authenticators=" + getName() + ":" + UserConsentEnforceConstants.AUTHENTICATOR_TYPE
                    + retryParam);
        } catch (IOException e) {
            throw new AuthenticationFailedException(e.getMessage(), e);
        }
        context.setCurrentAuthenticator(getName());
        return AuthenticatorFlowStatus.INCOMPLETE;
    }
    // authentication is now completed in this step. update the authenticated user information.
    updateAuthenticatedUserInStepConfig(context, authenticatedUser);
    return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
}