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:org.apache.myfaces.context.servlet.ServletExternalContextImpl.java

public void dispatch(String requestURI) throws IOException, FacesException {
    RequestDispatcher requestDispatcher = _servletRequest.getRequestDispatcher(requestURI);

    // If there is no dispatcher, send NOT_FOUND
    if (requestDispatcher == null) {
        ((HttpServletResponse) _servletResponse).sendError(HttpServletResponse.SC_NOT_FOUND);

        return;//from   w  w  w. j  a  v a  2  s. c  o m
    }

    try {
        requestDispatcher.forward(_servletRequest, _servletResponse);
    } catch (ServletException e) {
        if (e.getMessage() != null) {
            throw new FacesException(e.getMessage(), e);
        } else {
            throw new FacesException(e);
        }
    }
}

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

public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;//w  w  w  .  j  a va2 s  .c o m
    }

    VitroRequest request = new VitroRequest(req);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    /*for testing*/
    Ontology testMask = new Ontology();
    epo.setBeanClass(Ontology.class);
    epo.setBeanMask(testMask);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    OntologyDao oDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();
    epo.setDataAccessObject(oDao);

    Ontology ontologyForEditing = null;
    if (!epo.getUseRecycledBean()) {
        if (request.getParameter("uri") != null) {
            try {
                ontologyForEditing = oDao.getOntologyByURI(request.getParameter("uri"));
                action = "update";
            } catch (NullPointerException e) {
                log.error("No ontology record found for the namespace " + request.getParameter("uri"));
            }
        } else {
            ontologyForEditing = new Ontology();
        }
        epo.setOriginalBean(ontologyForEditing);
    } else {
        ontologyForEditing = (Ontology) epo.getNewBean();
    }

    //validators
    List<Validator> validatorList = new ArrayList<Validator>();
    validatorList.add(new RequiredFieldValidator());
    validatorList.add(new UrlValidator());
    epo.getValidatorMap().put("URI", validatorList);

    //make a simple mask for the class's id
    Object[] simpleMaskPair = new Object[2];
    simpleMaskPair[0] = "Id";
    simpleMaskPair[1] = Integer.valueOf(ontologyForEditing.getId());
    epo.getSimpleMask().add(simpleMaskPair);

    //set up any listeners

    //make a postinsert pageforwarder that will send us to a new ontology's edit screen
    epo.setPostInsertPageForwarder(new OntologyInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of ontologies
    epo.setPostDeletePageForwarder(new UrlForwarder("listOntologies"));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(oDao.getClass().getDeclaredMethod("getOntologyByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("OntologyRetryController could not find the getOntologyByURI method in the DAO");
    }

    FormObject foo = new FormObject();

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(ontologyForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/ontology_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Ontology Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Ontology");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("OntologyRetryContro" + "ller could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

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

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;//ww  w  .jav a 2 s. c o  m
    }

    String entURI = request.getParameter("uri");
    VitroRequest vreq = (new VitroRequest(request));
    ApplicationBean application = vreq.getAppBean();

    //Individual ent = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    Individual ent = vreq.getUnfilteredAssertionsWebappDaoFactory().getIndividualDao()
            .getIndividualByURI(entURI);
    if (ent == null) {
        try {
            RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
            request.setAttribute("bodyJsp", "/jenaIngest/notfound.jsp");
            request.setAttribute("title", "Individual Not Found");
            request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
                    + application.getThemeDir() + "css/edit.css\"/>");
            rd.forward(request, response);
        } catch (Exception e) {
            log.error("EntityEditController could not forward to view.");
            log.error(e.getMessage());
            log.error(e.getStackTrace());
        }
    }

    Individual inferredEnt = vreq.getUnfilteredWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    if (inferredEnt == null) {
        inferredEnt = new IndividualImpl(entURI);
    }

    request.setAttribute("entity", ent);

    ArrayList<String> results = new ArrayList<String>();
    int colCount = 4;
    results.add("Name");
    results.add("class");
    results.add("display level");
    results.add("edit level");
    results.add("last updated");
    colCount++;
    results.add("URI");
    colCount++;
    results.add("publish level");
    colCount++;

    String rName = null;
    if (ent.getName() != null && ent.getName().length() > 0) {
        rName = ent.getName();
    } else if (ent.getLocalName() != null && ent.getLocalName().length() > 0) {
        rName = ent.getLocalName();
    } else if (ent.isAnonymous()) {
        rName = "[anonymous resource]";
    } else {
        rName = "[resource]";
    }
    results.add(rName);

    String classStr = "";
    List<VClass> classList = inferredEnt.getVClasses(false);
    sortForPickList(classList, vreq);
    if (classList != null) {
        for (Iterator<VClass> classIt = classList.iterator(); classIt.hasNext();) {
            VClass vc = classIt.next();
            String rClassName = "";
            try {
                rClassName = "<a href=\"vclassEdit?uri=" + URLEncoder.encode(vc.getURI(), "UTF-8") + "\">"
                        + vc.getPickListName() + "</a>";
            } catch (Exception e) {
                rClassName = vc.getLocalNameWithPrefix();
            }
            classStr += rClassName;
            if (classIt.hasNext()) {
                classStr += ", ";
            }
        }
    }
    results.add(classStr);

    results.add(ent.getHiddenFromDisplayBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
    results.add(ent.getProhibitedFromUpdateBelowRoleLevel() == null ? "unspecified"
            : ent.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());

    String rModTime = (ent.getModTime() == null) ? "" : publicDateFormat.format(ent.getModTime());
    results.add(rModTime);
    results.add((ent.getURI() == null) ? "[anonymous individual]" : ent.getURI());
    results.add(ent.getHiddenFromPublishBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());
    request.setAttribute("results", results);
    request.setAttribute("columncount", colCount);
    request.setAttribute("suppressquery", "true");

    EditProcessObject epo = super.createEpo(request, FORCE_NEW);
    request.setAttribute("epo", epo);

    FormObject foo = new FormObject();
    HashMap<String, List<Option>> OptionMap = new HashMap<String, List<Option>>();

    List<VClass> types = ent.getVClasses(false);
    sortForPickList(types, vreq);
    request.setAttribute("types", types); // we're displaying all assertions, including indirect types

    try {
        List<Option> externalIdOptionList = new LinkedList<Option>();
        if (ent.getExternalIds() != null) {
            Iterator<DataPropertyStatement> externalIdIt = ent.getExternalIds().iterator();
            while (externalIdIt.hasNext()) {
                DataPropertyStatement eid = externalIdIt.next();
                String multiplexedString = new String(
                        "DatapropURI:" + new String(Base64.encodeBase64(eid.getDatapropURI().getBytes())) + ";"
                                + "Data:" + new String(Base64.encodeBase64(eid.getData().getBytes())));
                externalIdOptionList.add(new Option(multiplexedString, eid.getData()));
            }
        }
        OptionMap.put("externalIds", externalIdOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }

    try {
        OptionMap.put("VClassURI",
                FormUtils.makeOptionListFromBeans(
                        vreq.getUnfilteredWebappDaoFactory().getVClassDao().getAllVclasses(), "URI",
                        "PickListName", ent.getVClassURI(), null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    PropertyInstanceDao piDao = vreq.getUnfilteredWebappDaoFactory().getPropertyInstanceDao();
    // existing property statements
    try {
        List epiOptionList = new LinkedList();
        Collection<PropertyInstance> epiColl = piDao.getExistingProperties(ent.getURI(), null);
        Iterator<PropertyInstance> epiIt = epiColl.iterator();
        while (epiIt.hasNext()) {
            PropertyInstance pi = epiIt.next();
            String multiplexedString = new String("PropertyURI:"
                    + new String(Base64.encodeBase64(pi.getPropertyURI().getBytes())) + ";" + "ObjectEntURI:"
                    + new String(Base64.encodeBase64(pi.getObjectEntURI().getBytes())));
            epiOptionList.add(new Option(multiplexedString, pi.getDomainPublic() + " " + pi.getObjectName()));
        }
        OptionMap.put("ExistingPropertyInstances", epiOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }
    // possible property statements
    try {
        Collection piColl = piDao.getAllPossiblePropInstForIndividual(ent.getURI());
        List piList = new ArrayList();
        piList.addAll(piColl);
        OptionMap.put("PropertyURI", FormUtils.makeOptionListFromBeans(piList, "PropertyURI", "DomainPublic",
                (String) null, (String) null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    foo.setOptionLists(OptionMap);

    epo.setFormObject(foo);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("entityWebapp", ent);
    request.setAttribute("bodyJsp", "/templates/edit/specific/ents_edit.jsp");
    request.setAttribute("title", "Individual Control Panel");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + application.getThemeDir()
            + "css/edit.css\"/>");
    request.setAttribute("scripts", "/templates/edit/specific/ents_edit_head.jsp");

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityEditController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

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

/**
 * The doPost method of the servlet. <br>
 * // ww  w  .  j  a va2  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 {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ArrayList<String> documentURLs = null;
    File emlFile = null;
    String emlTextArea = null;
    Harvester harvester = null;
    String harvestId = null;
    String harvestListURL = null;
    String harvestReportId = null;
    boolean isDesktopUpload = false;
    boolean isEvaluate = false;
    String uid = (String) httpSession.getAttribute("uid");
    String urlTextArea = null;
    String warningMessage = "";

    try {
        if (uid == null) {
            throw new PastaAuthenticationException(LOGIN_WARNING);
        } else {
            /*
             * The "metadataSource" request parameter can have a value of
             * "emlText", "emlFile", "urlList", "harvestList", or
             * "desktopHarvester". It is set as a hidden input field in 
             * each of the harvester forms.
             */
            String metadataSource = request.getParameter("metadataSource");

            /*
             * "mode" can have a value of "evaluate" or "upgrade". It is set
             * as the value of the submit button in each of the harvester
             * forms.
             */
            String mode = request.getParameter("submit");
            if ((mode != null) && (mode.equalsIgnoreCase("evaluate"))) {
                isEvaluate = true;
            }

            if ((metadataSource != null) && (!metadataSource.equals("desktopHarvester"))) {
                harvestId = generateHarvestId();
                if (isEvaluate) {
                    harvestReportId = uid + "-evaluate-" + harvestId;
                } else {
                    harvestReportId = uid + "-upload-" + harvestId;
                }
            }

            if (metadataSource != null) {
                if (metadataSource.equals("emlText")) {
                    emlTextArea = request.getParameter("emlTextArea");
                    if (emlTextArea == null || emlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the text of an EML document into the text area.</p>";
                    }
                } else if (metadataSource.equals("emlFile")) {
                    Collection<Part> parts = request.getParts();
                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save EML file to disk
                            emlFile = processUploadedFile(part);
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.equals("desktopUpload")
                                        && fieldValue.equalsIgnoreCase("1")) {
                                    isDesktopUpload = true;
                                }
                            }
                        }
                    }
                } else if (metadataSource.equals("urlList")) {
                    urlTextArea = request.getParameter("urlTextArea");
                    if (urlTextArea == null || urlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter one or more EML document URLs into the text area.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromTextArea(urlTextArea);
                        warningMessage = CHECK_BACK_LATER;
                    }
                } else if (metadataSource.equals("harvestList")) {
                    harvestListURL = request.getParameter("harvestListURL");
                    if (harvestListURL == null || harvestListURL.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the URL to a Metacat Harvest List.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromHarvestList(harvestListURL);
                        warningMessage = CHECK_BACK_LATER;
                    }
                }
                /*
                 * If the metadata source is "desktopHarvester", we already have the
                 * EML file stored in a session attribute. Now we need to retrieve
                 * the data files from the brower's form fields and write the
                 * data files to a URL accessible location.
                 */
                else if (metadataSource.equals("desktopHarvester")) {
                    emlFile = (File) httpSession.getAttribute("emlFile");
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    harvestReportId = (String) httpSession.getAttribute("harvestReportId");
                    String dataPath = servletContext.getRealPath(DESKTOP_DATA_DIR);
                    String harvestPath = String.format("%s/%s", dataPath, harvestReportId);

                    Collection<Part> parts = request.getParts();
                    String objectName = null;
                    Part filePart = null;

                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save data file to disk
                            //processDataFile(part, harvestPath);
                            filePart = part;
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.startsWith("object-name-")) {
                                    objectName = fieldValue;
                                }
                            }
                        }

                        if (filePart != null && objectName != null) {
                            processDataFile(filePart, harvestPath, objectName);
                            objectName = null;
                            filePart = null;
                        }

                    }

                    emlFile = transformDesktopEML(harvestPath, emlFile, harvestReportId, entityList);
                }
            } else {
                throw new IllegalStateException("No value specified for request parameter 'metadataSource'");
            }

            if (harvester == null) {
                harvester = new Harvester(harvesterPath, harvestReportId, uid, isEvaluate);
            }

            if (emlTextArea != null) {
                harvester.processSingleDocument(emlTextArea);
            } else if (emlFile != null) {
                if (isDesktopUpload) {
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    httpSession.setAttribute("entityList", entityList);
                    httpSession.setAttribute("emlFile", emlFile);
                    httpSession.setAttribute("harvestReportId", harvestReportId);
                    httpSession.setAttribute("isEvaluate", new Boolean(isEvaluate));
                } else {
                    harvester.processSingleDocument(emlFile);
                }
            } else if (documentURLs != null) {
                harvester.setDocumentURLs(documentURLs);
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.execute(harvester);
                executorService.shutdown();
            }
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("message", warningMessage);

    /*
     * If we have a new reportId, and either there is no warning message or
     * it's the "Check back later" message, set the harvestReportID session
     * attribute to the new reportId value.
     */
    if (harvestReportId != null && harvestReportId.length() > 0
            && (warningMessage.length() == 0 || warningMessage.equals(CHECK_BACK_LATER))) {
        httpSession.setAttribute("harvestReportID", harvestReportId);
    }

    if (isDesktopUpload) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./desktopHarvester.jsp");
        requestDispatcher.forward(request, response);
    } else if (warningMessage.length() == 0) {
        response.sendRedirect("./harvestReport.jsp");
    } else {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./harvester.jsp");
        requestDispatcher.forward(request, response);
    }

}

From source file:org.agnitas.web.MailingStatAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*from  w w w .  j a va  2  s. c  o m*/
 *
 * @param form
 * @param req
 * @param res
 * @param mapping The ActionMapping used to select this instance
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 * @return destination
 */

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws IOException, ServletException {

    MailingStatForm aForm = null;
    ActionMessages errors = new ActionMessages();
    ActionForward destination = null;

    if (!this.checkLogon(req))
        return mapping.findForward("logon");

    if (form != null) {
        aForm = (MailingStatForm) form;
    } else {
        aForm = new MailingStatForm();
    }

    AgnUtils.logger().info("Action: " + aForm.getAction());

    if (!allowed("stats.mailing", req)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
        saveErrors(req, errors);
        return null;
    }

    try {
        switch (aForm.getAction()) {

        case ACTION_LIST:
            destination = mapping.findForward("list");
            break;

        case ACTION_MAILINGSTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("mailing_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    // display splash in browser
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadMailingStat(aForm, req);

                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }

            }
            break;

        case ACTION_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("mailing_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_OPENEDSTAT_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("opened_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_BOUNCESTAT_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("bounce_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_WEEKSTAT:
            loadWeekStat(aForm, req);
            destination = mapping.findForward("week_stat");
            break;

        case ACTION_DAYSTAT:
            loadDayStat(aForm, req);
            destination = mapping.findForward("day_stat");
            break;

        case ACTION_CLEAN_QUESTION:
            destination = mapping.findForward("clean_question");
            break;

        case ACTION_CLEAN:
            cleanAdminClicks(aForm, req);
            loadMailingStat(aForm, req);
            destination = mapping.findForward("mailing_stat");
            break;

        case ACTION_OPENEDSTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("opened_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadOpenedStat(aForm, req);
                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }
            }
            break;

        case ACTION_BOUNCESTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("bounce_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadBounceStat(aForm, req);
                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }
            }
            break;
        case ACTION_BOUNCE:
            destination = mapping.findForward("bounce");
            break;

        case ACTION_OPEN_TIME:
            loadOpenWeekStat(aForm, req);
            destination = mapping.findForward("open_week");
            break;

        case ACTION_OPEN_DAYSTAT:
            loadOpenDayStat(aForm, req);
            destination = mapping.findForward("open_day");
            break;

        default:
            aForm.setAction(MailingStatAction.ACTION_MAILINGSTAT);
            loadMailingStat(aForm, req);
            destination = mapping.findForward("list");
        }
    } catch (Exception e) {
        AgnUtils.logger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
    }

    if (destination != null && "list".equals(destination.getName())) {
        try {
            req.setAttribute("mailingStatlist", getMailingStats(req));
            setNumberOfRows(req, aForm);
        } catch (Exception e) {
            AgnUtils.logger().error("mailingStatlist: " + e + "\n" + AgnUtils.getStackTrace(e));
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(req, errors);
    }

    return destination;
}

From source file:com.alfaariss.oa.authentication.password.PasswordAuthenticationMethod.java

private void forwardUser(HttpServletRequest request, HttpServletResponse response, ISession session, int iTries,
        boolean bRetries, List<Enum> warnings) throws OAException {
    try {// w  ww.j ava2 s .co m
        if (iTries == 1 && _iAllowedTries != 1) {
            warnings.add(Warnings.ONE_RETRY_LEFT);
        }
        /* 20110304;dopey fix: set session instead of session.getId() into ID_NAME */
        request.setAttribute(ISession.ID_NAME, session);
        request.setAttribute(ISession.LOCALE_NAME, session.getLocale());
        request.setAttribute(HASCAPTCHA, _bCaptchaEnabled);

        if (bRetries) {
            // Only decrease retries if error is an attempt
            iTries--;
        }
        //Set retries
        ISessionAttributes oAttributes = session.getAttributes();
        oAttributes.put(PasswordAuthenticationMethod.class, _sMethodID + RETRIES_ATTRIBUTE_NAME,
                Integer.valueOf(iTries));
        session.persist();

        _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(),
                UserEvent.AUTHN_METHOD_IN_PROGRESS, this, warnings.toString()));

        request.setAttribute(DetailedUserException.DETAILS_NAME, warnings);
        request.setAttribute(AUTHN_METHOD_ATTRIBUTE_NAME, _sFriendlyName);
        request.setAttribute(Server.SERVER_ATTRIBUTE_NAME, _oEngine.getServer());
        IUser oUser = session.getUser();
        if (oUser != null) {
            request.setAttribute(USERID_ATTRIBUTE_NAME, oUser.getID());
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(_sTemplate);

        if (dispatcher != null) {
            dispatcher.forward(request, response);
        }
    } catch (IOException e) {
        _logger.warn("IO exception occured while forwarding", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (ServletException e) {
        _logger.warn("Servlet exception occured while forwarding", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.auraframework.http.AuraTestFilter.java

private String captureResponse(ServletRequest req, ServletResponse res, String testName, String uri)
        throws ServletException, IOException {
    CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper((HttpServletResponse) res) {
        @Override//w  w w  . ja  v  a  2  s  .  c o m
        public void sendRedirect(String location) throws IOException {
            // If the response is redirected after this filter, we want to
            // handle the redirect, so we need to set the jstestrun
            // parameter to make sure we can see it on the next request.
            Matcher test = jstestToRunPattern.matcher(location);
            if (test.find()) {
                location = test.replaceAll(testName);
            } else {
                location = location + (location.indexOf('?') < 0 ? "?" : "&") + jstestToRun.name + "="
                        + testName;
            }
            super.sendRedirect(location);
        }
    };
    RequestDispatcher dispatcher = req.getServletContext().getContext(uri).getRequestDispatcher(uri);
    if (dispatcher == null) {
        return null;
    }
    dispatcher.forward(req, responseWrapper);
    if (responseWrapper.getRedirectUrl() != null) {
        return null;
    }
    return responseWrapper.getCapturedResponseString();
}

From source file:com.alfaariss.oa.authentication.identifying.IdentifyingAuthenticationMethod.java

private void forwardUser(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
        List<Enum> warnings) throws OAException {
    try {//w ww. j  a  v  a 2s .  c om
        oRequest.setAttribute(ISession.ID_NAME, oSession.getId());
        oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale());

        if (warnings != null) {
            oRequest.setAttribute(DetailedUserException.DETAILS_NAME, warnings);
        }

        oRequest.setAttribute(IWebAuthenticationMethod.AUTHN_METHOD_ATTRIBUTE_NAME, _sFriendlyName);
        oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, _oaEngine.getServer());

        RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(_sTemplatePath);
        if (oDispatcher == null) {
            _logger.warn("There is no request dispatcher supported with name: " + _sTemplatePath);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        _logger.debug("Forward user to: " + _sTemplatePath);

        oSession.persist();

        oDispatcher.forward(oRequest, oResponse);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        if (oSession != null)
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, null));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                    oRequest.getRemoteAddr(), null, this, null));

        _logger.fatal("Internal error during forward", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:hudson.model.Descriptor.java

/**
 * Serves <tt>help.html</tt> from the resource of {@link #clazz}.
 *//*from w  w  w. j  a  v  a 2  s .  com*/
public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    String path = req.getRestOfPath();
    if (path.contains(".."))
        throw new ServletException("Illegal path: " + path);

    path = path.replace('/', '-');

    for (Class c = clazz; c != null; c = c.getSuperclass()) {
        RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help" + path);
        if (rd != null) {// Jelly-generated help page
            rd.forward(req, rsp);
            return;
        }

        InputStream in = getHelpStream(c, path);
        if (in != null) {
            // TODO: generalize macro expansion and perhaps even support JEXL
            rsp.setContentType("text/html;charset=UTF-8");
            String literal = IOUtils.toString(in, "UTF-8");
            rsp.getWriter().println(
                    Util.replaceMacro(literal, Collections.singletonMap("rootURL", req.getContextPath())));
            in.close();
            return;
        }
    }
    rsp.sendError(SC_NOT_FOUND);
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;/*w w  w .  jav  a2s . c o m*/
    }

    VitroRequest vreq = new VitroRequest(request);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);
    epo.setBeanClass(PropertyInstanceIface.class);
    Class[] classarray = { PropertyInstanceIface.class };
    try {
        epo.setInsertMethod(PropertyInstanceDao.class.getMethod("insertProp", classarray));
        epo.setUpdateMethod(epo.getInsertMethod());
    } catch (NoSuchMethodException nsme) {
        log.error("Unable to find " + PropertyInstanceDao.class.getName() + ".insertProp("
                + PropertyInstanceIface.class.getName() + ")");
    }

    try {
        epo.setDeleteMethod(PropertyInstanceDao.class.getMethod("deletePropertyInstance", classarray));
    } catch (NoSuchMethodException nsme) {
        log.error("Unable to find " + PropertyInstanceDao.class.getName() + ".deletePropertyInstance("
                + PropertyInstanceIface.class.getName() + ")");
    }

    String action = "insert";

    PropertyInstanceDao piDao = vreq.getUnfilteredWebappDaoFactory().getPropertyInstanceDao();
    epo.setDataAccessObject(piDao);
    ObjectPropertyDao pDao = vreq.getUnfilteredWebappDaoFactory().getObjectPropertyDao();
    IndividualDao eDao = vreq.getUnfilteredWebappDaoFactory().getIndividualDao();
    VClassDao vcDao = vreq.getUnfilteredWebappDaoFactory().getVClassDao();

    PropertyInstance objectForEditing = null;
    if (!epo.getUseRecycledBean()) {
        objectForEditing = new PropertyInstance();
        populateBeanFromParams(objectForEditing, vreq);
        if (vreq.getParameter(MULTIPLEXED_PARAMETER_NAME) != null) {
            action = "update";
        }
        epo.setOriginalBean(objectForEditing);
    } else {
        objectForEditing = (PropertyInstance) epo.getNewBean();
    }

    //set up any listeners
    //        List changeListenerList = new LinkedList();
    //        changeListenerList.add(new SearchReindexer());
    //        epo.setChangeListenerList(changeListenerList);

    FormObject foo = new FormObject();
    ObjectProperty p = pDao.getObjectPropertyByURI(objectForEditing.getPropertyURI());
    if (p != null) {
        foo.getValues().put("Prop", p.getDomainPublic());
    } else {
        foo.getValues().put("Prop", "The property must be specified.");
    }
    HashMap optionMap = new HashMap();
    String domainEntityName = "";
    String rangeEntityName = "";
    Individual domainEntity = eDao.getIndividualByURI(objectForEditing.getSubjectEntURI());
    List domainOptionList = new LinkedList();
    Individual subjectInd = eDao.getIndividualByURI(objectForEditing.getSubjectEntURI());
    if (subjectInd != null) {
        Option subjOpt = new Option(subjectInd.getURI(), subjectInd.getName());
    }
    domainOptionList.add(new Option(domainEntity.getURI(), domainEntity.getName(), true));
    optionMap.put("SubjectEntURI", domainOptionList);

    // TODO : handle list of VClasses
    List<VClass> possibleClasses = vcDao.getVClassesForProperty(domainEntity.getVClassURI(),
            objectForEditing.getPropertyURI());
    Iterator<VClass> possIt = possibleClasses.iterator();
    HashSet<Individual> possIndSet = new HashSet<Individual>();
    while (possIt.hasNext()) {
        VClass possClass = possIt.next();
        List<Individual> possibleIndividuals = eDao.getIndividualsByVClass(possClass);
        possIndSet.addAll(possibleIndividuals);
    }
    List<Individual> indList = new LinkedList();
    indList.addAll(possIndSet);
    sortForPickList(indList, vreq);
    List objectEntOptionList = new LinkedList();
    Iterator<Individual> indIt = indList.iterator();
    while (indIt.hasNext()) {
        Individual objInd = indIt.next();
        Option objIndOpt = new Option(objInd.getURI(), objInd.getName());
        if (objectForEditing.getObjectEntURI() != null
                && objectForEditing.getObjectEntURI().equals(objInd.getURI())) {
            objIndOpt.setSelected(true);
        }
        objectEntOptionList.add(objIndOpt);
    }
    if (objectEntOptionList.size() == 0) {
        objectEntOptionList
                .add(new Option("", "There are no individuals yet defined that could fill this role."));
    }
    optionMap.put("ObjectEntURI", objectEntOptionList);

    foo.setOptionLists(optionMap);
    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(objectForEditing, action, foo);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/ents2ents_retry_domainSide.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Object Property Instance Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "ObjectPropertyStatement");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("ObjectPropertyStatementRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}