Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

From source file:property_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w w  . j a  va  2  s . c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession hs = request.getSession();
    try {
        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");
            System.out.println(ln.getUId());

            String pradd1 = "";
            String pradd2 = "";
            String prage = "";

            String prbhk = "";
            String prdescrip = "";
            String prprice = "";

            String state = "";
            String city = "";
            String area = "";
            String prname = "";
            String prtype = "";
            String prphoto = "";
            String prphoto1 = "";
            String prphoto2 = "";
            String prphoto3 = "";
            String prfarea = "";
            int prid = 0;

            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("pname")) {
                        //getting value of field
                        prname = fileItem.getString();
                        System.out.println(prname);
                    } else if (fieldName.equals("price")) {
                        //getting value of field
                        prprice = fileItem.getString();
                        System.out.println(prprice);
                    } else if (fieldName.equals("pid")) {
                        prid = Integer.parseInt(fileItem.getString());

                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("pbhk")) {
                        prbhk = fileItem.getString();
                        System.out.println(prbhk);
                    } else if (fieldName.equals("pdescription")) {
                        prdescrip = fileItem.getString();
                        System.out.println(prdescrip);

                    } else if (fieldName.equals("ptype")) {
                        prtype = fileItem.getString();
                        System.out.println(prtype);

                    } else if (fieldName.equals("paddress1")) {
                        pradd1 = fileItem.getString();
                        System.out.println(pradd1);
                    } else if (fieldName.equals("paddress2")) {
                        pradd2 = fileItem.getString();
                        System.out.println(pradd2);
                    } else if (fieldName.equals("page")) {
                        prage = fileItem.getString();
                        System.out.println(prage);
                    } else if (fieldName.equals("pfarea")) {
                        prfarea = fileItem.getString();
                        System.out.println(prfarea);
                    } else if (fieldName.equals("prid")) {
                        prid = Integer.parseInt(fileItem.getString());
                        System.out.println("prid is " + prid);
                    }

                } else {

                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("pic1")) {
                        //getting name of file
                        prphoto = new File(fileItem.getName()).getName();
                        //get the extension of file by diving name into substring
                        //  String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());;
                        //rename file...concate name and extension
                        // custphoto=ln.getUId()+"."+extension;
                        try {
                            // FOR UBUNTU add GETRESOURCE  and GETPATH

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                            System.out.println("====" + fp);
                            fileItem.write(new File(fp + prphoto));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    if (fieldName.equals("pic2")) {

                        prphoto1 = new File(fileItem.getName()).getName();

                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                            System.out.println("====" + fp);
                            fileItem.write(new File(fp + prphoto1));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    if (fieldName.equals("pic3")) {

                        prphoto2 = new File(fileItem.getName()).getName();

                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                            System.out.println("====" + fp);
                            fileItem.write(new File(fp + prphoto2));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }

                    }

                    if (fieldName.equals("pic4")) {
                        prphoto3 = new File(fileItem.getName()).getName();

                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                            System.out.println("====" + fp);
                            fileItem.write(new File(fp + prphoto3));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }
                }
            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();

            //           String state="";
            //            Criteria cr = ss.createCriteria(StateMaster.class);
            //            cr.add(Restrictions.eq("sId", Integer.parseInt(stateid)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            System.out.println("----------"+ar.size());
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                state = ar.get(0).getSName();
            //                System.out.println("-------"+ar.get(0));
            //            }
            //            
            //            String city="";
            //            Criteria cr2 = ss.createCriteria(CityMaster.class);
            //            cr2.add(Restrictions.eq("cityId", Integer.parseInt(cityid)));
            //            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>)cr2.list();
            //            System.out.println("----------"+ar2.size());
            //            if(ar2.isEmpty()){
            //                
            //            }else{
            //                city = ar2.get(0).getCityName();
            //                System.out.println("-------"+city);
            //            }
            //            
            //            String area="";
            //            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            //            cr3.add(Restrictions.eq("areaId", Integer.parseInt(areaid)));
            //            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>)cr3.list();
            //            System.out.println("----------"+ar3.size());
            //            if(ar3.isEmpty()){
            //                
            //            }else{
            //                area = ar3.get(0).getAreaName();
            //                System.out.println("-------"+area);
            //            }
            //            
            //       Criteria crr=ss.createCriteria(AgentDetail.class);
            //       crr.add(Restrictions.eq("uId", ln.getUId()));
            //       ArrayList<AgentDetail> arr=(ArrayList<AgentDetail>)crr.list();
            //       if(arr.isEmpty())
            //       {
            //           out.print("array empty");
            //       }
            //       else
            //       {
            //           AgentDetail agd=arr.get(0);
            PropDetail prd = (PropDetail) ss.get(PropDetail.class, prid);
            System.out.println("old object id is " + prd.getPId());
            PropDetail prd1 = new PropDetail();

            prd1.setUId(prd.getUId());
            prd1.setPId(prd.getPId());
            prd1.setPDescription(prdescrip);
            prd1.setPImg1(prphoto1);
            prd1.setPImg2(prphoto2);
            prd1.setPImg3(prphoto3);
            prd1.setPImg4(prphoto);
            prd1.setPAdd1(pradd1);
            prd1.setPAdd2(pradd2);
            prd1.setPAge(Integer.parseInt(prage));
            prd1.setPBhk(prbhk);
            prd1.setPFloor(Integer.parseInt(prfarea));
            prd1.setPGmap(null);
            prd1.setPName(prname);
            prd1.setPPrice(Integer.parseInt(prprice));
            prd1.setPStatus(null);
            prd1.setPCity(city);
            prd1.setPArea(area);
            prd1.setPState(state);
            prd1.setPType(prtype);

            ss.evict(prd);
            ss.update(prd1);
            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("getstate?id=9");
            rd.forward(request, response);
        }

    } catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

From source file:cn.org.pomer.web.DirectResult.java

private void doDispatcher(HttpServletResponse response, HttpServletRequest request, String resultCodeAsLocation)
        throws IOException, ServletException {
    if (_log.isInfoEnabled()) {
        _log.info("Forwarding to location:" + resultCodeAsLocation);
    }//from w w w.j a v  a  2  s  . c  om

    PageContext pageContext = ServletActionContext.getPageContext();
    if (pageContext != null) {
        pageContext.include(resultCodeAsLocation);
        return;
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher(resultCodeAsLocation);
    if (dispatcher == null) {
        response.sendError(404, "result '" + resultCodeAsLocation + "' not found");
        return;
    }

    if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
        request.setAttribute("struts.view_uri", resultCodeAsLocation);
        request.setAttribute("struts.request_uri", request.getRequestURI());

        dispatcher.forward(request, response);
    } else {
        dispatcher.include(request, response);
    }
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    RequestDispatcher dispatcher = null;
    String param = request.getParameter("go");
    if (param == null)
        throw new ServletException("Missing parameter in Controller.");
    else if (param.equals("weather"))
        dispatcher = getServletContext().getNamedDispatcher("Weather");
    else if (param.equals("maps"))
        dispatcher = getServletContext().getNamedDispatcher("Maps");
    else/*from  w w  w  .  ja v a2 s  .c  o  m*/
        throw new ServletException("Improper parameter passed to Controller.");
    /*check for a null dispatcher, then 
    dispatch the request to the correct URL*/
    if (dispatcher != null)
        dispatcher.forward(request, response);
    else
        throw new ServletException("Controller received a null dispatcher.");
}

From source file:de.jwi.jfm.servlets.Controller.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String self = null;/*from   w  w  w.  j  av a2 s. com*/
    String contextPath = null;
    String pathInfo = null;
    Folder folder = null;
    String queryString = null;

    try {
        contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String method = request.getMethod();
        boolean formPosted = "POST".equals(method);

        pathInfo = request.getPathInfo();

        if (null == pathInfo) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + servletPath + " is alive.");

            return;
        }

        File f = new File(filebase, pathInfo);

        if (!f.exists()) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + pathInfo + " does not exist.");

            return;
        }

        if (f.isFile()) {
            doDownload(request, response, f);
            return;
        }

        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(request.getRequestURL() + "/");
            return;
        }

        queryString = request.getQueryString();

        String pathTranslated = request.getPathTranslated();
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();

        self = contextPath + servletPath;

        String fileURL = requestURI.replaceFirst(contextPath, "");
        fileURL = fileURL.replaceFirst(servletPath, "");

        folder = new Folder(f, pathInfo, fileURL);

        folder.load();

        String actionresult = "";

        if (FileUpload.isMultipartContent(request)) {
            try {
                actionresult = handleUpload(request, folder);
                folder.load();
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else if (formPosted || null != queryString) {
            try {
                actionresult = handleQuery(request, response, folder);
            } catch (OutOfSyncException e) {
                actionresult = e.getMessage();
            }
            if (null == actionresult) {
                return;
            }
        }

        request.setAttribute("actionresult", actionresult);
    } catch (SecurityException e) {
        request.setAttribute("actionresult", e.getClass().getName() + " " + e.getMessage());
        request.setAttribute("fatalerror", new Boolean(true));

    }

    String s = request.getRemoteUser();

    Principal principal = request.getUserPrincipal();

    if (principal != null) {
        request.setAttribute("principal", principal.getName());
    }

    request.setAttribute("self", self);

    s = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z").format(new Date());

    request.setAttribute("date", s);

    request.setAttribute("version", version);

    request.setAttribute("builddate", builddate);

    request.setAttribute("javaversion", System.getProperty("java.version"));

    request.setAttribute("serverInfo", getServletContext().getServerInfo());

    request.setAttribute("jfmhome", "https://java.net/projects/jfm");

    request.setAttribute("url", contextPath);

    request.setAttribute("path", pathInfo);

    request.setAttribute("folder", folder);

    String forward = "/WEB-INF/fm.jsp";

    if (queryString != null) {
        // hide get query parameters
        //         response.sendRedirect(request.getRequestURL() + "");
        //         return;
    }

    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(forward);

    requestDispatcher.forward(request, response);
}

From source file:org.b3log.latke.servlet.HTTPRequestDispatcher.java

/**
 * Serves.//from  w  w  w  . j  av a2  s  .c  om
 *
 * @param request the specified HTTP servlet request
 * @param response the specified HTTP servlet response
 * @throws ServletException servlet exception
 * @throws IOException io exception
 */
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final String resourcePath = request.getPathTranslated();
    final String requestURI = request.getRequestURI();

    LOGGER.log(Level.FINEST, "Request[contextPath={0}, pathTranslated={1}, requestURI={2}]",
            new Object[] { request.getContextPath(), resourcePath, requestURI });

    if (StaticResources.isStatic(request)) {
        final RequestDispatcher requestDispatcher = getServletContext().getNamedDispatcher(defaultServletName);

        if (null == requestDispatcher) {
            throw new IllegalStateException("A RequestDispatcher could not be located for the default servlet ["
                    + this.defaultServletName + "]");
        }

        requestDispatcher.forward(request, response);
        return;
    }

    final long startTimeMillis = System.currentTimeMillis();

    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    if (Latkes.isPageCacheEnabled()) {
        final String queryString = request.getQueryString();
        String pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);

        if (Strings.isEmptyOrNull(pageCacheKey)) {
            pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
            request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
        }
    }

    // Encoding configuration to filter/EncodingFilter

    final HTTPRequestContext context = new HTTPRequestContext();

    context.setRequest(request);
    context.setResponse(response);

    dispatch(context);
}

From source file:org.apache.catalina.authenticator.FormAuthenticator.java

/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed/*  w ww . java 2 s.  co  m*/
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException {

    // References to objects we will need later
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    Session session = null;

    // Have we already authenticated someone?
    Principal principal = hreq.getUserPrincipal();
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (principal != null) {
        if (log.isDebugEnabled())
            log.debug("Already authenticated '" + principal.getName() + "'");
        // Associate the session with any existing SSO session
        if (ssoId != null)
            associate(ssoId, getSession(request, true));
        return (true);
    }

    // Is there an SSO session against which we can try to reauthenticate?
    if (ssoId != null) {
        if (log.isDebugEnabled())
            log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication");
        // Try to reauthenticate using data cached by SSO.  If this fails,
        // either the original SSO logon was of DIGEST or SSL (which
        // we can't reauthenticate ourselves because there is no
        // cached username and password), or the realm denied
        // the user's reauthentication for some reason.
        // In either case we have to prompt the user for a logon */
        if (reauthenticateFromSSO(ssoId, request))
            return true;
    }

    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled())
                log.debug("Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                register(request, response, principal, Constants.FORM_METHOD, username, password);
                return (true);
            }
            if (log.isDebugEnabled())
                log.debug("Reauthentication failed, proceed normally");
        }
    }

    // Is this the re-submit of the original request URI after successful
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Restore request from session '" + session.getId() + "'");
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD,
                (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled())
                log.debug("Proceed to restored request");
            return (true);
        } else {
            if (log.isDebugEnabled())
                log.debug("Restore of original request failed");
            hres.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }

    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    String contextPath = hreq.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    response.setContext(request.getContext());

    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);

    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Save request in session '" + session.getId() + "'");
        saveRequest(request, session);
        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getLoginPage());
        try {
            disp.forward(hreq, hres);
            response.finishResponse();
        } catch (Throwable t) {
            log.warn("Unexpected error forwarding to login page", t);
        }
        return (false);
    }

    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();
    String username = hreq.getParameter(Constants.FORM_USERNAME);
    String password = hreq.getParameter(Constants.FORM_PASSWORD);
    if (log.isDebugEnabled())
        log.debug("Authenticating username '" + username + "'");
    principal = realm.authenticate(username, password);
    if (principal == null) {
        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getErrorPage());
        try {
            disp.forward(hreq, hres);
        } catch (Throwable t) {
            log.warn("Unexpected error forwarding to error page", t);
        }
        return (false);
    }

    // Save the authenticated Principal in our session
    if (log.isDebugEnabled())
        log.debug("Authentication of '" + username + "' was successful");
    if (session == null)
        session = getSession(request, true);
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);

    // If we are not caching, save the username and password as well
    if (!cache) {
        session.setNote(Constants.SESS_USERNAME_NOTE, username);
        session.setNote(Constants.SESS_PASSWORD_NOTE, password);
    }

    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled())
        log.debug("Redirecting to original '" + requestURI + "'");
    if (requestURI == null)
        hres.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
    else
        hres.sendRedirect(hres.encodeRedirectURL(requestURI));
    return (false);

}

From source file:com.github.mike10004.stormpathacctmgr.NewPasswordFormServletTest.java

@Test
public void testDoGet() throws Exception {
    System.out.println("NewPasswordFormServletTest.testDoGet");
    String emailAddress = "somebody@example.com";
    String token = "981ng9014ng4nh9014h901nh4jhqg8rejg089rjg09zahg49hqg08";
    final Application application = createNiceMock(Application.class);
    Account account = createNiceMock(Account.class);
    final RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest() {

        @Override/*  w  w w .j av a  2  s.  c  om*/
        public RequestDispatcher getRequestDispatcher(String path) {
            assertEquals(NewPasswordFormServlet.RESET_ENTER_NEW_PASSWORD_JSP_PATH, path);
            return requestDispatcher;
        }

    };
    mockRequest.setParameter(PasswordReset.PARAM_RESET_TOKEN, token);
    requestDispatcher.forward(mockRequest, mockResponse);
    EasyMock.expectLastCall().times(1);
    expect(account.getEmail()).andReturn(emailAddress).anyTimes();
    expect(application.verifyPasswordResetToken(token)).andReturn(account).times(1);
    replay(application, account, requestDispatcher);

    final Stormpaths stormpaths = new Stormpaths() {

        @Override
        public Application buildApplication() {
            return application;
        }

    };
    NewPasswordFormServlet instance = new NewPasswordFormServlet() {

        @Override
        protected Stormpaths createStormpaths() {
            return stormpaths;
        }

    };
    MockServletContext servletContext = new MockServletContext();
    instance.init(new MockServletConfig(servletContext));
    instance.doGet(mockRequest, mockResponse);
    String actualTargetEmailAttribute = (String) mockRequest
            .getAttribute(NewPasswordFormServlet.ATTR_TARGET_EMAIL);
    System.out.println("email attribute: " + actualTargetEmailAttribute);
    assertEquals(emailAddress, actualTargetEmailAttribute);
    System.out.println("status: " + mockResponse.getStatus());
    assertEquals(HttpServletResponse.SC_OK, mockResponse.getStatus());
}

From source file:com.zimbra.cs.service.ExternalUserProvServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String param = req.getParameter("p");
    if (param == null) {
        throw new ServletException("request missing param");
    }/*  ww  w  . j  ava2  s .  c  o  m*/
    Map<Object, Object> tokenMap = validatePrelimToken(param);
    Map<String, String> reqHeaders = new HashMap<String, String>();
    String ownerId = (String) tokenMap.get("aid");
    String folderId = (String) tokenMap.get("fid");
    String extUserEmail = (String) tokenMap.get("email");

    Provisioning prov = Provisioning.getInstance();
    Account grantee;
    try {
        Account owner = prov.getAccountById(ownerId);
        Domain domain = prov.getDomain(owner);
        grantee = prov.getAccountByName(mapExtEmailToAcctName(extUserEmail, domain));
        if (grantee == null) {
            // external virtual account not created yet
            if (prov.isOctopus() && DebugConfig.skipVirtualAccountRegistrationPage) {
                // provision using 'null' password and display name
                // UI will ask the user to set these post provisioning
                provisionVirtualAccountAndRedirect(req, resp, null, null, ownerId, extUserEmail);
            } else {
                resp.addCookie(new Cookie("ZM_PRELIM_AUTH_TOKEN", param));
                req.setAttribute("extuseremail", extUserEmail);
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("extuseremail", extUserEmail);
                    reqHeaders.put("ZM_PRELIM_AUTH_TOKEN", param);
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(EXT_USER_PROV_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    ServletContext context = getServletContext().getContext("/zimbra");
                    if (context != null) {
                        RequestDispatcher dispatcher = context.getRequestDispatcher(PUBLIC_EXTUSERPROV_JSP);
                        dispatcher.forward(req, resp);
                    } else {
                        logger.warn("Could not access servlet context url /zimbra");
                        throw ServiceException.TEMPORARILY_UNAVAILABLE();
                    }
                }
            }
        } else {
            // create a new mountpoint in the external user's mailbox if not already created

            String[] sharedItems = owner.getSharedItem();
            int sharedFolderId = Integer.valueOf(folderId);
            String sharedFolderPath = null;
            MailItem.Type sharedFolderView = null;
            for (String sharedItem : sharedItems) {
                ShareInfoData sid = AclPushSerializer.deserialize(sharedItem);
                if (sid.getItemId() == sharedFolderId && extUserEmail.equalsIgnoreCase(sid.getGranteeId())) {
                    sharedFolderPath = sid.getPath();
                    sharedFolderView = sid.getFolderDefaultViewCode();
                    break;
                }
            }
            if (sharedFolderPath == null) {
                throw new ServletException("share not found");
            }
            String mountpointName = getMountpointName(owner, grantee, sharedFolderPath);

            ZMailbox.Options options = new ZMailbox.Options();
            options.setNoSession(true);
            options.setAuthToken(AuthProvider.getAuthToken(grantee).toZAuthToken());
            options.setUri(AccountUtil.getSoapUri(grantee));
            ZMailbox zMailbox = new ZMailbox(options);
            ZMountpoint zMtpt = null;
            try {
                zMtpt = zMailbox.createMountpoint(String.valueOf(getMptParentFolderId(sharedFolderView, prov)),
                        mountpointName, ZFolder.View.fromString(sharedFolderView.toString()),
                        ZFolder.Color.DEFAULTCOLOR, null, ZMailbox.OwnerBy.BY_ID, ownerId,
                        ZMailbox.SharedItemBy.BY_ID, folderId, false);
            } catch (ServiceException e) {
                logger.debug("Error in attempting to create mountpoint. Probably it already exists.", e);
            }
            if (zMtpt != null) {
                if (sharedFolderView == MailItem.Type.APPOINTMENT) {
                    // make sure that the mountpoint is checked in the UI by default
                    FolderActionSelector actionSelector = new FolderActionSelector(zMtpt.getId(), "check");
                    FolderActionRequest actionRequest = new FolderActionRequest(actionSelector);
                    try {
                        zMailbox.invokeJaxb(actionRequest);
                    } catch (ServiceException e) {
                        logger.warn("Error in invoking check action on calendar mountpoint", e);
                    }
                }
                HashSet<MailItem.Type> types = new HashSet<MailItem.Type>();
                types.add(sharedFolderView);
                enableAppFeatures(grantee, types);
            }

            // check if the external user is already logged-in
            String zAuthTokenCookie = null;
            javax.servlet.http.Cookie cookies[] = req.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("ZM_AUTH_TOKEN")) {
                        zAuthTokenCookie = cookie.getValue();
                        break;
                    }
                }
            }
            AuthToken zAuthToken = null;
            if (zAuthTokenCookie != null) {
                try {
                    zAuthToken = AuthProvider.getAuthToken(zAuthTokenCookie);
                } catch (AuthTokenException ignored) {
                    // auth token is not valid
                }
            }
            if (zAuthToken != null && !zAuthToken.isExpired() && zAuthToken.isRegistered()
                    && grantee.getId().equals(zAuthToken.getAccountId())) {
                // external virtual account already logged-in
                resp.sendRedirect("/");
            } else if (prov.isOctopus() && !grantee.isVirtualAccountInitialPasswordSet()
                    && DebugConfig.skipVirtualAccountRegistrationPage) {
                // seems like the virtual user did not set his password during his last visit, after an account was
                // provisioned for him
                setCookieAndRedirect(req, resp, grantee);
            } else {
                req.setAttribute("virtualacctdomain", domain.getName());
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("virtualacctdomain", domain.getName());
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(PUBLIC_LOGIN_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    RequestDispatcher dispatcher = getServletContext().getContext("/zimbra")
                            .getRequestDispatcher(PUBLIC_LOGIN_JSP);
                    dispatcher.forward(req, resp);
                }
            }
        }
    } catch (ServiceException e) {
        throw new ServletException(e);
    }
}

From source file:com.vmware.identity.proxyservice.LogonProcessorImpl.java

/**
 * Choose a relying party site to send the assertion.
 *  1. Check RelayState//from w w w  .j a v  a  2 s  .  c o m
 *  2. Check if the selection is made by user.
 *  3. If not promp user for selection and return null from this function. The user selection of RP will come in as
 *      a new request.
 *
 * @param tenant
 * @param request
 * @param response
 * @param locale
 * @return EntityID string of the selected RP. Null if Choose RP dialog is called.
 * @throws SamlServiceException not able to dispatch request to RP selection jsp.
 */
private String chooseSignInRPSite(IdmAccessor idmAccessor, HttpServletRequest request,
        HttpServletResponse response, Locale locale) throws SamlServiceException {

    Validate.notNull(idmAccessor, "idmAccessor");
    Validate.notNull(request, "request");
    Validate.notNull(response, "response");

    String tenant = idmAccessor.getTenant();
    Validate.notNull(tenant, "tenant");

    //Use RelayState if available.
    String rp_selected = request.getParameter(Shared.RELAY_STATE_PARAMETER);
    if (rp_selected != null && !rp_selected.isEmpty()) {
        String rpID;
        try {
            rpID = URLDecoder.decode(rp_selected, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new SamlServiceException("Failed in URL-decoding RelayState: " + rp_selected, e);
        }
        log.debug("IDP_Initiated response has relay state which will be used for"
                + " identifying Relying Party. RelyingPartyID: " + rpID);
        return rpID;
    }

    //Check "CastleRPSelection" header
    rp_selected = request.getHeader(Shared.RP_SELECTION_ENTITYID);

    if (rp_selected != null && !rp_selected.isEmpty()) {
        log.debug(
                "IDP_Initiated response has \"CastleRPSelection\" header which will be used for identifying Relying Party.");
        return rp_selected;
    }

    Collection<RelyingParty> rpCollection = idmAccessor.getRelyingParties(tenant);

    //Prepare lists of RP URL and name for the selection dialog
    Iterator<RelyingParty> it = rpCollection.iterator();

    //Skip the Relying party selection if only one RP is registered
    if (rpCollection.size() == 1) {
        return it.next().getUrl();
    }

    List<String> rpEntityIdList = new ArrayList<String>();
    List<String> rpNameList = new ArrayList<String>();
    while (it.hasNext()) {
        RelyingParty rp = it.next();
        rpEntityIdList.add(rp.getUrl());
        rpNameList.add(rp.getName());
    }

    //dispatch selection form
    request.setAttribute(RPSelectionParam_RPNameList, rpNameList);
    request.setAttribute(RPSelectionParam_RPEntityIDList, rpEntityIdList);

    String samlResponseStr = request.getParameter(Shared.SAML_RESPONSE_PARAMETER);
    request.setAttribute(RPSelectionParam_SAMLResponse, StringEscapeUtils.escapeJavaScript(samlResponseStr));
    request.setAttribute(RPSelectionParam_DialogTittle,
            messageSource.getMessage("ChooseService.Title", null, locale));
    RequestDispatcher dispatcher = request.getRequestDispatcher(RPSelectionJSP);
    try {
        dispatcher.forward(request, response);
    } catch (Exception e) {
        throw new SamlServiceException("Failed in dispatch request to RPSelection.jsp", e);
    }

    return null;
}

From source file:gov.nih.nci.security.cgmm.authenticators.CaGridFormAuthenticator.java

/**
 * Called to forward to the error page// w  w w . j  a  v a2s .com
 * 
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed
 */
protected void forwardToErrorPage(Request request, Response response, LoginConfig config) {
    RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getErrorPage());
    try {
        disp.forward(request.getRequest(), response.getResponse());
    } catch (Throwable t) {
        log.warn("Unexpected error forwarding to error page", t);
    }
}