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:mashups.eventpub.EventPublisherServlet.java

/**
 * Lists events to be published and also sets the custom field map.
 *
 * @param request The request //from   w  w w  .jav a 2  s  .c om
 * @param response The response 
 */
private void processListEvents(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EventPublisher ep = new EventPublisher();

    /*
     * Set the EventPublisher's list feed
     */
    ep.setSsUrl(
            ((String) request.getSession().getAttribute(SESSION_ATTR_SS_CELL_FEED)).replace("cells", "list"));

    if (request.getParameter("fdTitle") != null) {
        SpreadsheetCustomFieldMap fieldMap = new SpreadsheetCustomFieldMap(
                (String) request.getParameter("fdTitle"), (String) request.getParameter("fdDescription"),
                (String) request.getParameter("fdStartDate"), (String) request.getParameter("fdEndDate"),
                (String) request.getParameter("fdLocation"), (String) request.getParameter("fdWebSite"),
                (String) request.getParameter("fdCalendarUrl"), (String) request.getParameter("fdBaseUrl"));
        ep.setFieldMap(fieldMap);
        request.getSession().setAttribute(SESSION_ATTR_FIELD_MAP, fieldMap);
    } else {
        ep.setFieldMap((SpreadsheetCustomFieldMap) request.getSession().getAttribute(SESSION_ATTR_FIELD_MAP));
    }

    try {
        ep.setSsAuthSubToken((String) request.getSession().getAttribute(SESSION_ATTR_SS_AUTH_TOKEN), false);
        List<Event> listEvents = ep.getEventsFromSpreadsheet();
        request.setAttribute("events", listEvents);
        request.getSession().setAttribute(SESSION_ATTR_EVENTS_TO_PUBLISH, listEvents);
        javax.servlet.RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/jsp/outputEventList.jsp");
        dispatcher.forward(request, response);
    } catch (EPAuthenticationException e) {
        System.err.println("Authentication exception: " + e.getMessage());
    }
}

From source file:com.ss.Controller.T4uCURDScheduleServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww. j  a  v a 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 {
    HttpSession session = request.getSession(true);
    T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser);
    if (user == null) { // User not logged in
        LOGGER.debug("User has not yet logged in.");
        String requestUri = request.getRequestURI();
        LOGGER.debug(String.format("Redirecting to /login.jsp?redirect=%s.", requestUri));
        request.setAttribute(T4uConstants.T4U_LOGINREDIRECT, requestUri);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp");
        dispatcher.forward(request, response);
    } else if (!user.getUserGroup().equals("admin")) { // Logged in as a normal user
        request.setAttribute("error", T4uConstants.ExUserNotAuthorised);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp");
        dispatcher.forward(request, response);
    } else { // Logged in as admin
        // Get request
        String action = request.getParameter("action");
        if (action != null) {
            String oSeats = null;
            int versionId = 0;
            int houseId = 0;
            SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
            Date date = null;
            java.sql.Date sqlDate = null;
            Timestamp scheduleTimeslot = null;
            //
            if (action != null) {
                switch (action) {
                case "insert":
                    versionId = Integer.parseInt(request.getParameter("versionId"));
                    houseId = Integer.parseInt(request.getParameter("houseId"));
                    String dateInsert = request.getParameter("scheduleTimeslot");
                    try {
                        date = sourceFormat.parse(dateInsert);
                        scheduleTimeslot = new Timestamp(date.getTime());
                    } catch (ParseException ex) {
                        java.util.logging.Logger.getLogger(T4uRegisterServlet.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                    if (T4uScheduleDAO.insertSchedule(versionId, houseId, scheduleTimeslot) > 0) {
                        // Successfully insert
                        List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                        List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                        for (int scheduleId : allScheduleIds)
                            allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                        session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                        request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    } else {
                        // Error
                        request.setAttribute("error", T4uConstants.ExScheduleError);
                        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                case "update":
                    int scheduleIdUpdate = Integer.parseInt(request.getParameter("scheduleIdUpdate"));
                    oSeats = T4uScheduleDAO.getOSeatsById(scheduleIdUpdate);
                    if (oSeats == null || oSeats.equals("")) {
                        // No seats occupied, allow update
                        versionId = Integer.parseInt(request.getParameter("versionId"));
                        houseId = Integer.parseInt(request.getParameter("houseId"));
                        String dateUpdate = request.getParameter("scheduleTimeslot");
                        try {
                            date = sourceFormat.parse(dateUpdate);
                            scheduleTimeslot = new Timestamp(date.getTime());
                        } catch (ParseException ex) {
                            java.util.logging.Logger.getLogger(T4uRegisterServlet.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                        if (T4uScheduleDAO.updateSchedule(scheduleIdUpdate, versionId, houseId,
                                scheduleTimeslot)) {
                            // Successfully insert
                            List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                            List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                            for (int scheduleId : allScheduleIds)
                                allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                            session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                            request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/schedules.jsp");
                            dispatcher.forward(request, response);
                        } else {
                            // Error
                            request.setAttribute("error", T4uConstants.ExScheduleError);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/error.jsp");
                            dispatcher.forward(request, response);
                        }
                    } else {
                        // Not allow update
                        request.setAttribute("error", T4uConstants.ExScheduleAlreadyOccupied);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                case "delete":
                    int scheduleIdDelete = Integer.parseInt(request.getParameter("scheduleIdDelete"));
                    oSeats = T4uScheduleDAO.getOSeatsById(scheduleIdDelete);
                    if (oSeats == null || oSeats.equals("")) {
                        // No seats occupied, allow delete
                        if (T4uScheduleDAO.deleteSchedule(scheduleIdDelete)) {
                            // Successfully insert
                            List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                            List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                            for (int scheduleId : allScheduleIds)
                                allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                            session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                            request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/schedules.jsp");
                            dispatcher.forward(request, response);
                        } else {
                            // Error
                            request.setAttribute("error", T4uConstants.ExScheduleError);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/error.jsp");
                            dispatcher.forward(request, response);
                        }
                    } else {
                        // Not allow update
                        request.setAttribute("error", T4uConstants.ExScheduleAlreadyOccupied);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                }
            }
        } else {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/schedules.jsp");
            dispatcher.forward(request, response);
        }

    }

    //        HttpSession session = request.getSession(true);
    //        session.setAttribute(T4uConstants.T4uAllSchedules,allSchedules );
    //        session.setAttribute(T4uConstants.T4uAllHouses, allHouses);
    //        session.setAttribute(T4uConstants.T4uAllMovies, allMovies);
    //        json.put("allMovies", allMovies);
    //        json.put("allHouses", allHouses);
}

From source file:controller.uploadPergunta7.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www .  ja va 2  s  .com
 *
 * @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 {

    String idLocal = (String) request.getParameter("idLocal");
    String expressaoModeloVolumePadrao = (String) request.getParameter("expressaoModeloVolumePadrao");
    String equacaoAjustada = (String) request.getParameter("equacaoAjustada");
    String idEquacaoAjustada = (String) request.getParameter("idEquacaoAjustada");

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);

        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    expressaoModeloVolumePadrao = expressaoModeloVolumePadrao.replace("+", "%2B");
    equacaoAjustada = equacaoAjustada.replace("+", "%2B");
    RequestDispatcher view = getServletContext().getRequestDispatcher("/novoLocalPergunta7?id=" + idLocal
            + "&nomeArquivo=" + name + "&expressaoModeloVolumePadrao=" + expressaoModeloVolumePadrao
            + "&equacaoAjustada=" + equacaoAjustada + "&idEquacaoAjustada=" + idEquacaoAjustada);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.listing.ClassHierarchyListingController.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTIONS)) {
        return;/*from w  w w.  j av  a2s.c  o m*/
    }

    VitroRequest vrequest = new VitroRequest(request);

    try {
        boolean inferred = (vrequest.getParameter("inferred") != null);

        if (vrequest.getAssertionsWebappDaoFactory() != null && !inferred) {
            vcDao = vrequest.getAssertionsWebappDaoFactory().getVClassDao();
        } else {
            vcDao = vrequest.getFullWebappDaoFactory().getVClassDao();
        }

        ArrayList<String> results = new ArrayList<String>();
        results.add("XX"); // column 1
        results.add("class"); // column 2
        results.add("shortdef"); // column 3
        results.add("example"); // column 4
        results.add("group"); // column 5
        results.add("ontology"); // column 6
        results.add("display level"); // column 7
        results.add("update level"); // column 8
        results.add("XX"); // column 9

        String ontologyUri = request.getParameter("ontologyUri");
        String startClassUri = request.getParameter("vclassUri");

        List<VClass> roots = null;

        if (ontologyUri != null) {
            roots = vcDao.getOntologyRootClasses(ontologyUri);
        } else if (startClassUri != null) {
            roots = new LinkedList<VClass>();
            roots.add(vcDao.getVClassByURI(startClassUri));
        } else {
            roots = vcDao.getRootClasses();
        }

        if (roots.isEmpty()) {
            roots = new LinkedList<VClass>();
            roots.add(vrequest.getFullWebappDaoFactory().getVClassDao().getTopConcept());
        }

        Collections.sort(roots);

        Iterator rootIt = roots.iterator();
        if (!rootIt.hasNext()) {
            VClass vcw = new VClass();
            vcw.setName("<strong>No classes found.</strong>");
            results.addAll(addVClassDataToResultsList(vrequest.getFullWebappDaoFactory(), vcw, 0, ontologyUri));
        } else {
            while (rootIt.hasNext()) {
                VClass root = (VClass) rootIt.next();
                if (root != null) {
                    ArrayList childResults = new ArrayList();
                    addChildren(vrequest.getFullWebappDaoFactory(), root, childResults, 0, ontologyUri);
                    results.addAll(childResults);
                }
            }
        }

        request.setAttribute("results", results);
        request.setAttribute("columncount", NUM_COLS);
        request.setAttribute("suppressquery", "true");
        request.setAttribute("title", (inferred) ? "Inferred Class Hierarchy" : "Class Hierarchy");
        request.setAttribute("bodyJsp", Controllers.HORIZONTAL_JSP);
        // new way of adding more than one button
        List<ButtonForm> buttons = new ArrayList<ButtonForm>();
        HashMap<String, String> newClassParams = new HashMap<String, String>();
        String temp;
        if ((temp = vrequest.getParameter("ontologyUri")) != null) {
            newClassParams.put("ontologyUri", temp);
        }
        ButtonForm newClassButton = new ButtonForm(Controllers.VCLASS_RETRY_URL, "buttonForm", "Add new class",
                newClassParams);
        buttons.add(newClassButton);
        HashMap<String, String> allClassParams = new HashMap<String, String>();
        if ((temp = vrequest.getParameter("ontologyUri")) != null) {
            allClassParams.put("ontologyUri", temp);
        }
        ButtonForm allClassButton = new ButtonForm("listVClassWebapps", "buttonForm", "All classes",
                allClassParams);
        buttons.add(allClassButton);
        if (!inferred) {
            HashMap<String, String> inferParams = new HashMap<String, String>();
            if ((temp = vrequest.getParameter("ontologyUri")) != null) {
                inferParams.put("ontologyUri", temp);
            }
            inferParams.put("inferred", "1");
            ButtonForm inferButton = new ButtonForm("showClassHierarchy", "buttonForm",
                    "Inferred class hierarchy", inferParams);
            buttons.add(inferButton);
        } else {
            HashMap<String, String> inferParams = new HashMap<String, String>();
            if ((temp = vrequest.getParameter("ontologyUri")) != null) {
                inferParams.put("ontologyUri", temp);
            }
            ButtonForm inferButton = new ButtonForm("showClassHierarchy", "buttonForm",
                    "Asserted class hierarchy", inferParams);
            buttons.add(inferButton);
        }
        request.setAttribute("topButtons", buttons);
        /*
        request.setAttribute("horizontalJspAddButtonUrl", Controllers.VCLASS_RETRY_URL);
        request.setAttribute("horizontalJspAddButtonText", "Add new class");
        */

        RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
        try {
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }

}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobControlInProgressHandler.java

/**
 * Invokes this EntryPageHandler object/*from  w w  w.j  a  v  a2s.c om*/
 * <p>
 * 
 * @param p_ageDescriptor
 *            the description of the page to be produced.
 * @param p_request
 *            original request sent from the browser.
 * @param p_response
 *            original response object.
 * @param p_context
 *            the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    boolean stateMarch = false;
    if (Job.DISPATCHED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    String action = p_request.getParameter(ACTION_STRING);
    if (StringUtil.isNotEmpty(action) && "removeJobFromGroup".equals(action)) {
        removeJobFromGroup(p_request);
    }
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, BASE_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));

    // since an instance of a page handler is used by different clients,
    // this instance variable needs to be set only once. There's no need
    // to synchronize this section as the value of export url is always the
    // same.
    if (m_exportUrl == null) {
        m_exportUrl = ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL();
    }

    if (p_request.getParameter("checkIsUploadingForExport") != null) {
        long jobId = Long.parseLong(p_request.getParameter("jobId"));
        Job job = WorkflowHandlerHelper.getJobById(jobId);
        String result = "";
        for (Workflow workflow : job.getWorkflows()) {
            if (result.length() > 0)
                break;
            Hashtable<Long, Task> tasks = workflow.getTasks();
            for (Long taskKey : tasks.keySet()) {
                if (tasks.get(taskKey).getIsUploading() == 'Y') {
                    result = "uploading";
                    break;
                }
            }
        }
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        out.write(result);
        out.close();
        return;
    } else if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.DISPATCHED);
    JobVoInProgressSearcher searcher = new JobVoInProgressSearcher();
    searcher.setJobVos(p_request, true);
    p_request.setAttribute(EXPORT_URL_PARAM, m_exportUrl);
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.DISPATCHED));
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    sessionMgr.setAttribute("destinationPage", "inprogress");
    // clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache. do both. "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); // HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); // HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to
                                                        // cache
                                                        // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

From source file:dk.itst.oiosaml.sp.service.SPFilter.java

/**
 * Check whether the user is authenticated i.e. having session with a valid
 * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is sent to
 * the Login Site.//w  w  w .  ja va  2 s.  c om
 * 
 * @param request
 *            The servletRequest
 * @param response
 *            The servletResponse
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("OIOSAML-J SP Filter invoked");

    if (!(request instanceof HttpServletRequest)) {
        throw new RuntimeException("Not supported operation...");
    }
    HttpServletRequest servletRequest = ((HttpServletRequest) request);
    Audit.init(servletRequest);

    if (!isFilterInitialized()) {
        try {
            Configuration conf = SAMLConfiguration.getSystemConfiguration();
            setRuntimeConfiguration(conf);
        } catch (IllegalStateException e) {
            request.getRequestDispatcher("/saml/configure").forward(request, response);
            return;
        }
    }
    if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) {
        log.warn("Running in debug mode, skipping regular filter");
        develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf);
        return;
    }

    if (cleanerRunning.compareAndSet(false, true)) {
        SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(),
                ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30);
    }

    SessionHandler sessionHandler = sessionHandlerFactory.getHandler();

    if (servletRequest.getServletPath().equals(conf.getProperty(Constants.PROP_SAML_SERVLET))) {
        log.debug("Request to SAML servlet, access granted");
        chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response);
        return;
    }

    final HttpSession session = servletRequest.getSession();
    if (log.isDebugEnabled())
        log.debug("sessionId....:" + session.getId());

    // Is the user logged in?
    if (sessionHandler.isLoggedIn(session.getId())
            && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null) {
        int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel();
        int assuranceLevel = conf.getInt(Constants.PROP_ASSURANCE_LEVEL);
        if (actualAssuranceLevel < assuranceLevel) {
            sessionHandler.logOut(session);
            log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
            throw new RuntimeException(
                    "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
        }
        UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION);
        if (log.isDebugEnabled())
            log.debug("Everything is ok... Assertion: " + ua);

        Audit.log(Operation.ACCESS, servletRequest.getRequestURI());

        try {
            UserAssertionHolder.set(ua);
            HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname);
            chain.doFilter(requestWrap, response);
            return;
        } finally {
            UserAssertionHolder.set(null);
        }
    } else {
        session.removeAttribute(Constants.SESSION_USER_ASSERTION);
        UserAssertionHolder.set(null);

        String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(servletRequest));

        String protocol = conf.getString(Constants.PROP_PROTOCOL, "saml20");
        String loginUrl = conf.getString(Constants.PROP_SAML_SERVLET, "/saml");

        String protocolUrl = conf.getString(Constants.PROP_PROTOCOL + "." + protocol);
        if (protocolUrl == null) {
            throw new RuntimeException(
                    "No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol);
        }
        loginUrl += protocolUrl;
        if (log.isDebugEnabled())
            log.debug("Redirecting to " + protocol + " login handler at " + loginUrl);

        RequestDispatcher dispatch = servletRequest.getRequestDispatcher(loginUrl);
        dispatch.forward(new SAMLHttpServletRequest(servletRequest, hostname, relayState), response);
    }
}

From source file:edu.lternet.pasta.portal.DataPackageCitationServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from  w  w w  .  ja  va2s .  co  m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;
    Integer id = null;
    boolean isPackageId = false;

    // Accept packageId by parts or whole
    String scope = request.getParameter("scope");
    String identifier = request.getParameter("identifier");
    String revision = request.getParameter("revision");
    String packageid = request.getParameter("packageid");

    try {
        if (scope != null && !(scope.isEmpty()) && identifier != null && !(identifier.isEmpty())
                && revision != null && !(revision.isEmpty())) {

            id = Integer.valueOf(identifier);
            isPackageId = true;

        } else if (packageid != null && !packageid.isEmpty()) {

            String[] tokens = packageid.split("\\.");

            if (tokens.length == 3) {
                scope = tokens[0];
                identifier = tokens[1];
                id = Integer.valueOf(identifier);
                revision = tokens[2];
                isPackageId = true;
            }

        } else {
            throw new ServletException("A well-formed packageId was not found.");
        }

        if (isPackageId) {
            html = this.mapFormatter(uid, scope, id, revision);
        } else {
            throw new ServletException(
                    "The 'scope', 'identifier', or 'revision' field of the packageId is empty.");
        }

        request.setAttribute("citationHtml", html);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
        requestDispatcher.forward(request, response);
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

}

From source file:cust_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www  .j  av a  2  s .  c  o  m
 *
 * @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");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");

            System.out.println(ln.getUId());
            String firstn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            int id = 0;
            String e = "";

            String num = "";
            String p = "";
            String custphoto = "";
            String custname = "";
            String area = "";

            // creates FileItem instances which keep their content in a temporary file on disk
            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("fname")) {
                        firstn = fileItem.getString();
                        System.out.println(firstn);
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                        System.out.println(lastn);
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                        System.out.println(un);
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                        System.out.println(state);
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                        System.out.println(city);
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                        System.out.println(e);
                    }

                    else if (fieldName.equals("number")) {
                        num = fileItem.getString();
                        System.out.println(num);

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

                } else {

                    //getting name of file
                    custphoto = 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;

                    System.out.println(custphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

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

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //             String op="";
            //                cr.add(Restrictions.eq("sId", Integer.parseInt(state)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                StateMaster sm = ar.get(0);
            //                op=sm.getSName();
            //                
            //            }

            CustomerDetail cd1 = (CustomerDetail) ss.get(CustomerDetail.class, id);
            System.out.println("cid is " + cd1.getCId());
            CustomerDetail cd = new CustomerDetail();

            cd.setUId(cd1.getUId());
            cd.setCId(cd1.getCId());
            cd.setCFname(firstn);
            cd.setCLname(lastn);
            cd.setCNum(num);
            cd.setCEmail(e);
            cd.setCState(state);
            cd.setCCity(city);
            cd.setCArea(area);
            cd.setCImg(custphoto);

            ss.evict(cd1);
            ss.update(cd);

            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("customerprofile.jsp");
            rd.forward(request, response);

        }

    }

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

}

From source file:at.gv.egovernment.moa.id.configuration.filter.AuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterchain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) req;
    HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

    HttpSession session = httpServletRequest.getSession();

    Object authuserobj = session.getAttribute(Constants.SESSION_AUTH);
    AuthenticatedUser authuser = (AuthenticatedUser) authuserobj;

    String requestURL = WebAppUtil.getRequestURLWithParameters(httpServletRequest, true);

    log.trace("Request URL: " + requestURL);

    AuthenticationManager authManager = AuthenticationManager.getInstance();
    if (!authManager.isActiveUser(authuser)) {
        //user is not active anymore. Invalidate session and reauthenticate user
        String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID);
        session.invalidate();/*  w w  w . j  a  v  a  2 s . c  o m*/
        authuser = null;

        //TODO: set infotext

        session = httpServletRequest.getSession(true);
        session.setAttribute(Constants.SESSION_PVP2REQUESTID, authID);
    }

    if (authuser == null && !this.isExcluded(requestURL)) {

        if (config.isLoginDeaktivated()) {
            //add dummy Daten
            log.warn("Authentication is deaktivated. Dummy authentication-information are used!");

            if (authuser == null) {
                int sessionTimeOut = session.getMaxInactiveInterval();
                Date sessionExpired = new Date(
                        new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

                authuser = AuthenticatedUser.generateDefaultUser(sessionExpired);
                authManager.setActiveUser(authuser);

                //authuser = new AuthenticatedUser(1, "Max", "TestUser", true, false);
                httpServletRequest.getSession().setAttribute(Constants.SESSION_AUTH, authuser);
            }

            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                if (loginPageForward) {
                    log.debug("Authenticated page is set. Forwarding to \"" + getAuthenticatedPage() + "\".");
                    RequestDispatcher dispatcher = req.getRequestDispatcher(getAuthenticatedPage());
                    dispatcher.forward(httpServletRequest, httpServletResponse);
                } else {
                    log.debug("Authenticated page is set. Redirecting to \"" + getAuthenticatedPage() + "\".");
                    httpServletResponse
                            .sendRedirect(httpServletResponse.encodeRedirectURL(getAuthenticatedPage()));
                }
                return;
            }

        } else {
            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                log.debug(
                        "Unable to find authentication data. Authenticated page is given so there is no need to save original request url. "
                                + (loginPageForward ? "Forwarding" : "Redirecting") + " to login page \""
                                + loginPage + "\".");

            } else {
                log.debug("Unable to find authentication data. Storing request url and "
                        + (loginPageForward ? "forwarding" : "redirecting") + " to login page \"" + loginPage
                        + "\".");
                session.setAttribute(STORED_REQUEST_URL_ID, requestURL);

            }

            if (loginPageForward) {
                RequestDispatcher dispatcher = req.getRequestDispatcher(loginPage);
                dispatcher.forward(httpServletRequest, httpServletResponse);
                return;

            } else {
                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(loginPage));
                return;

            }
        }

    } else {
        try {
            filterchain.doFilter(req, resp);

        } catch (Exception e) {

            //String redirectURL = "./index.action";
            //HttpServletResponse httpResp = (HttpServletResponse) resp;
            //redirectURL = httpResp.encodeRedirectURL(redirectURL);
            //resp.setContentType("text/html");
            //((HttpServletResponse) resp).setStatus(302);
            //httpResp.addHeader("Location", redirectURL);
            //log.warn("A Filter Error occurs -> Redirect to Login-Form");
        }
    }
}

From source file:cn.vlabs.duckling.vwb.VWBDriverServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    URLParser info = URLParser.getParser(request);
    if (info.hasMoreSlash()) {
        response.sendRedirect(buildURL(info, request));
        return;/*from  w ww .  ja v  a  2s.  com*/
    }
    SiteMetaInfo site = findSiteById(request, info.getSiteId());

    if (site == null) {
        site = findSiteByDomain(request);
    }

    if (site == null) {
        log.info("Neither site find by site id or domain. redirect to default site.");
        site = container.getSite(VWBContainer.ADMIN_SITE_ID);
        response.sendRedirect(getFrontPage(request));
        return;
    }
    if (requireRedirect(request, info, site.getId())) {
        response.sendRedirect(getFrontPage(request));
        return;
    }

    if (info.isPlainURL()) {
        // Plain URL just forward.
        // support for Site id based url (login/logout/JSON-RPC etc.).
        if (info.getPage() != null) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(info.getPage());
            dispatcher.forward(request, response);
            return;
        }
    }

    if (info.isSimpleURL()) {
        processSimpleURL(info, request, response);
        return;
    }

    if (info.getPage() == null) {
        response.sendRedirect(getFrontPage(request));
        return;
    }
    // Proceeding viewport...
    int vid = Constant.DEFAULT_FRONT_PAGE;

    vid = Integer.parseInt(info.getPage());
    Resource vp = VWBContainerImpl.findContainer().getResourceService().getResource(site.getId(), vid);
    if (vp == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try {
        if (showWelcome(request, site, vid)) {
            vid = Constant.WELCOME_FRONT_PAGE;
            vp = VWBContainerImpl.findContainer().getResourceService().getResource(site.getId(), vid);
        }
    } catch (NumberFormatException e) {
        response.sendRedirect(getFrontPage(request));
        return;
    }

    request.setAttribute("contextPath", request.getContextPath());
    try {
        IRequestMapper mapper = container.getMapFactory().getRequestMapper(vp.getType());
        if (mapper != null) {
            log.debug(vp.getType() + " is requested.");
            fetcher.saveToSession(request);
            mapper.map(vp, info.getParams(), request, response);
        } else {
            log.debug("not support type is requested.");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } catch (ServletException e) {
        if (e.getRootCause() != null) {
            sendError(request, response, e.getRootCause());
        } else
            sendError(request, response, e);
    } catch (Throwable e) {
        sendError(request, response, e);
    }
}