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

/**
 * List node properties and children//ww  w.j a  va  2 s  . co  m
 */
private void list(Session session, String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException {
    log.debug("list({}, {}, {}, {})", new Object[] { session, path, request, response });
    String stats = WebUtils.getString(request, "stats");
    String uuid = WebUtils.getString(request, "uuid");
    ServletContext sc = getServletContext();
    ContentInfo ci = null;
    Node node = null;

    // Respository stats calculation
    if (!stats.equals("")) {
        if (stats.equals("0")) {
            request.getSession().removeAttribute("stats");
        } else {
            request.getSession().setAttribute("stats", true);
        }
    }

    // Handle path or uuid
    if (!path.equals("")) {
        if (path.equals("/")) {
            node = session.getRootNode();
        } else {
            node = session.getRootNode().getNode(path.substring(1));
        }
    } else if (!uuid.equals("")) {
        node = session.getNodeByUUID(uuid);
        path = node.getPath();
    } else {
        node = session.getRootNode();
    }

    if (request.getSession().getAttribute("stats") != null && node.isNodeType(Folder.TYPE)) {
        try {
            ci = OKMFolder.getInstance().getContentInfo(null, node.getPath());
        } catch (AccessDeniedException e) {
            log.warn(e.getMessage(), e);
        } catch (com.openkm.core.RepositoryException e) {
            log.warn(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.warn(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.warn(e.getMessage(), e);
        }
    }

    // Activity log
    if (node.isNodeType(JcrConstants.MIX_REFERENCEABLE)) {
        UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_LIST", node.getUUID(), node.getPath(), null);
    } else {
        UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_LIST", ((NodeImpl) node).getId().toString(),
                node.getPath(), null);
    }

    sc.setAttribute("contentInfo", ci);
    sc.setAttribute("node", node);
    sc.setAttribute("isFolder", node.isNodeType(Folder.TYPE));
    sc.setAttribute("isDocument", node.isNodeType(Document.TYPE));
    sc.setAttribute("isDocumentContent", node.isNodeType(Document.CONTENT_TYPE));
    sc.setAttribute("isScripting", node.isNodeType(Scripting.TYPE));
    sc.setAttribute("holdsLock", node.holdsLock());
    sc.setAttribute("breadcrumb", createBreadcrumb(node.getPath()));
    sc.setAttribute("properties", getProperties(node));
    sc.setAttribute("children", getChildren(node));
    sc.getRequestDispatcher("/admin/repository_list.jsp").forward(request, response);
    log.debug("list: void");
}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/* w  w w . j a v  a  2s.co  m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

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

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

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            boolean showSql = false;
            String vtable = "";
            String type = "";
            String qs = "";
            byte[] data = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("showSql")) {
                        showSql = true;
                    } else if (item.getFieldName().equals("vtables")) {
                        vtable = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, showSql, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    sc.setAttribute("vtable", vtable);
                    executeMetadata(session, qs, false, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("showSql", showSql);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        } else {
            // Edit table cell value
            String action = request.getParameter("action");
            String vtable = request.getParameter("vtable");
            String column = request.getParameter("column");
            String value = request.getParameter("value");
            String id = request.getParameter("id");

            if (action.equals("edit")) {
                int idx = column.indexOf('(');

                if (idx > 0) {
                    column = column.substring(idx + 1, idx + 6);
                }

                String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value
                        + "' where dmv.table='" + vtable + "' and dmv.id=" + id;
                log.info("HQL: {}", hql);
                session = HibernateUtil.getSessionFactory().openSession();
                int rows = session.createQuery(hql).executeUpdate();
                log.info("Rows affected: {}", rows);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

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

/**
 * Execute metadata query//  w  ww  . jav a  2  s .  c o  m
 */
private void executeMetadata(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws DatabaseException, ServletException, IOException,
        HibernateException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String mds = st.nextToken();
        String[] parts = mds.split("\\|");

        if (parts.length > 1) {
            String hql = null;

            if (parts[0].toUpperCase().equals("SENTENCE")) {
                if (parts.length > 2) {
                    List<String> tables = Arrays.asList(parts[1].split(","));
                    hql = DatabaseMetadataUtils.replaceVirtual(tables, parts[2]);
                    log.debug("Metadata SENTENCE: {}", hql);
                    globalResults.add(executeHQL(session, hql, tables));
                }
            } else if (parts[0].toUpperCase().equals("SELECT")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], null);
                }

                log.debug("Metadata SELECT: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("UPDATE")) {
                if (parts.length > 3) {
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], parts[3]);
                } else if (parts.length > 2) {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], null);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], null, null);
                }

                log.debug("Metadata UPDATE: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("DELETE")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], null);
                }

                log.debug("Metadata DELETE: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else {
                throw new DatabaseException("Error in metadata action");
            }
        } else {
            throw new DatabaseException("Error in metadata sentence parameters");
        }
    }

    //sc.setAttribute("sql", HibernateUtil.toSql(qs));
    sc.setAttribute("exception", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

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

/**
 * Execute metadata query//from  www . j ava2s.  co m
 */
private void executeMetadata(Session session, String qs, boolean showSql, ServletContext sc,
        HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, ServletException, IOException, HibernateException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String mds = st.nextToken();
        String[] parts = mds.split("\\|");

        if (parts.length > 1) {
            String hql = null;

            if (parts[0].toUpperCase().equals("SENTENCE")) {
                if (parts.length > 2) {
                    List<String> tables = Arrays.asList(parts[1].split(","));
                    hql = DatabaseMetadataUtils.replaceVirtual(tables, parts[2]);
                    log.debug("Metadata SENTENCE: {}", hql);
                    globalResults.add(executeHQL(session, hql, showSql, tables));
                }
            } else if (parts[0].toUpperCase().equals("SELECT")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], null);
                }

                log.debug("Metadata SELECT: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("UPDATE")) {
                if (parts.length > 3) {
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], parts[3]);
                } else if (parts.length > 2) {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], null);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], null, null);
                }

                log.debug("Metadata UPDATE: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("DELETE")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], null);
                }

                log.debug("Metadata DELETE: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else {
                throw new DatabaseException("Error in metadata action");
            }
        } else {
            throw new DatabaseException("Error in metadata sentence parameters");
        }
    }

    sc.setAttribute("exception", null);
    sc.setAttribute("showSql", showSql);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

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

/**
 * Invokes this EntryPageHandler object//from   ww  w  .  j a v  a 2s.  co  m
 * <p>
 * @param p_ageDescriptor the description of the page to be produced.
 * @param p_request original request sent from the browser.
 * @param p_response original response object.
 * @param p_context the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

    if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

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

    m_exportBean = new NavigationBean(EXPORT_BEAN, p_thePageDescriptor.getPageName());
    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, LOCALIZED_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));
    p_request.setAttribute("action", p_request.getParameter("action"));
    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.LOCALIZED);
    JobVoLocalizedSearcher searcher = new JobVoLocalizedSearcher();
    searcher.setJobVos(p_request);

    p_request.setAttribute(EXPORT_URL_PARAM, m_exportBean.getPageURL());
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.LOCALIZED));
    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);

    sessionMgr.setAttribute("destinationPage", "localized");
    //clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache.  do both.  "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); //HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); //HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to cache
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

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

/**
 * Invokes this EntryPageHandler object/*from   ww  w .ja v a 2 s.c o m*/
 * <p>
 * 
 * @param p_ageDescriptor
 *            the description of the page to be produced.
 * @param p_request
 *            original request sent from the browser.
 * @param p_response
 *            original response object.
 * @param p_context
 *            the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    boolean stateMarch = false;
    if (Job.DISPATCHED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    String action = p_request.getParameter(ACTION_STRING);
    if (StringUtil.isNotEmpty(action) && "removeJobFromGroup".equals(action)) {
        removeJobFromGroup(p_request);
    }
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, BASE_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));

    // since an instance of a page handler is used by different clients,
    // this instance variable needs to be set only once. There's no need
    // to synchronize this section as the value of export url is always the
    // same.
    if (m_exportUrl == null) {
        m_exportUrl = ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL();
    }

    if (p_request.getParameter("checkIsUploadingForExport") != null) {
        long jobId = Long.parseLong(p_request.getParameter("jobId"));
        Job job = WorkflowHandlerHelper.getJobById(jobId);
        String result = "";
        for (Workflow workflow : job.getWorkflows()) {
            if (result.length() > 0)
                break;
            Hashtable<Long, Task> tasks = workflow.getTasks();
            for (Long taskKey : tasks.keySet()) {
                if (tasks.get(taskKey).getIsUploading() == 'Y') {
                    result = "uploading";
                    break;
                }
            }
        }
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        out.write(result);
        out.close();
        return;
    } else if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.DISPATCHED);
    JobVoInProgressSearcher searcher = new JobVoInProgressSearcher();
    searcher.setJobVos(p_request, true);
    p_request.setAttribute(EXPORT_URL_PARAM, m_exportUrl);
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.DISPATCHED));
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    sessionMgr.setAttribute("destinationPage", "inprogress");
    // clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache. do both. "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); // HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); // HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to
                                                        // cache
                                                        // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

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

/**
 * Invokes this EntryPageHandler object/*from w w w .  j a  v a2 s.c o  m*/
 * <p>
 * @param p_ageDescriptor the description of the page to be produced.
 * @param p_request original request sent from the browser.
 * @param p_response original response object.
 * @param p_context the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

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

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

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

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

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

    if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    performAppropriateOperation(p_request);
    Vector jobStates = new Vector();
    jobStates.add(Job.EXPORTED);
    jobStates.add(Job.EXPORT_FAIL);
    p_request.setAttribute(JobManagementHandler.EXPORT_URL_PARAM,
            ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL());
    p_request.setAttribute(JobManagementHandler.JOB_ID, JobManagementHandler.JOB_ID);

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

    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), jobStates));

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    sessionMgr.setAttribute("destinationPage", "exported");
    //clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache.  do both.  "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); //HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); //HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to cache
    // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}