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.StampServlet.java

/**
 * List image stamp//w  ww  .  j a  v  a  2 s  .c om
 */
private void imageList(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("imageList({}, {}, {})", new Object[] { session, request, response });
    ServletContext sc = getServletContext();
    sc.setAttribute("stamps", StampImageDAO.findAll());
    sc.getRequestDispatcher("/admin/stamp_image_list.jsp").forward(request, response);
    log.debug("imageList: void");
}

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

/**
 * results/*from  ww  w .  j av a  2  s . c om*/
 */
private void results(String userId, HttpServletRequest request, HttpServletResponse response, String action,
        Map<String, String> results, long omId) throws DatabaseException, ServletException, IOException {
    ServletContext sc = getServletContext();
    sc.setAttribute("action", action);
    sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
    sc.setAttribute("results", results);
    sc.getRequestDispatcher("/admin/omr_check.jsp").forward(request, response);
    log.debug("check: void");
}

From source file:org.apache.nifi.web.ContentViewerController.java

/**
 * Gets the content and defers to registered viewers to generate the markup.
 *
 * @param request servlet request/*from www  .j  av  a2 s . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest;
    try {
        contentRequest = getContentRequest(request);
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to interpret content request.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    if (contentRequest.getDataUri() == null) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "The data reference must be specified.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
        downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to find the specified content");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final AccessDeniedException ade) {
        request.setAttribute("title", "Access Denied");
        request.setAttribute("messages",
                "Unable to approve access to the specified content: " + ade.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "An unexpected error has occurred: " + e.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
        mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
        displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Invalid display mode: " + mode);

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // buffer the content to support resetting in case we need to detect the content type or char encoding
    try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
        final String mimeType;
        final String normalizedMimeType;

        // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
        // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
        if (downloadableContent.getType() == null || StringUtils
                .startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
            // attempt to detect the content stream if we don't know what it is ()
            final DefaultDetector detector = new DefaultDetector();

            // create the stream for tika to process, buffered to support reseting
            final TikaInputStream tikaStream = TikaInputStream.get(bis);

            // provide a hint based on the filename
            final Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

            // Get mime type
            final MediaType mediatype = detector.detect(tikaStream, metadata);
            mimeType = mediatype.toString();
        } else {
            mimeType = downloadableContent.getType();
        }

        // Extract only mime type and subtype from content type (anything after the first ; are parameters)
        // Lowercase so subsequent code does not need to implement case insensitivity
        normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase();

        // add attributes needed for the header
        request.setAttribute("filename", downloadableContent.getFilename());
        request.setAttribute("contentType", mimeType);

        // generate the header
        request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

        // remove the attributes needed for the header
        request.removeAttribute("filename");
        request.removeAttribute("contentType");

        // generate the markup for the content based on the display mode
        if (DisplayMode.Hex.equals(displayMode)) {
            final byte[] buffer = new byte[BUFFER_LENGTH];
            final int read = StreamUtils.fillBuffer(bis, buffer, false);

            // trim the byte array if necessary
            byte[] bytes = buffer;
            if (read != buffer.length) {
                bytes = new byte[read];
                System.arraycopy(buffer, 0, bytes, 0, read);
            }

            // convert bytes into the base 64 bytes
            final String base64 = Base64.encodeBase64String(bytes);

            // defer to the jsp
            request.setAttribute("content", base64);
            request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
        } else {
            // lookup a viewer for the content
            final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);

            // handle no viewer for content type
            if (contentViewerUri == null) {
                request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
            } else {
                // create a request attribute for accessing the content
                request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
                    @Override
                    public InputStream getContentStream() {
                        return bis;
                    }

                    @Override
                    public String getContent() throws IOException {
                        // detect the charset
                        final CharsetDetector detector = new CharsetDetector();
                        detector.setText(bis);
                        detector.enableInputFilter(true);
                        final CharsetMatch match = detector.detect();

                        // ensure we were able to detect the charset
                        if (match == null) {
                            throw new IOException("Unable to detect character encoding.");
                        }

                        // convert the stream using the detected charset
                        return IOUtils.toString(bis, match.getName());
                    }

                    @Override
                    public ViewableContent.DisplayMode getDisplayMode() {
                        return displayMode;
                    }

                    @Override
                    public String getFileName() {
                        return downloadableContent.getFilename();
                    }

                    @Override
                    public String getContentType() {
                        return normalizedMimeType;
                    }

                    @Override
                    public String getRawContentType() {
                        return mimeType;
                    }
                });

                try {
                    // generate the content
                    final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
                    viewerContext.getRequestDispatcher("/view-content").include(request, response);
                } catch (final Exception e) {
                    String message = e.getMessage() != null ? e.getMessage() : e.toString();
                    message = "Unable to generate view of data: " + message;

                    // log the error
                    logger.error(message);
                    if (logger.isDebugEnabled()) {
                        logger.error(StringUtils.EMPTY, e);
                    }

                    // populate the request attributes
                    request.setAttribute("title", "Error");
                    request.setAttribute("messages", message);

                    // forward to the error page
                    final ServletContext viewerContext = servletContext.getContext("/nifi");
                    viewerContext.getRequestDispatcher("/message").forward(request, response);
                    return;
                }

                // remove the request attribute
                request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
            }
        }

        // generate footer
        request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*from  w  w  w.  j a v a 2  s . c  o  m*/
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

/**
 * List languages/*from  ww  w.  j  a  v  a2s.  co m*/
 * 
 * Translations reference is english
 */
private void list(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    sc.setAttribute("langs", LanguageDAO.findAll());
    sc.setAttribute("max", LanguageDAO.findByPk(Language.DEFAULT).getTranslations().size());
    sc.getRequestDispatcher("/admin/language_list.jsp").forward(request, response);
    log.debug("list: void");
}

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

/**
 * Create language/*w  w  w.j av  a2s  . c  o  m*/
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("edit({}, {}, {})", new Object[] { userId, request, response });

    ServletContext sc = getServletContext();
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("persist", true);
    sc.setAttribute("lg", null);
    sc.getRequestDispatcher("/admin/language_edit.jsp").forward(request, response);

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

From source file:servlet.login.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www .jav  a  2s.  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, ClassNotFoundException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> Desarrollo</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("</body>");
        out.println("</html>");

        String U, P;

        U = request.getParameter("email");
        P = DigestUtils.sha1Hex(request.getParameter("pass"));

        DAO_usuario consultar = new DAO_usuario();
        Conexion con = new Conexion();
        if (!con.conectar()) {
            response.setContentType("text/html");

            out.println("<script type=\"text/javascript\">");
            out.println("alert('[ERROR] Al conectar');");

            out.println("</script>");

            out.println("<script type=\"text/javascript\">");
            out.println("window.location=\"iniciar_sesion.jsp\";");

            out.println("</script>");

        } else {

            if (!consultar.Usuario_Correcto(U, P)) {
                response.setContentType("text/html");
                out.println("<script type=\"text/javascript\">");
                out.println("alert('[ERROR] Al iniciar sesion.');");

                out.println("</script>");

                out.println("<script type=\"text/javascript\">");
                out.println("window.location=\"iniciar_sesion.jsp\";");

                out.println("</script>");

            } else {

                /*
                 ResultSet usuario;
                         
                 usuario =  consultar.Select_Usuario(U, P);
                         
                 String sexo,nickname;
                 sexo = usuario.getString("sexo");
                 nickname = usuario.getString("usuario");
                 int tipo_usuario = usuario.getInt("tipo_usuario");
                 */

                HttpSession mysesion = request.getSession();
                ServletContext ctx = getServletContext();

                mysesion.setAttribute("U", U);
                mysesion.setAttribute("P", P);
                /*
                mysesion.setAttribute("sexo",sexo);
                mysesion.setAttribute("tipo_usuario",tipo_usuario);
                mysesion.setAttribute("nickname",nickname);
                */
                RequestDispatcher dispatcher = ctx.getRequestDispatcher("/desarrollo.jsp");

                dispatcher.include(request, response);

            }
        }
    }
}

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

/**
 * editAscFile/*w  w w .  j  a v a  2s.co m*/
 */
private void editAscFile(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, ServletException, IOException {
    ServletContext sc = getServletContext();
    long omId = WebUtils.getLong(request, "om_id");
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
    sc.getRequestDispatcher("/admin/omr_edit_asc.jsp").forward(request, response);
    log.debug("editAscFile: void");
}

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

/**
 * editFieldsFile//from   w ww .ja v a 2 s  .  c  o m
 */
private void editFieldsFile(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, ServletException, IOException {
    ServletContext sc = getServletContext();
    long omId = WebUtils.getLong(request, "om_id");
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
    sc.getRequestDispatcher("/admin/omr_edit_fields.jsp").forward(request, response);
    log.debug("editFieldsFile: void");
}

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

/**
 * delete type record//w  w  w . j ava2 s .c  om
 */
private void delete(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("delete({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    long omId = WebUtils.getLong(request, "om_id");
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
    sc.getRequestDispatcher("/admin/omr_edit.jsp").forward(request, response);
    log.debug("delete: void");
}