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.ikon.servlet.admin.MimeTypeServlet.java

/**
 * List registered mime types/*w w  w  . jav a  2s .  c o  m*/
 */
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("mimeTypes", MimeTypeDAO.findAll("mt.name"));
    sc.getRequestDispatcher("/admin/mime_list.jsp").forward(request, response);
    log.debug("list: void");
}

From source file:Servlet.BAC_UploadNotices.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww . j a  v  a  2  s .c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    try {

        InputStream inputStream = null;

        String category = null;
        String idd = "";
        ArrayList<String> files = new ArrayList<String>();
        ArrayList<String> fileType = new ArrayList<String>();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                //ArrayList<String> 

                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

                String id = null;
                String contractorName = null;
                int cont_has_proj_ID = 0;

                String title = null;

                File path = null;
                File uploadedFiles = null;
                String fileName = null;
                String documentType = null;

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {

                        //Returns the string inside the field
                        String value = item.getString();
                        //returns the name of the field
                        String value2 = item.getFieldName();

                        if (value2.equals("projectId")) {
                            id = value;
                            idd = value;
                        }
                        if (value2.equals("projectName")) {
                            title = value;
                        }
                        if (value2.equals("contProject")) {
                            cont_has_proj_ID = Integer.parseInt(value);
                        }
                        if (value2.equals("contractor")) {
                            contractorName = value;
                        }

                    }

                    if (!item.isFormField()) {
                        fileName = item.getName();
                        String root = getServletContext().getRealPath("/");

                        String fieldname = item.getFieldName();
                        //Add the conditions here
                        if (fieldname.equalsIgnoreCase("Notice of award")) {

                            documentType = "Notice of award";

                        }
                        if (fieldname.equalsIgnoreCase("Notice to proceed")) {

                            documentType = "Notice to proceed";

                        }
                        fileType.add(documentType);

                        //path where the file will be stored
                        path = new File("D:\\Development\\NetBeans\\Projects\\Cogito\\Upload"
                                + "/Bids and Awards Department" + "/Bid Notices/" + title + "/"
                                + contractorName);
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        uploadedFiles = new File(path + "/" + fileName);
                        item.write(uploadedFiles);
                        files.add(fileName);

                    }
                }

                BACDAO bacdao = new BACDAO();
                OCPDDAO oc = new OCPDDAO();
                //CHANGE
                Project project = oc.getBasicProjectDetails(id);
                int contractorIdd = bacdao.getContractorID(cont_has_proj_ID);
                Contractor contractor = bacdao.getContractorInfo(contractorIdd);
                bacdao.changeBACStatus4(bacdao.getContUser(contractorIdd), id);
                bacdao.changeBACStatus5(cont_has_proj_ID);
                ArrayList<Contractor_Has_Project> respondents = bacdao.getViewRespondents(id);
                for (int x = 0; x < respondents.size(); x++) {
                    if (respondents.get(x).getID() == contractorIdd) {
                        respondents.remove(x);
                    }
                }
                for (int x = 0; x < respondents.size(); x++) {
                    bacdao.deleteContractorProj(respondents.get(x).getID());
                }
                //CHANGE
                for (int x = 0; x < files.size(); x++) {
                    Bid_Notices bidnotice = new Bid_Notices(0, files.get(x), null, project, contractor,
                            "chrome-extension://nhcgkapmceenhknicldaiaplpkpmicmc/"
                                    + "Bids and Awards Department" + "/Bid Notices/" + title + "/"
                                    + contractorName,
                            fileType.get(x));
                    bacdao.uploadBidNotices(bidnotice);
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                Logger.getLogger(BAC_UploadInvitationToBid.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        request.setAttribute("success", "Success");
        ServletContext context = getServletContext();
        RequestDispatcher dispatch = context.getRequestDispatcher("/BAC_Home");
        dispatch.forward(request, response);

    } finally {
        out.close();
    }

}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    UserItem currentUser = (UserItem) session.getAttribute("user");
    if (currentUser != null && ServletFileUpload.isMultipartContent(req)) {
        Conf conf = (Conf) getServletContext().getAttribute("conf");
        // keep files of up to 10 MiB in memory 10485760
        FileItemFactory factory = new DiskFileItemFactory(10485760, new File(conf.getPathTemp()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(conf.getFileSizeMax());

        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        session.setAttribute("uploadListener", listener);
        upload.setProgressListener(listener);

        File tempFile = File.createTempFile(String.format("%05d-", currentUser.getUid()), null,
                new File(conf.getPathTemp()));
        tempFile.deleteOnExit();// w w w. j  ava  2 s  .  co m
        try {
            FileItem file = new FileItem();

            /* iterate over all uploaded items */
            FileItemIterator it = upload.getItemIterator(req);
            FileOutputStream filestream = null;

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String name = item.getFieldName();
                InputStream instream = item.openStream();
                DigestOutputStream outstream = null;

                if (item.isFormField()) {
                    String value = Streams.asString(instream);
                    // logger.info(name + " : " + value);
                    /* not the file upload. Maybe the password field? */
                    if (name.equals("password") && !value.equals("")) {
                        logger.info("Uploaded file has password set");
                        file.setPwPlainText(value);
                    }
                    instream.close();
                } else {
                    // This is the file you're looking for
                    file.setName(item.getName());
                    file.setType(
                            item.getContentType() == null ? "application/octet-stream" : item.getContentType());
                    file.setUid(currentUser.getUid());

                    try {
                        filestream = new FileOutputStream(tempFile);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        outstream = new DigestOutputStream(filestream, md);
                        long filesize = IOUtils.copyLarge(instream, outstream);

                        if (filesize == 0) {
                            throw new Exception("File is empty.");
                        }
                        md = outstream.getMessageDigest();
                        file.setMd5sum(toHex(md.digest()));
                        file.setSize(filesize);

                    } finally {
                        if (outstream != null) {
                            try {
                                outstream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (filestream != null) {
                            try {
                                filestream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                }
            }
            /* All done. Save the new file */
            if (conf.getDaysFileExpiration() != 0) {
                file.setDaysToKeep(conf.getDaysFileExpiration());
            }
            if (file.create(ds, req.getRemoteAddr())) {
                File finalFile = new File(conf.getPathStore(), Integer.toString(file.getFid()));
                tempFile.renameTo(finalFile);
                logger.log(Level.INFO, "User {0} storing file \"{1}\" in the filestore",
                        new Object[] { currentUser.getUid(), file.getName() });
                req.setAttribute("msg",
                        "File <strong>\"" + Helpers.htmlSafe(file.getName())
                                + "\"</strong> uploaded successfully. <a href='" + req.getContextPath()
                                + "/file/edit/" + file.getFid() + "'>Click here to edit file</a>");
                req.setAttribute("javascript", "parent.uploadComplete('info');");
            } else {
                req.setAttribute("msg", "Unable to contact the database");
                req.setAttribute("javascript", "parent.uploadComplete('critical');");
            }
        } catch (SizeLimitExceededException e) {
            tempFile.delete();
            req.setAttribute("msg", "File is too large. The maximum size of file uploads is "
                    + FileItem.humanReadable(conf.getFileSizeMax()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (FileUploadException e) {
            tempFile.delete();
            req.setAttribute("msg", "Unable to upload file");
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (Exception e) {
            tempFile.delete();
            req.setAttribute("msg",
                    "Unable to upload file. ".concat(e.getMessage() == null ? "" : e.getMessage()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } finally {
            session.setAttribute("uploadListener", null);
        }
        ServletContext app = getServletContext();
        RequestDispatcher disp = app.getRequestDispatcher("/templates/AjaxDummy.jsp");
        disp.forward(req, resp);
    }
}

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

/**
 * Create CSS/*from  w  ww .  jav a2  s .  c  o m*/
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("create({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();

    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("persist", true);
    sc.setAttribute("css", null);
    sc.getRequestDispatcher("/admin/css_edit.jsp").forward(request, response);

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

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

/**
 * Edit property groups// ww  w  . j  a v  a 2 s  .co m
 */
private void edit(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("edit({}, {})", new Object[] { request, response });

    if (WebUtils.getBoolean(request, "persist")) {
        String definition = request.getParameter("definition");
        FileUtils.writeStringToFile(new File(Config.PROPERTY_GROUPS_XML), definition, "UTF-8");

        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_EDIT", null, null, null);
    } else {
        String xml = FileUtils.readFileToString(new File(Config.PROPERTY_GROUPS_XML), "UTF-8");
        ServletContext sc = getServletContext();
        sc.setAttribute("persist", true);
        sc.setAttribute("action", "edit");
        sc.setAttribute("definition", xml.replace("&", "&amp;"));
        sc.getRequestDispatcher("/admin/property_groups_edit.jsp").forward(request, response);
    }

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

From source file:org.apache.struts2.portlet.result.PortletResult.java

/**
 * Executes the regular servlet result.// w w w  .  j  a va 2  s  .co  m
 */
private void executeRegularServletResult(String finalLocation, ActionInvocation actionInvocation)
        throws ServletException, IOException {
    ServletContext ctx = ServletActionContext.getServletContext();
    HttpServletRequest req = ServletActionContext.getRequest();
    HttpServletResponse res = ServletActionContext.getResponse();
    try {
        ctx.getRequestDispatcher(finalLocation).include(req, res);
    } catch (ServletException e) {
        LOG.error("ServletException including " + finalLocation, e);
        throw e;
    } catch (IOException e) {
        LOG.error("IOException while including result '" + finalLocation + "'", e);
        throw e;
    }
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*  w  ww. ja v a2  s  . c o m*/

    ServletContext sc = getServletContext();
    sc.setAttribute("repoPath", "/" + Repository.ROOT);
    sc.setAttribute("docUuid", null);
    sc.setAttribute("text", null);
    sc.setAttribute("time", null);
    sc.setAttribute("mimeType", null);
    sc.setAttribute("extractor", null);
    sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
}

From source file:com.bstek.dorado.view.resolver.HtmlViewResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (touchUserAgentArray != null) {
        String userAgent = request.getHeader("user-agent");
        for (String mobile : touchUserAgentArray) {
            if (StringUtils.containsIgnoreCase(userAgent, mobile)) {
                Context context = Context.getCurrent();
                context.setAttribute("com.bstek.dorado.view.resolver.HtmlViewResolver.isTouch", true);
                break;
            }/*from   w ww  .j  av a  2 s.c  o m*/
        }
    }

    String uri = getRelativeRequestURI(request);
    if (!PathUtils.isSafePath(uri)) {
        throw new PageAccessDeniedException("[" + request.getRequestURI() + "] Request forbidden.");
    }

    if (shouldAutoLoadDataConfigResources) {
        if (System.currentTimeMillis() - lastValidateTimestamp > MIN_DATA_CONFIG_VALIDATE_SECONDS
                * ONE_SECOND) {
            lastValidateTimestamp = System.currentTimeMillis();

            ((ReloadableDataConfigManagerSupport) dataConfigManager).validateAndReloadConfigs();

            if (dataConfigManager instanceof ConfigurableDataConfigManager) {
                ((ConfigurableDataConfigManager) dataConfigManager).recalcConfigLocations();
            }
        }
    }

    String viewName = extractViewName(uri);

    if (listeners != null) {
        synchronized (listeners) {
            for (ViewResolverListener listener : listeners) {
                listener.beforeResolveView(viewName);
            }
        }
    }

    DoradoContext context = DoradoContext.getCurrent();
    ViewConfig viewConfig = null;
    try {
        viewConfig = viewConfigManager.getViewConfig(viewName);
    } catch (FileNotFoundException e) {
        throw new PageNotFoundException(e);
    }

    View view = viewConfig.getView();

    ViewCacheMode cacheMode = ViewCacheMode.none;
    ViewCache cache = view.getCache();
    if (cache != null && cache.getMode() != null) {
        cacheMode = cache.getMode();
    }

    if (ViewCacheMode.clientSide.equals(cacheMode)) {
        long maxAge = cache.getMaxAge();
        if (maxAge <= 0) {
            maxAge = Configure.getLong("view.clientSideCache.defaultMaxAge", 300);
        }

        response.addHeader(HttpConstants.CACHE_CONTROL, HttpConstants.MAX_AGE + maxAge);
    } else {
        response.addHeader(HttpConstants.CACHE_CONTROL, HttpConstants.NO_CACHE);
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Expires", "0");
    }

    String pageTemplate = view.getPageTemplate();
    String pageUri = view.getPageUri();
    if (StringUtils.isNotEmpty(pageTemplate) && StringUtils.isNotEmpty(pageUri)) {
        throw new IllegalArgumentException(
                "Can not set [view.pageTemplate] and [view.pageUri] at the same time.");
    }

    if (StringUtils.isNotEmpty(pageUri)) {
        ServletContext servletContext = context.getServletContext();
        RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(pageUri);
        request.setAttribute(View.class.getName(), view);
        requestDispatcher.include(request, response);
    } else {
        org.apache.velocity.context.Context velocityContext = velocityHelper.getContext(view, request,
                response);

        Template template = getPageTemplate(pageTemplate);
        PrintWriter writer = getWriter(request, response);
        try {
            template.merge(velocityContext, writer);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    if (listeners != null) {
        synchronized (listeners) {
            for (ViewResolverListener listener : listeners) {
                listener.afterResolveView(viewName, view);
            }
        }
    }
}

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

/**
 * List property groups//from w ww .  java2  s.  c o  m
 * @throws Exception 
 */
private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();

    XMLUtils utils = new XMLUtils(PROPERTY_GROUPS_XML);
    if (utils.isPGXMLEmpty()) {
        sc.getRequestDispatcher("/admin/property_group_register.jsp").forward(request, response);
    } else {

        FormUtils.resetPropertyGroupsForms();
        OKMPropertyGroup okmPropGroups = OKMPropertyGroup.getInstance();
        List<PropertyGroup> groups = okmPropGroups.getAllGroups(null);
        Map<PropertyGroup, List<Map<String, String>>> pGroups = new LinkedHashMap<PropertyGroup, List<Map<String, String>>>();

        for (PropertyGroup group : groups) {
            List<FormElement> mData = okmPropGroups.getPropertyGroupForm(null, group.getName());
            List<Map<String, String>> fMaps = new ArrayList<Map<String, String>>();

            for (FormElement fe : mData) {
                fMaps.add(FormUtils.toString(fe));
            }

            pGroups.put(group, fMaps);
        }

        sc.setAttribute("pGroups", pGroups);
        sc.getRequestDispatcher("/admin/property_groups_list.jsp").forward(request, response);

        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_LIST", null, null, null);
    }
    log.debug("list: void");
}

From source file:Servlet.Citizen_AddInfo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w  .j  a v a 2s .  c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();

    ActivityDAO actdao = new ActivityDAO();

    try {
        CitizenDAO citizenDAO = new CitizenDAO();
        NotificationDAO ntDAO = new NotificationDAO();
        Citizen c = (Citizen) session.getAttribute("user");
        InputStream inputStream = null;

        ArrayList<String> files = new ArrayList<String>();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                //ArrayList<String> 

                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

                String title = null;
                String description = null;
                String location = null;
                String locationdetails = null;

                String videoD = null;
                String imageD = null;
                String documentD = null;

                File path = null;
                File uploadedFiles = null;
                String fileName = null;
                Citizen user = (Citizen) session.getAttribute("user");

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {

                        //Returns the string inside the field
                        String value = item.getString();
                        //returns the name of the field
                        String value2 = item.getFieldName();

                        if (value2.equals("testimonialtitle")) {
                            title = value;
                        }
                        if (value2.equals("testimonialdescription")) {
                            description = value;
                        }
                        if (value2.equals("videodescription")) {
                            videoD = value;
                        }
                        if (value2.equals("imagedescription")) {
                            imageD = value;
                        }
                        if (value2.equals("documentdescription")) {
                            documentD = value;
                        }

                    }

                    if (!item.isFormField()) {
                        fileName = item.getName();
                        String root = getServletContext().getRealPath("/");

                        //path where the file will be stored
                        path = new File("C:\\Users\\AdrianKyle\\Documents\\NetBeansProjects\\Cogito\\Upload"
                                + "/Citizen/" + title);
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        uploadedFiles = new File(path + "/" + fileName);
                        item.write(uploadedFiles);
                        files.add(fileName);

                    }
                }

                Testimonial t = (Testimonial) session.getAttribute("openTestimonial");

                //Add activity
                actdao.addActivity(new Activity(0,
                        "you have added additional information in a testimonial entitled " + title, null,
                        user.getUser()));

                //Add Notification
                ntDAO.addNotification(new Notification(0, c.getFirstName() + " " + c.getLastName()
                        + " has requested to add additional files to testimonial entitled " + t.getTitle(),
                        null, t.getCitizen().getUser()));

                //Place in appropriate tables
                for (int x = 0; x < files.size(); x++) {

                    String filename = files.get(x);
                    String[] parts = filename.split(Pattern.quote("."));
                    String extension = parts[1];
                    //Videos
                    if (extension.equalsIgnoreCase("mp4") || extension.equalsIgnoreCase("avi")
                            || extension.equalsIgnoreCase("3gp") || extension.equalsIgnoreCase("flv")
                            || extension.equalsIgnoreCase("wmv") || extension.equalsIgnoreCase("mkv")) {
                        Files f = new Files();
                        f.setFileName(files.get(x));
                        f.setType("Video");
                        f.setTestimonial(t);
                        f.setStatus("Pending");
                        f.setDescription(videoD);
                        f.setUploader(c.getUser().getUsername());
                        f.setTestimonial(t);
                        citizenDAO.uploadFiles(f, c.getUser().getUsername());

                    } //Images
                    else if (extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("jpeg")
                            || extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("bmp")) {
                        Files f = new Files();
                        f.setFileName(files.get(x));
                        f.setType("Image");
                        f.setTestimonial(t);
                        f.setStatus("Pending");
                        f.setDescription(imageD);
                        f.setUploader(c.getUser().getUsername());
                        f.setTestimonial(t);
                        citizenDAO.uploadFiles(f, c.getUser().getUsername());
                    } //Documents 
                    else if (extension.equalsIgnoreCase("pdf") || extension.equalsIgnoreCase("docx")
                            || extension.equalsIgnoreCase("doc") || extension.equalsIgnoreCase("pptx")
                            || extension.equalsIgnoreCase("txt") || extension.equalsIgnoreCase("xlsx")) {
                        Files f = new Files();
                        f.setFileName(files.get(x));
                        f.setType("Document");
                        f.setTestimonial(t);
                        f.setStatus("Pending");
                        f.setDescription(documentD);
                        f.setUploader(c.getUser().getUsername());
                        f.setTestimonial(t);
                        citizenDAO.uploadFiles(f, c.getUser().getUsername());
                    }

                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                Logger.getLogger(Citizen_AddInfo.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        request.setAttribute("success", "addSuccess");
        ServletContext context = getServletContext();
        RequestDispatcher dispatch = context.getRequestDispatcher("/Citizen_SearchTestimonial");
        dispatch.forward(request, response);

    } finally {
        out.close();
    }
}