Example usage for javax.servlet ServletContext getRequestDispatcher

List of usage examples for javax.servlet ServletContext getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from   ww w . j  ava 2s .  co  m
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        sc.setAttribute("type", null);
        sc.setAttribute("showSql", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from w  ww . j  a va 2  s. c o  m
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        //sc.setAttribute("sql", null);
        sc.setAttribute("type", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

@Override
protected DecoratorSelector initDecoratorSelector(SiteMeshWebAppContext webAppContext) {
    // TODO: Remove heavy coupling on horrible SM2 Factory
    final Factory factory = Factory.getInstance(new Config(filterConfig));
    factory.refresh();//from  w  w  w.ja  v  a 2  s  .  co  m
    return new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper()) {
        @Override
        public Decorator selectDecorator(Content content, SiteMeshContext context) {
            SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context;
            final com.opensymphony.module.sitemesh.Decorator decorator = factory.getDecoratorMapper()
                    .getDecorator(webAppContext.getRequest(), content2htmlPage(content));
            if (decorator == null || decorator.getPage() == null) {
                return new GrailsNoDecorator();
            } else {
                return new OldDecorator2NewDecorator(decorator) {
                    @Override
                    protected void render(Content content, HttpServletRequest request,
                            HttpServletResponse response, ServletContext servletContext,
                            SiteMeshWebAppContext webAppContext) throws IOException, ServletException {

                        HTMLPage htmlPage = content2htmlPage(content);
                        request.setAttribute(PAGE, htmlPage);

                        // see if the URI path (webapp) is set
                        if (decorator.getURIPath() != null) {
                            // in a security conscious environment, the servlet container
                            // may return null for a given URL
                            if (servletContext.getContext(decorator.getURIPath()) != null) {
                                servletContext = servletContext.getContext(decorator.getURIPath());
                            }
                        }
                        // get the dispatcher for the decorator
                        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(decorator.getPage());
                        if (response.isCommitted()) {
                            dispatcher.include(request, response);
                        } else {
                            dispatcher.forward(request, response);
                        }

                        request.removeAttribute(PAGE);
                    }

                };
            }
        }
    };
}

From source file:com.ikon.servlet.admin.LanguageServlet.java

/**
 * Translate language// w ww  . j  av  a  2 s  . c o m
 */
private void translate(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("translate({}, {}, {})", new Object[] { userId, request, response });

    if (WebUtils.getBoolean(request, "persist")) {
        Set<Translation> newTranslations = new HashSet<Translation>();
        Language langBase = LanguageDAO.findByPk(Language.DEFAULT);
        Language lang = LanguageDAO.findByPk(request.getParameter("lg_id"));

        for (Translation translation : langBase.getTranslations()) {
            String text = request.getParameter(translation.getTranslationId().getKey());

            if (text != null && !text.equals("")) {
                Translation newTranslation = new Translation();
                newTranslation.getTranslationId().setModule(translation.getTranslationId().getModule());
                newTranslation.getTranslationId().setKey(translation.getTranslationId().getKey());
                newTranslation.getTranslationId().setLanguage(lang.getId());
                newTranslation.setText(text);
                newTranslations.add(newTranslation);
            }
        }

        lang.setTranslations(newTranslations);
        LanguageDAO.update(lang);
    } else {
        ServletContext sc = getServletContext();
        String lgId = WebUtils.getString(request, "lg_id");
        Language langToTranslate = LanguageDAO.findByPk(lgId);
        Map<String, String> translations = new HashMap<String, String>();

        for (Translation translation : langToTranslate.getTranslations()) {
            translations.put(translation.getTranslationId().getKey(), translation.getText());
        }

        sc.setAttribute("action", WebUtils.getString(request, "action"));
        sc.setAttribute("persist", true);
        sc.setAttribute("lg_id", lgId);
        sc.setAttribute("langToTranslateName", langToTranslate.getName());
        sc.setAttribute("translations", translations);
        sc.setAttribute("langBase", LanguageDAO.findByPk(Language.DEFAULT)); // English always it'll be used as a translations base
        sc.getRequestDispatcher("/admin/translation_edit.jsp").forward(request, response);
    }

    log.debug("translate: void");
}

From source file:org.alfresco.web.app.Application.java

/**
 * Handles error conditions detected by servlets.
 * /*from   www. j a v a  2 s  .  c o m*/
 * @param servletContext
 *           The servlet context
 * @param request
 *           The HTTP request
 * @param response
 *           The HTTP response
 * @param messageKey
 *           the resource bundle key for the error mesage
 * @param statusCode
 *           the status code to set on the response
 * @param logger
 *           The logger
 * @throws IOException
 *            Signals that an I/O exception has occurred.
 * @throws ServletException
 *            the servlet exception
 */
public static void handleSystemError(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, String messageKey, int statusCode, Log logger)
        throws IOException, ServletException {
    // get the error bean from the session and set the error that occurred.
    HttpSession session = request.getSession();
    ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME);
    if (errorBean == null) {
        errorBean = new ErrorBean();
        session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean);
    }
    errorBean.setErrorMessageKey(messageKey);
    errorBean.setReturnPage(null);

    // try and find the configured error page
    boolean errorShown = false;
    String errorPage = getErrorPage(servletContext);

    if (errorPage != null) {
        if (logger.isDebugEnabled())
            logger.debug("An error has occurred, forwarding to error page: " + errorPage);

        if (!response.isCommitted()) {
            errorShown = true;
            response.reset();
            response.setStatus(statusCode);
            response.setContentType(MimetypeMap.MIMETYPE_HTML);
            response.setCharacterEncoding("utf-8");
            servletContext.getRequestDispatcher(errorPage).include(request, response);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Response is already committed, re-throwing error");
        }
    } else {
        if (logger.isDebugEnabled())
            logger.debug("No error page defined, re-throwing error");
    }

    // if we could not show the error page for whatever reason, re-throw the error
    if (!errorShown) {
        throw new ServletException(getMessage(session, messageKey));
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }/*from w w w .j  ava2  s  .c  o m*/

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}

From source file:com.openkm.servlet.admin.JcrRepositoryViewServlet.java

/**
 * Edit property//from   w  ww  .  j  a v  a2s.c  o m
 */
private void edit(Session session, String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException {
    log.debug("edit({}, {}, {}, {})", new Object[] { session, path, request, response });
    String property = WebUtils.getString(request, "property");
    ServletContext sc = getServletContext();
    Node node = session.getRootNode().getNode(path.substring(1));
    Property prop = node.getProperty(property);
    boolean multiple = false;
    String value;

    if (prop.getDefinition().isMultiple()) {
        value = toString(prop.getValues(), "\n");
        multiple = true;
    } else {
        value = prop.getValue().getString();
    }

    // Activity log
    UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_EDIT", node.getUUID(), path,
            property + ", " + value);

    sc.setAttribute("node", node);
    sc.setAttribute("property", prop);
    sc.setAttribute("multiple", multiple || prop.getName().equals(Scripting.SCRIPT_CODE));
    sc.setAttribute("value", value);
    sc.getRequestDispatcher("/admin/jcr_repository_edit.jsp").forward(request, response);
    log.debug("edit: void");
}

From source file:com.ikon.servlet.admin.RepositoryViewServlet.java

/**
 * Edit property/*w ww  .  j  a  v a 2  s  . c  o  m*/
 */
private void edit(Session session, String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException {
    log.debug("edit({}, {}, {}, {})", new Object[] { session, path, request, response });
    String property = WebUtils.getString(request, "property");
    ServletContext sc = getServletContext();
    Node node = session.getRootNode().getNode(path.substring(1));
    Property prop = node.getProperty(property);
    boolean multiple = false;
    String value;

    if (prop.getDefinition().isMultiple()) {
        value = toString(prop.getValues(), "\n");
        multiple = true;
    } else {
        value = prop.getValue().getString();
    }

    // Activity log
    UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_EDIT", node.getUUID(), path,
            property + ", " + value);

    sc.setAttribute("node", node);
    sc.setAttribute("property", prop);
    sc.setAttribute("multiple", multiple || prop.getName().equals(Scripting.SCRIPT_CODE));
    sc.setAttribute("value", value);
    sc.getRequestDispatcher("/admin/repository_edit.jsp").forward(request, response);
    log.debug("edit: void");
}

From source file:com.ikon.servlet.PasswordResetServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String username = WebUtils.getString(request, "username");
    ServletContext sc = getServletContext();
    User usr = null;/*from   www  . j  a va 2s  . c  o  m*/

    try {
        usr = AuthDAO.findUserByPk(username);
    } catch (DatabaseException e) {
        log.error(getServletName() + " User '" + username + "' not found");
    }

    if (usr != null) {
        try {
            String password = RandomStringUtils.randomAlphanumeric(8);
            AuthDAO.updateUserPassword(username, password);
            MailUtils.sendMessage(usr.getEmail(), usr.getEmail(), "Password reset", "Your new password is: "
                    + password + "<br/>"
                    + "To change it log in and then go to 'Tools' > 'Preferences' > 'User Configuration'.");
            sc.setAttribute("resetOk", usr.getEmail());
            response.sendRedirect("password_reset.jsp");
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            sc.setAttribute("resetFailed", "Failed to send the new password by email");
            response.sendRedirect("password_reset.jsp");
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
            sc.setAttribute("resetFailed", "Failed reset the user password");
            response.sendRedirect("password_reset.jsp");
        }
    } else {
        sc.setAttribute("resetFailed", "Invalid user name provided");
        sc.getRequestDispatcher("/password_reset.jsp").forward(request, response);
    }
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

/**
 * Import into database/*from   ww w  . j ava  2s .c o  m*/
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    log.debug("executeUpdate({}, {}, {})", new Object[] { session, request, response });
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();
    WorkerUpdate worker = new WorkerUpdate();
    worker.setData(data);
    session.doWork(worker);

    GlobalResult gr = new GlobalResult();
    gr.setColumns(null);
    gr.setResults(null);
    gr.setSql(null);
    gr.setRows(worker.getRows());
    gr.setErrors(worker.getErrors());
    globalResults.add(gr);

    sc.setAttribute("qs", null);
    sc.setAttribute("type", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);

    log.debug("executeUpdate: void");
}