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:edu.lternet.pasta.portal.DataPackageAuditServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from www .  j  ava 2 s . 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 {

    String forward = "./auditReportTable.jsp";

    AuditManagerClient auditClient = null;
    HttpSession httpSession = request.getSession();
    String xml = null;
    StringBuffer filter = new StringBuffer();
    String message = null;
    String pastaUriHead = null;
    String uid = (String) httpSession.getAttribute("uid");

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

    try {
        auditClient = new AuditManagerClient(uid);
        pastaUriHead = auditClient.getPastaUriHead();

        /*
         * Request and process filter parameters
         */

        // Encode empty request parameters with SQL regex string "%" 
        String scope = "%25";
        String identifier = "%25";
        String revision = "%25";
        String resourceId = null;

        String value = "";

        value = request.getParameter("scope");
        if (value != null && !value.isEmpty())
            scope = value;

        value = request.getParameter("identifier");
        if (value != null && !value.isEmpty())
            identifier = value;

        value = request.getParameter("revision");
        if (value != null && !value.isEmpty())
            revision = value;

        String packageId = scope + "." + identifier + "." + revision;

        String begin = (String) request.getParameter("begin");
        if (begin != null && !begin.isEmpty()) {
            filter.append("fromTime=" + begin + "&");
        }

        String end = (String) request.getParameter("end");
        if (end != null && !end.isEmpty()) {
            filter.append("toTime=" + end + "&");
        }

        // Filter on "info"
        filter.append("category=info&");

        boolean packageResource = false || (request.getParameter("package") != null);
        boolean metadataResource = false || (request.getParameter("metadata") != null);
        boolean dataResource = false || (request.getParameter("entity") != null);
        boolean reportResource = false || (request.getParameter("report") != null);
        boolean includeAllResources = false;

        if (!(packageResource || metadataResource || dataResource || reportResource)) {
            includeAllResources = true;
        }

        // Filter on "readDataPackage"
        if (packageResource || includeAllResources) {
            filter.append("serviceMethod=readDataPackage&");
            resourceId = getResourceId(pastaUriHead, packageId, PACKAGE);
            filter.append("resourceId=" + resourceId + "&");
        }

        // Filter on "readMetadata"
        if (metadataResource || includeAllResources) {
            filter.append("serviceMethod=readMetadata&");
            resourceId = getResourceId(pastaUriHead, packageId, METADATA);
            filter.append("resourceId=" + resourceId + "&");
        }

        // Filter on "readDataEntity"
        if (dataResource || includeAllResources) {
            filter.append("serviceMethod=readDataEntity&");
            resourceId = getResourceId(pastaUriHead, packageId, ENTITY);
            filter.append("resourceId=" + resourceId + "&");
        }

        // Filter on "readDataPackageReport"
        if (reportResource || includeAllResources) {
            filter.append("serviceMethod=readDataPackageReport&");
            resourceId = getResourceId(pastaUriHead, packageId, REPORT);
            filter.append("resourceId=" + resourceId + "&");
        }

        String userIdParam = (String) request.getParameter("userId");
        if (userIdParam != null && !userIdParam.isEmpty()) {
            String userParam = "public";
            if (!userIdParam.equalsIgnoreCase(userParam)) {
                userParam = PastaClient.composeDistinguishedName(userIdParam);
            }
            filter.append("user=" + userParam + "&");
        }

        String groupParam = (String) request.getParameter("group");
        if (groupParam != null && !groupParam.isEmpty()) {
            filter.append("group=" + groupParam + "&");
        }

        if (limit != null && !limit.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("limit=" + limit);
            } else {
                filter.append("&limit=" + limit);
            }
        }

        if (uid.equals("public")) {
            message = LOGIN_WARNING;
            forward = "./login.jsp";
        } else if (auditClient != null) {
            String filterStr = filter.toString();
            xml = auditClient.reportByFilter(filterStr);
            ReportUtility reportUtility = new ReportUtility(xml);
            message = reportUtility.xmlToHtmlTable(cwd + xslpath);
        }

        request.setAttribute("reportMessage", message);

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

}

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

/**
 * Invokes this EntryPageHandler object//from  ww  w .j  a  v a2s. com
 * <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);

    //"Job Details" >> "View Error" >> "Re-Export" (GBS-908)
    //After re-export,UI will turn back to "Exported" search results list.
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
        String isFromExportErrorPage = p_request.getParameter("fromExportErrorPage");
        if (isFromExportErrorPage != null && "true".equals(isFromExportErrorPage)) {
            User user = (User) sessionMgr.getAttribute(WebAppConstants.USER);
            WorkflowManager wfManager = ServerProxy.getWorkflowManager();
            //Get all the checked pages as an array of strings
            //For "View Error",only one workflow can be selected.
            String pages[] = p_request.getParameterValues("page");
            if (pages != null && pages.length > 0) {
                ArrayList pageIds = new ArrayList();//target pages
                Workflow wf = null;
                Job job = null;
                ArrayList wfIds = new ArrayList();

                // Find the workflows associated with the pages checked
                for (int i = 0; i < pages.length; i++) {
                    // The value of the page param is "pageId_<pageId>_wfId_<wfId>
                    Long curPageId = new Long(
                            pages[i].substring(pages[i].indexOf("pageId_") + 7, pages[i].indexOf("_wfId")));
                    pageIds.add(curPageId);
                    //set values for wf and job only once
                    if (wf == null) {
                        String wfId = pages[i].substring(pages[i].indexOf("_wfId_") + 6, pages[i].length());
                        wf = wfManager.getWorkflowById(new Long(wfId));
                        wfIds.add(new Long(wfId));
                        job = wf.getJob();
                    }
                }
                ExportParameters ep = new ExportParameters(wf);
                boolean isTargetPage = true;
                Long taskId = null;

                long exportBatchId = ServerProxy.getExportEventObserver().notifyBeginExportTargetBatch(job,
                        user, pageIds, wfIds, taskId, ExportBatchEvent.INTERIM_PRIMARY);
                ServerProxy.getPageManager().exportPage(ep, pageIds, isTargetPage, exportBatchId);
            }
        }
    } catch (Exception e) {
        //In fact,no exception will be caught here.
        s_logger.error("Fail to re-export selected pages.", e);
    }

    boolean stateMarch = false;
    if (Job.EXPORTED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, BASE_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));
    // error bean.
    m_exportErrorBean = new NavigationBean(ERROR_BEAN, p_thePageDescriptor.getPageName());
    p_request.setAttribute("action", p_request.getParameter("action"));

    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);
    Vector jobStates = new Vector();
    jobStates.add(Job.EXPORTED);
    jobStates.add(Job.EXPORT_FAIL);
    p_request.setAttribute(JobManagementHandler.EXPORT_URL_PARAM,
            ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL());
    p_request.setAttribute(JobManagementHandler.JOB_ID, JobManagementHandler.JOB_ID);

    sessionMgr.setMyjobsAttribute("lastState", Job.EXPORTED);
    JobVoExportSearcher searcher = new JobVoExportSearcher();
    searcher.setJobVos(p_request);

    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(), jobStates));

    // 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", "exported");
    //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:edu.cornell.mannlib.vitro.webapp.controller.edit.listing.PropertyWebappsListingController.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTIONS)) {
        return;/*from www. jav a  2s .  c  o  m*/
    }

    VitroRequest vrequest = new VitroRequest(request);

    String noResultsMsgStr = "No object properties found";

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

    ObjectPropertyDao dao = vrequest.getFullWebappDaoFactory().getObjectPropertyDao();
    PropertyInstanceDao piDao = vrequest.getFullWebappDaoFactory().getPropertyInstanceDao();
    VClassDao vcDao = vrequest.getFullWebappDaoFactory().getVClassDao();
    PropertyGroupDao pgDao = vrequest.getFullWebappDaoFactory().getPropertyGroupDao();

    String vclassURI = request.getParameter("vclassUri");

    List props = new ArrayList();
    if (request.getParameter("propsForClass") != null) {
        noResultsMsgStr = "There are no properties that apply to this class.";

        // incomplete list of classes to check, but better than before
        List<String> superclassURIs = vcDao.getAllSuperClassURIs(vclassURI);
        superclassURIs.add(vclassURI);
        superclassURIs.addAll(vcDao.getEquivalentClassURIs(vclassURI));

        Map<String, PropertyInstance> propInstMap = new HashMap<String, PropertyInstance>();
        for (String classURI : superclassURIs) {
            Collection<PropertyInstance> propInsts = piDao.getAllPropInstByVClass(classURI);
            for (PropertyInstance propInst : propInsts) {
                propInstMap.put(propInst.getPropertyURI(), propInst);
            }
        }
        List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>();
        propInsts.addAll(propInstMap.values());
        Collections.sort(propInsts);

        Iterator propInstIt = propInsts.iterator();
        HashSet propURIs = new HashSet();
        while (propInstIt.hasNext()) {
            PropertyInstance pi = (PropertyInstance) propInstIt.next();
            if (!(propURIs.contains(pi.getPropertyURI()))) {
                propURIs.add(pi.getPropertyURI());
                ObjectProperty prop = (ObjectProperty) dao.getObjectPropertyByURI(pi.getPropertyURI());
                if (prop != null) {
                    props.add(prop);
                }
            }
        }
    } else {
        props = (request.getParameter("iffRoot") != null) ? dao.getRootObjectProperties()
                : dao.getAllObjectProperties();
    }

    OntologyDao oDao = vrequest.getFullWebappDaoFactory().getOntologyDao();
    HashMap<String, String> ontologyHash = new HashMap<String, String>();

    Iterator propIt = props.iterator();
    List<ObjectProperty> scratch = new ArrayList();
    while (propIt.hasNext()) {
        ObjectProperty p = (ObjectProperty) propIt.next();
        if (p.getNamespace() != null) {
            if (!ontologyHash.containsKey(p.getNamespace())) {
                Ontology o = (Ontology) oDao.getOntologyByURI(p.getNamespace());
                if (o == null) {
                    if (!VitroVocabulary.vitroURI.equals(p.getNamespace())) {
                        log.debug("doGet(): no ontology object found for the namespace " + p.getNamespace());
                    }
                } else {
                    ontologyHash.put(p.getNamespace(), o.getName() == null ? p.getNamespace() : o.getName());
                }
            }
            if (ontologyUri != null && p.getNamespace().equals(ontologyUri)) {
                scratch.add(p);
            }
        }
    }

    if (ontologyUri != null) {
        props = scratch;
    }

    if (props != null) {
        Collections.sort(props, new ObjectPropertyHierarchyListingController.ObjectPropertyAlphaComparator());
    }

    ArrayList results = new ArrayList();
    results.add("XX"); // column 1
    results.add("property public name"); // column 2
    results.add("prefix + local name"); // column 3
    results.add("domain"); // column 4
    results.add("range"); // column 5
    results.add("group"); // column 6
    results.add("display tier"); // column 7
    results.add("display level"); // column 8
    results.add("update level"); // column 9

    if (props != null) {
        if (props.size() == 0) {
            results.add("XX");
            results.add("<strong>" + noResultsMsgStr + "</strong>");
            results.add("");
            results.add("");
            results.add("");
            results.add("");
            results.add("");
            results.add("");
            results.add("");
        } else {
            Iterator propsIt = props.iterator();
            while (propsIt.hasNext()) {
                ObjectProperty prop = (ObjectProperty) propsIt.next();
                results.add("XX");

                String propNameStr = ObjectPropertyHierarchyListingController.getDisplayLabel(prop);
                try {
                    results.add("<a href=\"./propertyEdit?uri=" + URLEncoder.encode(prop.getURI(), "UTF-8")
                            + "\">" + propNameStr + "</a>"); // column 1
                } catch (Exception e) {
                    results.add(propNameStr); // column 2
                }

                results.add(prop.getLocalNameWithPrefix()); // column 3

                VClass vc = (prop.getDomainVClassURI() != null)
                        ? vcDao.getVClassByURI(prop.getDomainVClassURI())
                        : null;
                String domainStr = (vc != null) ? vc.getLocalNameWithPrefix() : "";
                results.add(domainStr); // column 4

                vc = (prop.getRangeVClassURI() != null) ? vcDao.getVClassByURI(prop.getRangeVClassURI()) : null;
                String rangeStr = (vc != null) ? vc.getLocalNameWithPrefix() : "";
                results.add(rangeStr); // column 5

                if (prop.getGroupURI() != null) {
                    PropertyGroup pGroup = pgDao.getGroupByURI(prop.getGroupURI());
                    results.add(pGroup == null ? "unknown group" : pGroup.getName()); // column 6
                } else {
                    results.add("unspecified");
                }
                if (prop.getDomainDisplayTierInteger() != null) {
                    results.add(Integer.toString(prop.getDomainDisplayTierInteger(), BASE_10)); // column 7
                } else {
                    results.add(""); // column 7
                }
                results.add(prop.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)"
                        : prop.getHiddenFromDisplayBelowRoleLevel().getShorthand()); // column 8
                results.add(prop.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)"
                        : prop.getProhibitedFromUpdateBelowRoleLevel().getShorthand()); // column 9
            }
        }
        request.setAttribute("results", results);
    }

    request.setAttribute("columncount", new Integer(NUM_COLS));
    request.setAttribute("suppressquery", "true");
    request.setAttribute("title", "Object Properties");
    request.setAttribute("bodyJsp", Controllers.HORIZONTAL_JSP);

    // new way of adding more than one button
    List<ButtonForm> buttons = new ArrayList<ButtonForm>();
    HashMap<String, String> newPropParams = new HashMap<String, String>();
    newPropParams.put("controller", "Property");
    ButtonForm newPropButton = new ButtonForm(Controllers.RETRY_URL, "buttonForm", "Add new object property",
            newPropParams);
    buttons.add(newPropButton);
    HashMap<String, String> rootPropParams = new HashMap<String, String>();
    rootPropParams.put("iffRoot", "true");
    String temp;
    if ((temp = vrequest.getParameter("ontologyUri")) != null) {
        rootPropParams.put("ontologyUri", temp);
    }
    ButtonForm rootPropButton = new ButtonForm("showObjectPropertyHierarchy", "buttonForm", "root properties",
            rootPropParams);
    buttons.add(rootPropButton);
    request.setAttribute("topButtons", buttons);

    /* original way of adding 1 button
    request.setAttribute("horizontalJspAddButtonUrl", Controllers.RETRY_URL);
    request.setAttribute("horizontalJspAddButtonText", "Add new object property");
    request.setAttribute("horizontalJspAddButtonControllerParam", "Property");
    */
    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    try {
        rd.forward(request, response);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:net.sourceforge.hunterj.javadocViewer.JavadocViewerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w ww.  ja  v a  2  s.  co m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String toRemove = request.getParameter(JVConst.DOCHOME_OPTS_REMOVE.value);
    String realJavadocHome = request.getParameter(JVConst.DOCHOME_PARAM.value);

    if (StringUtils.isNotEmpty(toRemove)) {
        this.removeJavadocHome(request.getSession(), toRemove);
        return;
    }
    if (StringUtils.isEmpty(realJavadocHome)) {
        realJavadocHome = (String) request.getSession().getAttribute(JVConst.DOCHOME_ATTR.value);
        if (StringUtils.isEmpty(realJavadocHome)) {
            request.setAttribute(JVConst.DOCHOME_ERROR.value,
                    new FileNotFoundException("No javadoc home is selected."));
            this.dispatchToView(request, response);
            return;
        }
    }
    // Check to see if the local file path is valid.
    if (!isRemoteResource(realJavadocHome) && Files.notExists(Paths.get(realJavadocHome))) {
        request.setAttribute(JVConst.DOCHOME_ERROR.value,
                new FileNotFoundException("\"".concat(realJavadocHome).concat("\" is not a valid file path.")));
        this.dispatchToView(request, response);
        return;
    }

    // handle sub-requests by iframes for files, not under the servlet context
    String[] urlParts = request.getRequestURI().split(JVConst.DOCHOME_URL_PART.value);
    if (urlParts.length == 2 && realJavadocHome != null) {
        String filePath = realJavadocHome.concat(urlParts[1]);

        // Handle requests to remote servers
        if (this.isRemoteResource(realJavadocHome)) {
            this.doGetRemoteResource(response, filePath);
            return;
        }
        request.setAttribute(FileServlet.ABS_FILE_PATH, filePath);
        RequestDispatcher dispatch = request
                .getRequestDispatcher(response.encodeURL(FileServlet.FILE_SERVE_URI));
        dispatch.forward(request, response);
        return;
    }
    // At this point the request is for the main viewer page and is probably correct/valid.
    this.checkJavadocHome(request.getSession(), realJavadocHome);
    request.getSession().setAttribute(JVConst.DOCHOME_ATTR.value, realJavadocHome);
    this.dispatchToView(request, response);
}

From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w.  j  av  a2 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 {
    response.setContentType("text/html;charset=UTF-8");
    String action = request.getParameter("action");
    System.out.println("action: " + action);
    if (action == null || action.isEmpty()) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //PriceDAO priceDAO = new PriceDAO();

        try {
            List<FileItem> fields = upload.parseRequest(request);
            //out.println("Number of fields: " + fields.size() + "<br/><br/>");
            Iterator<FileItem> it = fields.iterator();
            while (it.hasNext()) {
                FileItem fileItem = it.next();
                //store in webserver.
                String fileName = fileItem.getName();
                if (fileName != null) {
                    File file = new File(fileName);
                    fileItem.write(file);
                    System.out.println("File successfully saved as " + file.getAbsolutePath());

                    //process file
                    Reader in = new FileReader(file.getAbsolutePath());
                    Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
                    for (CSVRecord record : records) {
                        String name = record.get("<name>");
                        String login = record.get("<login>");
                        String title = record.get("<title>");
                        String email = record.get("<email>");
                        String role = record.get("<role>");
                        String dept = record.get("<department>");
                        String joinDate = record.get("<joinDate>");
                        String probDate = record.get("<probDate>");
                        String annLeaveEnt = record.get("<leave_entitlement>");
                        String annBal = record.get("<leave_bal>");
                        String annMax = record.get("<leave_max>");
                        String annCF = record.get("<leave_cf>");
                        String med = record.get("<med_taken>");
                        String oil = record.get("<oil_taken>");
                        String unpaid = record.get("<unpaid_taken>");
                        String child = record.get("<child_bal>");

                        TitleDTO titleDto = titleBean.getTitleByName(title);
                        RoleDTO roleDto = accessBean.getRole(role);
                        DeptDTO deptDto = deptBean.getDepartment(dept);
                        //create the user first
                        UserDTO user = new UserDTO();
                        user.setName(name);
                        user.setLogin(login);
                        user.setTitle(titleDto);
                        user.setEmail(email);
                        user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy"));
                        user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy"));
                        //store in user table.
                        userBean.createUser(user);
                        //assign role
                        userBean.assignRole(user, roleDto);
                        //assign dept
                        deptBean.assignEmployee(user, deptDto);

                        //leave ent
                        LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual");
                        LeaveEntDTO annualentDTO = new LeaveEntDTO();
                        annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt));
                        annualentDTO.setBalance(Double.parseDouble(annBal));
                        annualentDTO.setMax(Double.parseDouble(annMax));
                        annualentDTO.setCarriedOver(Double.parseDouble(annCF));
                        annualentDTO.setLeaveType(lvtypeDTO);
                        //assign annual leave
                        annualentDTO.setUser(user);
                        leaveBean.addLeaveEnt(annualentDTO);
                        //medical ent
                        LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave");
                        LeaveEntDTO medentDTO = new LeaveEntDTO();
                        medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med));
                        medentDTO.setCurrent(medTypeDTO.getDays());
                        medentDTO.setUser(user);
                        medentDTO.setLeaveType(medTypeDTO);
                        leaveBean.addLeaveEnt(medentDTO);
                        //oil ent
                        LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu");
                        LeaveEntDTO oilentDTO = new LeaveEntDTO();
                        oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil));
                        oilentDTO.setCurrent(0);
                        oilentDTO.setUser(user);
                        oilentDTO.setLeaveType(oilTypeDTO);
                        leaveBean.addLeaveEnt(oilentDTO);
                        //unpaid
                        LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid");
                        LeaveEntDTO unpaidentDTO = new LeaveEntDTO();
                        unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid));
                        unpaidentDTO.setCurrent(0);
                        unpaidentDTO.setUser(user);
                        unpaidentDTO.setLeaveType(unpaidTypeDTO);
                        leaveBean.addLeaveEnt(unpaidentDTO);
                        //child
                        LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care");
                        double cur = childTypeDTO.getDays();
                        LeaveEntDTO childentDTO = new LeaveEntDTO();
                        childentDTO.setBalance(cur - Double.parseDouble(child));
                        childentDTO.setCurrent(cur);
                        childentDTO.setUser(user);
                        childentDTO.setLeaveType(childTypeDTO);
                        leaveBean.addLeaveEnt(childentDTO);

                    }
                    /*
                    if (stockPrices.size() > 0) {
                       priceDAO.OpenConnection();
                       priceDAO.updateStockPrice(stockPrices);
                    }
                                */

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //priceDAO.CloseConnection();
            RequestDispatcher dispatcher = request.getRequestDispatcher("/employee");
            //request.setAttribute(Constants.TITLE, "Home");
            dispatcher.forward(request, response);
        }
    } else {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp");
        //request.setAttribute(Constants.TITLE, "Home");
        dispatcher.forward(request, response);

    }
}

From source file:com.vodafone.poms.ii.security.loginController.java

public String doLogin() {
    try {/*from  w  w w .j  ava2  s .co m*/
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/login");
        System.out.println("Dispatcher is OK!");

        ServletRequest request = (ServletRequest) context.getRequest();
        if (request == null) {
            System.out.println("Request is NULL");
        }

        ServletResponse response = (ServletResponse) context.getResponse();
        dispatcher.forward(request, response);

        FacesContext.getCurrentInstance().responseComplete();

    } catch (ServletException | IOException ex) {
        Logger.getLogger(loginController.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Caught an error while doing Authentication!");
    }
    return null;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.RDFUploadController.java

public void loadRDF(VitroRequest request, HttpServletResponse response) throws ServletException {
    Map<String, List<FileItem>> fileStreams = request.getFiles();
    String filePath = fileStreams.get("filePath").get(0).getName();
    fileStream = fileStreams.get("filePath").get(0);
    String modelName = request.getParameter("modelName");
    String docLoc = request.getParameter("docLoc");
    String languageStr = request.getParameter("language");
    ModelMaker maker = getModelMaker(request);

    if (modelName == null) {
        request.setAttribute("title", "Load RDF Data");
        request.setAttribute("bodyJsp", LOAD_RDF_DATA_JSP);
    } else {/*from  w  w w . j  a  v  a  2s.c  o  m*/
        RDFService rdfService = getRDFService(request, maker, modelName);
        try {
            doLoadRDFData(modelName, docLoc, filePath, languageStr, rdfService);
        } finally {
            rdfService.close();
        }
        WhichService modelType = getModelType(request);
        showModelList(request, maker, modelType);
    }

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        String errMsg = " could not forward to view.";
        log.error(errMsg, e);
        throw new ServletException(errMsg, e);
    }

}

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

/**
 * The doPost method of the servlet. <br>
 * // w ww  .ja  v  a  2s  .  c  o 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 {

    String forward = "./auditReportTable.jsp";

    try {
        HttpSession httpSession = request.getSession();
        String xml = null;
        StringBuffer filter = new StringBuffer();

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

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

        /*
         * Request and process filter parameters
         */

        String serviceMethodParam = (String) request.getParameter("serviceMethod");
        if (serviceMethodParam != null && !serviceMethodParam.isEmpty()
                && !serviceMethodParam.equalsIgnoreCase("all")) {
            filter.append("&serviceMethod=" + serviceMethodParam);
        }

        String beginTime = "00:00:00";
        String endTime = "00:00:00";
        String time = "";

        String beginDate = (String) request.getParameter("beginDate");
        if (beginDate != null && !beginDate.isEmpty()) {
            time = (String) request.getParameter("beginTime");
            if (time != null && !time.isEmpty())
                beginTime = time;
            if (filter.length() == 0) {
                filter.append("fromTime=" + beginDate + "T" + beginTime);
            } else {
                filter.append("&fromTime=" + beginDate + "T" + beginTime);
            }
        }

        String endDate = (String) request.getParameter("endDate");
        if (endDate != null && !endDate.isEmpty()) {
            time = (String) request.getParameter("endTime");
            if (time != null && !time.isEmpty())
                endTime = time;
            if (filter.length() == 0) {
                filter.append("toTime=" + endDate + "T" + endTime);
            } else {
                filter.append("&toTime=" + endDate + "T" + endTime);
            }
        }

        String debug = (String) request.getParameter("debug");
        if (debug != null && !debug.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("category=" + debug);
            } else {
                filter.append("&category=" + debug);
            }
        }

        String info = (String) request.getParameter("info");
        if (info != null && !info.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("category=" + info);
            } else {
                filter.append("&category=" + info);
            }
        }

        String warn = (String) request.getParameter("warn");
        if (warn != null && !warn.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("category=" + warn);
            } else {
                filter.append("&category=" + warn);
            }
        }

        String error = (String) request.getParameter("error");
        if (error != null && !error.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("category=" + error);
            } else {
                filter.append("&category=" + error);
            }
        }

        String userIdParam = (String) request.getParameter("userId");
        if (userIdParam != null && !userIdParam.isEmpty()) {
            String userParam = "public";
            if (!userIdParam.equalsIgnoreCase(userParam)) {
                userParam = PastaClient.composeDistinguishedName(userIdParam);
            }
            if (filter.length() == 0) {
                filter.append("user=" + userParam);
            } else {
                filter.append("&user=" + userParam);
            }
        }

        String group = (String) request.getParameter("group");
        if (group != null && !group.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("group=" + group);
            } else {
                filter.append("&group=" + group);
            }
        }

        String code = (String) request.getParameter("code");
        if (code != null && !code.isEmpty() && !code.equalsIgnoreCase("all")) {
            if (filter.length() == 0) {
                filter.append("status=" + code);
            } else {
                filter.append("&status=" + code);
            }
        }

        if (limit != null && !limit.isEmpty()) {
            if (filter.length() == 0) {
                filter.append("limit=" + limit);
            } else {
                filter.append("&limit=" + limit);
            }
        }

        String message = null;

        if (uid.equals("public")) {
            message = LOGIN_WARNING;
            forward = "./login.jsp";
        } else {

            logger.info(filter.toString());

            AuditManagerClient auditClient = new AuditManagerClient(uid);
            xml = auditClient.reportByFilter(filter.toString());

            ReportUtility reportUtility = new ReportUtility(xml);
            message = reportUtility.xmlToHtmlTable(cwd + xslpath);
        }

        request.setAttribute("reportMessage", message);

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

}

From source file:filter.ConexaoHibernateFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws ServletException, IOException {
    try {/*www  . ja  v a 2s  .  c o  m*/

        this.sf.getCurrentSession().beginTransaction();
        chain.doFilter(servletRequest, servletResponse);
        this.sf.getCurrentSession().getTransaction().commit();
        this.sf.getCurrentSession().close();
    } catch (Throwable ex) {
        try {
            if (this.sf.getCurrentSession().getTransaction().isActive()) {
                this.sf.getCurrentSession().getTransaction().rollback();
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        throw new ServletException(ex);
    }
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpSession session = request.getSession();

    // recupera o usuario adm logado da sesso
    Object login = session.getAttribute("UsuarioAtual");
    RequestDispatcher dispatcher = null;

    if (!(request.getRequestURI().equals(paginaLogin) || request.getRequestURI().equals(paginaPrimeiroAcesso)
            || request.getRequestURI().equals(paginaRecuperarSenha))) {
        if (login == null) {
            // ento envia para a pagina de acesso invalido
            dispatcher = servletRequest.getRequestDispatcher("loginEntrar.xhtml");
            dispatcher.forward(servletRequest, servletResponse);
        }

    }

}

From source file:eu.eidas.node.APSelectorServlet.java

/**
 * Prepares the citizen to be redirected to the AP.
 * @param request//from   w  w  w. j  a v  a 2s . co  m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        LOG.debug("**** EXECUTE : APSelectorServlet ****");

        APSelectorBean controllerService = (APSelectorBean) getApplicationContext()
                .getBean("springManagedAPSelector");

        validateSession(controllerService);

        // Prevent cookies from being accessed through client-side script.
        setHTTPOnlyHeader(request, response);

        final Map<String, Object> parameters = getHttpRequestParameters(request);

        IPersonalAttributeList attrList = (PersonalAttributeList) request
                .getAttribute(EIDASParameters.ATTRIBUTE_LIST.toString());

        String strAttrList = (String) parameters.get(SpecificParameterNames.STR_ATTR_LIST.toString());
        if (strAttrList == null) {
            strAttrList = (String) request.getAttribute(SpecificParameterNames.STR_ATTR_LIST.toString());
        }

        if (strAttrList != null) {
            LOG.debug("Setting AttributeList...");
            attrList = new PersonalAttributeList();
            attrList.populate(strAttrList);
            validateAttrList(controllerService, attrList);
        }

        if (controllerService.getNumberOfAps() > 0 && !checkAttributes(attrList)) {
            LOG.debug("Build parameter list");

            final String username = (String) controllerService.getSession()
                    .get(EIDASParameters.USERNAME.toString());
            EIDASUtil.validateParameter(APSelectorServlet.class.getCanonicalName(),
                    EIDASParameters.USERNAME.toString(), username);
            parameters.put(EIDASParameters.USERNAME.toString(), username);
            request.setAttribute(EIDASParameters.USERNAME.toString(), username);
            LOG.debug("Build username=" + username);

            if (controllerService.isExternalAP()) {
                LOG.debug("External AP configured");
                request.setAttribute(SpecificParameterNames.CALLBACK_URL.toString(),
                        encodeURL(controllerService.getCallbackURL(), request, response));
                final boolean retVal = controllerService.getSpecificEidasNode().prepareAPRedirect(attrList,
                        parameters, getHttpRequestAttributesHeaders(request), controllerService.getSession());
                if (retVal) {
                    request.setAttribute(EIDASParameters.AP_URL.toString(),
                            controllerService.getSession().get(EIDASParameters.AP_URL.toString()));
                    request.setAttribute(SpecificParameterNames.STR_ATTR_LIST.toString(), attrList.toString());
                    LOG.debug("[execute] external-ap");

                    RequestDispatcher dispatcher = getServletContext()
                            .getRequestDispatcher(response.encodeURL(SpecificViewNames.AP_REDIRECT.toString()));
                    dispatcher.forward(request, response);
                    return;
                }
            } else {
                controllerService.getSpecificEidasNode().getAttributesFromAttributeProviders(attrList,
                        parameters, getHttpRequestAttributesHeaders(request));
            }
        }

        final EIDASAuthnRequest authReq = (EIDASAuthnRequest) controllerService.getSession()
                .get(EIDASParameters.AUTH_REQUEST.toString());
        if (SAMLCore.EIDAS10_SAML_PREFIX.getValue().equalsIgnoreCase(authReq.getMessageFormatName())) {
            for (PersonalAttribute pa : attrList) {
                if (!pa.getValue().isEmpty() && !StringUtils.isEmpty(pa.getValue().get(0))
                        && StringUtils.isEmpty(pa.getStatus())) {
                    pa.setStatus(EIDASStatusCode.STATUS_AVAILABLE.toString());
                }
            }
        }

        if (authReq.getPersonalAttributeList().containsKey(controllerService.getAttribute())
                && controllerService.isSigModuleExists()) {
            final PersonalAttribute attr = authReq.getPersonalAttributeList()
                    .get(controllerService.getAttribute());
            if (!attr.isEmptyValue()) {
                LOG.debug("[execute] external-sig-module");
                final String signedDocValue = attr.getValue().get(0);
                request.setAttribute(SpecificParameterNames.DATA.toString(), signedDocValue);
                attrList.put(attr.getName(), attr);
                request.setAttribute(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
                String dataURL = controllerService.getDataURL() + ";jsessionid=" + request.getSession().getId();
                request.setAttribute(SpecificParameterNames.DATA_URL.toString(), dataURL);
                controllerService.getSession().put(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
                request.setAttribute(SpecificParameterNames.SIG_MODULE_CREATOR_URL.toString(),
                        controllerService.getSigCreatorModuleURL());

                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
                        response.encodeURL(SpecificViewNames.EXTERNAL_SIG_MODULE_REDIRECT.toString()));
                dispatcher.forward(request, response);
                return;

            } else {
                LOG.info("ERROR : [execute] No " + controllerService.getAttribute() + " value found!");
            }
        }

        request.setAttribute(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
        request.setAttribute(SpecificParameterNames.STR_ATTR_LIST.toString(), strAttrList);

        LOG.trace("[execute] internal-ap");
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(response.encodeURL(SpecificViewNames.AP_RESPONSE.toString()));
        dispatcher.forward(request, response);

    } catch (ServletException e) {
        LOG.info("ERROR : ", e.getMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    } catch (IOException e) {
        LOG.info("ERROR : ", e.getMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    } catch (AbstractEIDASException e) {
        LOG.info("ERROR : ", e.getErrorMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    }

}