com.krawler.esp.servlets.ExportMPXServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.krawler.esp.servlets.ExportMPXServlet.java

Source

/*
 * Copyright (C) 2012  Krawler Information Systems Pvt Ltd
 * All rights reserved.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package com.krawler.esp.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.mpxj.Duration;
import net.sf.mpxj.ProjectCalendar;
import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.ProjectHeader;
import net.sf.mpxj.Resource;
import net.sf.mpxj.ResourceAssignment;
import net.sf.mpxj.Task;
import net.sf.mpxj.TimeUnit;
import net.sf.mpxj.mpx.MPXWriter;
import net.sf.mpxj.mspdi.MSPDIWriter;
import net.sf.mpxj.writer.ProjectWriter;
import com.krawler.database.DbPool;
import com.krawler.database.DbPool.Connection;
import com.krawler.common.service.ServiceException;
import com.krawler.common.session.SessionExpiredException;
import com.krawler.common.util.Constants;
import com.krawler.common.util.KrawlerLog;
import com.krawler.common.util.StringUtil;
import com.krawler.database.DbResults;
import com.krawler.database.DbUtil;
import com.krawler.esp.handlers.AuditTrail;
import com.krawler.esp.handlers.AuthHandler;
import com.krawler.esp.handlers.projdb;
import com.krawler.svnwebclient.configuration.ConfigurationException;
import com.krawler.utils.json.base.JSONArray;
import com.krawler.utils.json.base.JSONException;
import com.krawler.utils.json.base.JSONObject;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.mpxj.Priority;
import net.sf.mpxj.Rate;
import net.sf.mpxj.RelationType;
import net.sf.mpxj.ResourceType;

public class ExportMPXServlet extends HttpServlet {

    public class EndPage extends PdfPageEventHelper {

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            try {
                Rectangle page = document.getPageSize();
                PdfPTable foot = new PdfPTable(1);
                PdfPCell cell = new PdfPCell(new Paragraph("Generated by: Project Management Application",
                        FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)));
                cell.setBorder(0);
                foot.addCell(cell);
                foot.setTotalWidth(page.getWidth() / 4);
                foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin() + 10,
                        writer.getDirectContent());
            } catch (Exception e) {
                Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
                throw new ExceptionConverter(e);
            }
        }
    }

    private static final long serialVersionUID = -8401651817881523209L;
    static SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd");
    private static Font fontBig = FontFactory.getFont("Helvetica", 24, Font.NORMAL, Color.BLACK);
    private static String imgPath = "";
    private static String companyName = "";
    private static String companySubDomain = "";

    public static void clearAll() {
        imgPath = "";
        companyName = "";
        companySubDomain = "";
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        clearAll();
        if (com.krawler.esp.handlers.SessionHandler.isValidSession(request, response)) {
            com.krawler.database.DbPool.Connection conn = null;
            try {
                conn = DbPool.getConnection();
                String fileType = request.getParameter("filetype");
                String userid = AuthHandler.getUserid(request);
                if (StringUtil.equal(fileType, "mpx")) {
                    createMpxFile(conn, request, response, userid);
                } else if (StringUtil.equal(fileType, "csv")) {
                    createCsvFile(conn, request, response);
                } else if (StringUtil.equal(fileType, "pdf")) {
                    createPDFFile(conn, request, response);
                }
            } catch (ConfigurationException ex) {
                Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SessionExpiredException ex) {
                Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ServiceException xex) {
                KrawlerLog.op.warn("Problem In Connection while creating project:" + xex.toString());
                DbPool.quietRollback(conn);
            } finally {
                DbPool.quietClose(conn);
            }
        } else {
            response.getOutputStream().println("{\"valid\": false}");
        }
    }

    public static void createCsvFile(Connection conn, HttpServletRequest request, HttpServletResponse response) {
        String projid = request.getParameter("projectid");
        try {
            String userid = AuthHandler.getUserid(request);
            String companyid = AuthHandler.getCompanyid(request);
            String tasks = projdb.getProjectTasks(conn, projid, userid, companyid, 0, -1, true);
            String[] priority = { "High", "Moderate", "Low" };
            StringBuilder taskSB = new StringBuilder();
            HashMap taskIdIndex = new HashMap();
            HashMap<String, String> WBS = new HashMap();
            WBS = getWBSTypeParentValue(conn, projid, 0, WBS);
            JSONArray taskArr = new com.krawler.utils.json.base.JSONObject(tasks).getJSONArray("data");
            taskSB.append(
                    "\"Taskid\",\"Task Name\",\"Duration\",\"Start Date\",\"End Date\",\"Predecessor\",\"Parent\","
                            + "\"Resource Names\",\"Percent Complete\",\"Priority\",\"Notes\"\n");
            for (int c = 0; c < taskArr.length(); c++) {
                com.krawler.utils.json.base.JSONObject temp = taskArr.getJSONObject(c);
                taskIdIndex.put(temp.getString("taskid"), temp.getInt("taskindex"));
            }
            taskIdIndex.put("0", 0);
            for (int c = 0; c < taskArr.length(); c++) {
                com.krawler.utils.json.base.JSONObject temp = taskArr.getJSONObject(c);
                String pred = "";
                if (!StringUtil.isNullOrEmpty(temp.getString("predecessor"))) {
                    String[] p = temp.getString("predecessor").split(",");
                    for (int i = 0; i < p.length; i++) {
                        pred += taskIdIndex.get(p[i]).toString() + ",";
                    }
                    pred = pred.substring(0, (pred.length() - 1));
                }
                String tempStr = "\"" + Integer.toString(temp.getInt("taskindex")) + "\"," + "\""
                        + temp.getString("taskname") + "\"," + "\"" + temp.getString("duration") + "\"," + "\""
                        + temp.getString("startdate") + "\"," + "\"" + temp.getString("enddate") + "\"," + "\""
                        + pred + "\"," + "\"" + WBS.get(temp.getString("taskid")) + "\"," + "\""
                        + projdb.getTaskResourcesNames(conn, temp.getString("taskid"), projid) + "\"," + "\""
                        + Integer.toString(temp.getInt("percentcomplete")) + "\"," + "\""
                        + priority[temp.getInt("priority")] + "\"," + "\""
                        + temp.getString("notes").replace("\n", "\\n") + "\"\n";
                taskSB.append(tempStr);
            }
            String fname = request.getParameter("filename");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(taskSB.toString().getBytes());
            os.close();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + ".csv\"");
            response.setContentType("application/octet-stream");
            response.setContentLength(os.size());
            response.getOutputStream().write(os.toByteArray());
            response.getOutputStream().flush();
            String type = "[CSV]";
            AddToAuditTrail(conn, request, projid, type);
            conn.commit();
        } catch (ServiceException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException e) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, e);
        } catch (SessionExpiredException e) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    public static void getCompanyDetails(HttpServletRequest request) {
        String res1 = null;
        String res2 = null;
        String res3 = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        com.krawler.database.DbPool.Connection conn = null;
        String GET_COMPNY_IMGPATH = "SELECT companyname,subdomain,image FROM company WHERE companyid = ?";
        try {
            conn = DbPool.getConnection();
            pstmt = conn.prepareStatement(GET_COMPNY_IMGPATH);
            pstmt.setString(1, AuthHandler.getCompanyid(request));
            rs = pstmt.executeQuery();
            if (rs.next()) {

                res1 = rs.getString("image").trim();
                String tmp[] = res1.split("/");
                res1 = tmp[tmp.length - 1].toString().trim();
                res3 = rs.getString("subdomain");
                res2 = rs.getString("companyname");
            } else {
                res1 = "";
                res2 = "";
                res3 = "";
            }
            //                conn.close();
        } catch (SessionExpiredException ex) {
            KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
            DbPool.quietRollback(conn);
            res1 = "";
            res2 = "";
            res3 = "";
        } catch (SQLException ex) {
            KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
            DbPool.quietRollback(conn);
            res1 = "";
            res2 = "";
            res3 = "";
        } catch (ServiceException ex) {
            KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
            DbPool.quietRollback(conn);
            res1 = "";
            res2 = "";
            res3 = "";
        } finally {
            imgPath = res1;
            companyName = res2;
            companySubDomain = res3;
            DbPool.quietClose(conn);
        }
    }

    private static void addComponyLogo(Document d) throws ConfigurationException, DocumentException {
        PdfPTable table = new PdfPTable(1);
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.setWidthPercentage(50);
        PdfPCell cell = null;
        try {
            imgPath = com.krawler.esp.utils.ConfigReader.getinstance().get("platformURL") + "b/" + companySubDomain
                    + "/images/store/?company=true";
            // imgPath="http://192.168.0.141:8080/dp_dev/b/Demo/images/store/?company=true";
            Image img = Image.getInstance(imgPath);
            cell = new PdfPCell(img);
        } catch (Exception e) {
            cell = new PdfPCell(new Paragraph(companyName, fontBig));
        }
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(cell);
        table.setSpacingAfter(10);
        d.add(table);
    }

    public void createPDFFile(Connection conn, HttpServletRequest request, HttpServletResponse response)
            throws ConfigurationException {
        String projid = request.getParameter("projectid");
        try {
            String userid = AuthHandler.getUserid(request);
            String companyid = AuthHandler.getCompanyid(request);
            String tasks = projdb.getProjectTasks(conn, projid, userid, companyid, 0, -1, true);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4);
            document.setPageSize(PageSize.A4.rotate());
            PdfWriter writer = PdfWriter.getInstance(document, os);
            setHeaderFooter(document, request.getParameter("header"));
            JSONObject jobj = new JSONObject(request.getParameter("options"));
            JSONArray jarr = jobj.getJSONArray("data");
            ArrayList tabCols = new ArrayList();
            ArrayList tabArr = createTables(jarr, tabCols, document);//new ArrayList();
            writer.setPageEvent(new EndPage());

            HashMap taskIdIndex = new HashMap();
            JSONArray taskArr = new com.krawler.utils.json.base.JSONObject(tasks).getJSONArray("data");
            for (int c = 0; c < taskArr.length(); c++) {
                com.krawler.utils.json.base.JSONObject temp = taskArr.getJSONObject(c);
                taskIdIndex.put(temp.getString("taskid"), temp.getInt("taskindex"));
            }
            taskIdIndex.put("0", 0);
            for (int c = 0; c < taskArr.length(); c++) {
                com.krawler.utils.json.base.JSONObject temp = taskArr.getJSONObject(c);
                String pred = "";
                if (!StringUtil.isNullOrEmpty(temp.getString("predecessor"))) {
                    String[] p = temp.getString("predecessor").split(",");
                    for (int i = 0; i < p.length; i++) {
                        pred += taskIdIndex.get(p[i]).toString() + ",";
                    }
                    pred = pred.substring(0, (pred.length() - 1));
                }
                String taskResourceNames = projdb.getTaskResourcesNames(conn, temp.getString("taskid"), projid);
                for (int i = 0; i < tabArr.size(); i++) {
                    int lvl = 0;
                    if (i == 0) {
                        lvl = temp.getInt("level");
                    }
                    String[] colArr = (String[]) tabCols.get(i);
                    String[] values = getPDFCellOfRec(colArr, temp, pred, taskResourceNames);
                    Font fnt = new Font();
                    if (temp.getBoolean("isparent")) {
                        fnt.setStyle(Font.BOLD);
                    } else {
                        fnt.setStyle(Font.NORMAL);
                    }
                    addPdfRowToTable(values, (PdfPTable) tabArr.get(i), fnt, lvl);
                }
            }
            document.open();
            getCompanyDetails(request);
            addComponyLogo(document);
            for (int i = 0; i < tabArr.size(); i++) {
                PdfPTable temp = (PdfPTable) tabArr.get(i);
                temp.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
                document.add(temp);
                document.newPage();
            }
            document.close();
            os.close();
            String fname = request.getParameter("filename");
            os.close();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + ".pdf\"");
            response.setContentType("application/octet-stream");
            response.setContentLength(os.size());
            response.getOutputStream().write(os.toByteArray());
            response.getOutputStream().flush();
            String type = "[PDF]";
            AddToAuditTrail(conn, request, projid, type);
            conn.commit();
        } catch (ServiceException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException e) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, e);
        } catch (SessionExpiredException e) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    public static void setHeaderFooter(Document doc, String headerText) {
        HeaderFooter footer = new HeaderFooter(
                new Phrase(" ", FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)), true);
        footer.setBorderWidth(0);
        footer.setBorderWidthTop(1);
        footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
        doc.setFooter(footer);
        HeaderFooter header = new HeaderFooter(
                new Phrase(headerText, FontFactory.getFont("Helvetica", 14, Font.BOLD, Color.BLACK)), false);
        doc.setHeader(header);
    }

    public static ArrayList createTables(JSONArray jarr, ArrayList tabCols, Document doc) throws DocumentException {
        ArrayList tabArr = new ArrayList();
        ArrayList hMap = getColumnHash(jarr);
        HashMap hMapWidth = (HashMap) hMap.get(1);
        HashMap hMapColumn = (HashMap) hMap.get(0);
        int total = 0;
        ArrayList cols = null;
        ArrayList widths = null;
        //        int tmep = 0;
        while (!hMapWidth.isEmpty()) {
            if (total == 0) {
                cols = new ArrayList();
                widths = new ArrayList();
                cols.add(hMapColumn.get(hMapColumn.keySet().toArray()[0]));
                widths.add(hMapWidth.get(hMapWidth.keySet().toArray()[0]));
                total += Integer.parseInt(hMapWidth.get(hMapWidth.keySet().toArray()[0]).toString());
                hMapColumn.remove(hMapColumn.keySet().toArray()[0]);
                hMapWidth.remove(hMapWidth.keySet().toArray()[0]);
            }
            int keyVal = getNextWidth(total, hMapWidth);
            if (keyVal != -1) {
                cols.add(hMapColumn.get(keyVal));
                widths.add(hMapWidth.get(keyVal));
                total += Integer.parseInt(hMapWidth.get(keyVal).toString());
                hMapColumn.remove(keyVal);
                hMapWidth.remove(keyVal);
            } else {
                tabArr.add(createPdfTable(cols, widths, tabCols, doc));
                total = 0;
            }
        }
        if (!cols.isEmpty()) {
            tabArr.add(createPdfTable(cols, widths, tabCols, doc));
        }
        return tabArr;
    }

    public static int getNextWidth(int total, HashMap hMap) {
        int key = -1;
        Object[] keyArr = hMap.keySet().toArray();
        if (keyArr.length != 0) {
            int diff = Integer.parseInt(hMap.get(keyArr[0]).toString()) + total;
            if ((850 - diff) >= 0) {
                key = Integer.parseInt(keyArr[0].toString());
            }
            for (int i = 1; i < hMap.size(); i++) {
                int temp = Integer.parseInt(hMap.get(keyArr[i]).toString()) + total;
                if ((850 - temp) >= 0 && diff < temp) {
                    diff = temp;
                    key = Integer.parseInt(keyArr[i].toString());
                }
            }
        }
        return key;
    }

    public static PdfPTable createPdfTable(ArrayList header, ArrayList widths, ArrayList tabCol, Document doc)
            throws DocumentException {
        PdfPTable temp = new PdfPTable(header.size());
        float[] wid = new float[widths.size()];
        String[] cols = new String[header.size()];
        for (int i = 0; i < widths.size(); i++) {
            wid[i] = (float) (Integer.parseInt(widths.get(i).toString()));
            cols[i] = header.get(i).toString();
        }
        temp.setWidthPercentage(wid, doc.getPageSize());
        temp.setTotalWidth(100);
        Font fnt1 = new Font();
        fnt1.setStyle(Font.NORMAL);
        addPdfRowToTable(cols, temp, fnt1, 0);
        temp.setHeaderRows(1);
        tabCol.add(cols);
        return temp;
    }

    public static ArrayList getColumnHash(JSONArray jarr) {
        ArrayList arr = new ArrayList();
        try {
            HashMap hMapWidth = new HashMap();
            HashMap hMapColumn = new HashMap();
            for (int i = 0; i < jarr.length(); i++) {
                JSONObject temp = jarr.getJSONObject(i);
                hMapWidth.put(i, temp.getInt("width"));
                hMapColumn.put(i, temp.getString("column"));
            }
            arr.add(0, hMapColumn);
            arr.add(1, hMapWidth);
        } catch (JSONException e) {
        }
        return arr;
    }

    public static void addPdfRowToTable(String[] values, PdfPTable tab, Font fnt, int lvl) {
        for (int i = 0; i < values.length; i++) {
            PdfPCell cell = new PdfPCell(new Paragraph(values[i], fnt));
            if (values[i].compareTo("") == 0) {
                cell.setMinimumHeight(16); // Setting minimum height for cell when no data is present
            }
            if (i == 1 && lvl != 0) {
                cell.setIndent((lvl * 10));
            }
            tab.addCell(cell);
        }
    }

    public static String[] getPDFCellOfRec(String[] jarr, JSONObject rec, String pred, String res) {
        String[] values = new String[jarr.length];
        String[] priority = { "High", "Moderate", "Low" };
        try {
            for (int i = 0; i < jarr.length; i++) {
                if (StringUtil.equal("Task id", jarr[i])) {
                    values[i] = rec.getString("taskindex");
                } else if (StringUtil.equal("Task name", jarr[i])) {
                    values[i] = rec.getString("taskname");
                } else if (StringUtil.equal("Duration", jarr[i])) {
                    values[i] = rec.getString("duration");
                } else if (StringUtil.equal("Start date", jarr[i])) {
                    values[i] = rec.getString("startdate");
                } else if (StringUtil.equal("End date", jarr[i])) {
                    values[i] = rec.getString("enddate");
                } else if (StringUtil.equal("Predecessor", jarr[i])) {
                    values[i] = pred;
                } else if (StringUtil.equal("Resources", jarr[i])) {
                    values[i] = res;
                } else if (StringUtil.equal("Percent complete", jarr[i])) {
                    values[i] = Integer.toString(rec.getInt("percentcomplete"));
                } else if (StringUtil.equal("Priority", jarr[i])) {
                    values[i] = priority[rec.getInt("priority")];
                } else if (StringUtil.equal("Notes", jarr[i])) {
                    values[i] = rec.getString("notes").replaceAll("!NL!", "\\n");
                }
            }
        } catch (JSONException e) {
        }
        return values;
    }

    public static void createMpxFile(Connection conn, HttpServletRequest request, HttpServletResponse response,
            String userid) {
        try {
            String resStr = null;
            String projid = request.getParameter("projectid");
            resStr = getResource(conn, projid);
            int cnt = 0;
            String filename = request.getParameter("filename");
            JSONArray tk = getExportData(conn, projid);
            JSONArray res = null;
            if ((resStr != null || resStr.compareTo("{}") != 0)) {
                res = new JSONArray(resStr);
                cnt = res.length();
            }
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            ProjectFile file = new ProjectFile();
            file.setAutoTaskUniqueID(true);
            //            file.setAutoResourceID(true);
            file.setAutoResourceUniqueID(true);
            file.setAutoOutlineLevel(true);
            file.setAutoOutlineNumber(true);
            file.setAutoWBS(true);
            file.setAutoCalendarUniqueID(true);
            ProjectCalendar calendar = file.addDefaultBaseCalendar();
            //            ProjectCalendarException exception = calendar.addCalendarException();
            ProjectHeader header = file.getProjectHeader();
            String[] dates = projdb.getminmaxProjectDate(conn, projid, userid).split(",");
            java.util.Date dt = df1.parse(dates[0]);
            dt = df1.parse(dates[0]);
            header.setStartDate(dt);
            header.setActualStart(dt);
            HashMap rMap = new HashMap();
            List<Resource> rs = new ArrayList<Resource>();
            if (cnt != 0) {
                for (int i = 0; i < res.length(); i++) {
                    Resource resource1 = file.addResource();
                    resource1.setID(i + 1);
                    JSONObject temp = res.getJSONObject(i);
                    rMap.put(temp.getString("resourceID"), i + 1);
                    resource1.setName(temp.getString("resourceName"));
                    Rate sr = new Rate(temp.getInt("stdRate"), TimeUnit.DAYS);
                    resource1.setStandardRate(sr);
                    if (temp.getJSONObject("type").getInt("typeID") == Constants.WORK_RESOURCE) {
                        resource1.setType(ResourceType.WORK);
                        resource1.setMaxUnits(temp.getInt("wuvalue"));
                    } else if (temp.getJSONObject("type").getInt("typeID") == Constants.MATERIAL_RESOURCE) {
                        resource1.setType(ResourceType.MATERIAL);
                    } else {
                        resource1.setType(ResourceType.WORK);
                    }
                    resource1.setGroup(temp.getJSONObject("category").getString("categoryName"));
                    rs.add(resource1);
                }
            }
            List<Task> task1 = new ArrayList<Task>();
            Task projnm = file.addTask();
            projnm.setID(0);
            projnm.setName(filename);
            projnm.setUniqueID(0);
            HashMap idMap = new HashMap();
            idMap.put("0", 0);
            for (int j = 0; j < tk.length(); j++) {
                JSONObject tempJobj = tk.getJSONObject(j);
                if (!StringUtil.isNullOrEmpty(tempJobj.getString("startdate"))
                        && tempJobj.getString("parent").equals("0")) {
                    Task mst = file.addTask();
                    task1.add(mst);
                    setTaskValue(conn, mst, tempJobj, idMap, rMap, projid, rs);
                    addChilds(conn, mst, tk, j, tempJobj, idMap, task1, rMap, projid, rs);
                }
            }
            for (int i = 0; i < tk.length(); i++) {
                JSONObject tempJobj = tk.getJSONObject(i);
                String p = tempJobj.getString("predecessor");
                if (!StringUtil.isNullOrEmpty(p)) {
                    Task tempMTask = getMSTask(tempJobj.getString("taskindex"), task1);
                    String[] pr = p.split(",");
                    for (int ctr = 0; ctr < pr.length; ctr++) {
                        Task temp = getMSTask(idMap.get(pr[ctr]).toString(), task1);
                        if (!temp.getNull()) {
                            tempMTask.addPredecessor(temp, RelationType.FINISH_START,
                                    Duration.getInstance(0, TimeUnit.DAYS));
                        }
                    }
                }
            }
            ProjectWriter writer1 = getWriter(filename + ".mpx");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".mpx\"");
            response.setContentType("application/octet-stream");
            writer1.write(file, response.getOutputStream());
            String type = "[MPX]";
            AddToAuditTrail(conn, request, projid, type);
            conn.commit();
        } catch (ServiceException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            KrawlerLog.op.warn("Problem During File Operation :" + e.toString());
        } catch (JSONException e1) {
            KrawlerLog.op.warn("Problem During Creating JSON Object :" + e1.toString());
        } catch (java.text.ParseException p) {
            KrawlerLog.op.warn("Problem While Parsing Data :" + p.toString());
        }
    }

    public static Task getMSTask(String p, List<Task> t) {
        Task temp = null;
        for (int c = 0; c < t.size(); c++) {
            if (StringUtil.equal(p, t.get(c).getID().toString())) {
                temp = t.get(c);
                break;
            }
        }
        return temp;
    }

    public static void AddToAuditTrail(Connection conn, HttpServletRequest request, String projId, String type) {
        try {
            String companyid = AuthHandler.getCompanyid(request);
            String loginid = AuthHandler.getUserid(request);
            String userid = AuthHandler.getUserid(request);
            String projName = projdb.getProjectName(conn, projId);
            String userFullName = AuthHandler.getAuthor(conn, loginid);
            String userName = AuthHandler.getUserName(request);
            String ipAddress = AuthHandler.getIPAddress(request);
            String params = userFullName + "(" + userName + ")," + type + "," + projName;
            AuditTrail.insertLog(conn, "119", loginid, userid, projId, companyid, params, ipAddress, 0);
        } catch (SessionExpiredException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServiceException ex) {
            Logger.getLogger(ExportMPXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void setTaskValue(Connection conn, Task mst, JSONObject tempJobj, HashMap idMap, HashMap rMap,
            String projid, List<Resource> rl) throws JSONException, ParseException, ServiceException {
        int[] taskPriority = { 101, 500, 801 };
        mst.setName(tempJobj.getString("taskname"));
        mst.setID(tempJobj.getInt("taskindex"));
        mst.setUniqueID(tempJobj.getInt("taskindex"));
        idMap.put(tempJobj.getString("taskid"), tempJobj.getInt("taskindex"));
        mst.setPercentageComplete(tempJobj.getInt("percentcomplete"));
        mst.setStart(df.parse(tempJobj.getString("startdate")));
        String date = tempJobj.getString("actstartdate");
        if (!StringUtil.isNullOrEmpty(date)) {
            mst.setActualStart(df.parse(date));
        }
        date = tempJobj.getString("enddate");
        if (!StringUtil.isNullOrEmpty(date)) {
            mst.setFinish(df.parse(date));
        }
        String dur = tempJobj.getString("duration");
        if (dur.equals("0")) {
            mst.setMilestone(true);
            mst.setDuration(Duration.getInstance(0, TimeUnit.DAYS));
        } else {
            int duri = dur.indexOf("h");
            if (duri != -1) {
                dur = dur.substring(0, duri);
                mst.setDuration(Duration.getInstance(Double.parseDouble(dur), TimeUnit.HOURS));
            } else {
                duri = dur.indexOf("d");
                if (duri != -1) {
                    mst.setDuration(
                            Duration.getInstance(Double.parseDouble(dur.substring(0, duri)), TimeUnit.DAYS));
                    dur = dur.substring(0, duri);
                } else {
                    mst.setDuration(Duration.getInstance(Double.parseDouble(dur), TimeUnit.DAYS));
                }
            }
            mst.setMilestone(false);
        }
        String tr = projdb.getTaskResources(conn, tempJobj.getString("taskid"), projid);
        JSONObject jobj = new JSONObject(tr);
        if (!StringUtil.equal(tr, "{data:{}}")) {
            JSONArray tres = jobj.getJSONArray("data");
            for (int rcnt = 0; rcnt < tres.length(); rcnt++) {
                JSONObject temp = tres.getJSONObject(rcnt);
                if (rMap.get(temp.getString("resourceID")) != null) {
                    Resource r = getResource(rMap.get(temp.getString("resourceID")).toString(), rl);
                    if (r != null) {
                        mst.addResourceAssignment(r);
                    }
                }
            }
        }
        mst.setNotes(tempJobj.getString("notes"));
        mst.setPriority(Priority.getInstance(taskPriority[tempJobj.getInt("priority")]));
    }

    private static Resource getResource(String rid, List<Resource> rl) {
        Resource r = null;
        int id = Integer.parseInt(rid);
        for (int cnt = 0; cnt < rl.size(); cnt++) {
            if (rl.get(cnt).getID() == id) {
                r = rl.get(cnt);
                break;
            }
        }
        return r;
    }

    private static String getPredecessorValue(JSONArray task1, String SearchPred) throws JSONException {
        String[] pred2 = SearchPred.split(",");
        String ab1 = "";
        String pred = "";
        if (!pred2[0].equals(ab1)) {
            for (int l = 0; l < pred2.length; l++) {
                for (int m = 0; m < task1.length(); m++) {
                    JSONObject temp = task1.optJSONObject(m);
                    if (pred2[l].compareTo(temp.getString("taskid")) == 0) {
                        if (l == pred2.length - 1) {
                            pred += temp.getString("tindex") + "";
                        } else {
                            pred += temp.getString("tindex") + ",";
                        }
                    }
                }
            }
        }
        return pred;
    }

    private static JSONArray getExportData(Connection conn, String projid) throws ServiceException {
        String returnStr = projdb.getTask(conn, projid, 0, -1);
        com.krawler.utils.json.base.JSONArray jobj1 = null;
        try {
            if (returnStr.compareTo("{data:{}}") != 0) {
                com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject(returnStr);
                JSONArray taskArray = jobj.getJSONArray("data");
                for (int i = 0; i < taskArray.length(); i++) {
                    JSONObject temp = taskArray.getJSONObject(i);
                    String sdtStr = temp.getString("startdate");
                    String edtStr = temp.getString("enddate");
                    String actsdt = temp.getString("actualstartdate");
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-d HH:mm:ss");
                    java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-d");
                    if (sdtStr.compareTo("") != 0) {
                        java.util.Date dt = sdf.parse(sdtStr);
                        sdtStr = sdf1.format(dt);
                        temp.remove("startdate");
                        temp.put("startdate", sdtStr);
                    }
                    if (edtStr.compareTo("") != 0) {
                        java.util.Date dt = sdf.parse(edtStr);
                        edtStr = sdf1.format(dt);
                        temp.remove("enddate");
                        temp.put("enddate", edtStr);
                    }
                    if (actsdt.compareTo("") != 0) {
                        java.util.Date dt = sdf.parse(actsdt);
                        actsdt = sdf1.format(dt);
                        temp.remove("actualstartdate");
                        temp.put("actstartdate", actsdt);
                    }
                    String predecessor = projdb.getPredecessor(conn, temp.getString("taskid"));
                    temp.put("predecessor", predecessor);
                    String resources = projdb.getTaskResourcesNames(conn, temp.getString("taskid"), projid);
                    temp.put("resourcename", resources);
                    temp.put("tindex", i + 1);
                }
                returnStr = jobj.toString();
                jobj1 = jobj.getJSONArray("data");
            }
        } catch (JSONException e) {
            KrawlerLog.op.warn("Problem During Creating JSON Object :" + e.toString());
            return null;
        } catch (java.text.ParseException e1) {
            KrawlerLog.op.warn("Problem While Parsing Data :" + e1.toString());
            return null;
        }
        return jobj1;
    }

    private static String getResource(Connection conn, String pid) {
        String projectResourceList = null;
        try {
            //            projectResourceList = dbcon.getProjectResources(pid, 100, 0, "");
            projectResourceList = projdb.getProjectResources(conn, pid, 0, 100, "");
            com.krawler.utils.json.base.JSONObject resourcejObj = new com.krawler.utils.json.base.JSONObject(
                    projectResourceList);
            projectResourceList = resourcejObj.getJSONArray("data").toString();
        } catch (Exception e) {
            KrawlerLog.op.warn("Problem During Creating JSON Object :" + e.toString());
        }
        return projectResourceList;
    }

    private static ProjectWriter getWriter(String filename) {
        ProjectWriter result;
        String suffix;
        if (filename.length() < 4) {
            suffix = ".MPX";
        } else {
            suffix = filename.substring(filename.length() - 4).toUpperCase();
        }
        if (suffix.equals(".XML") == true) {
            result = new MSPDIWriter();
        } else {
            result = new MPXWriter();
        }
        return (result);
    }

    public static void addChilds(Connection conn, Task t, JSONArray tk, int ctr, JSONObject ptask, HashMap idMap,
            List<Task> task1, HashMap rMap, String projid, List<Resource> rl)
            throws JSONException, ParseException, ServiceException {
        String pTaskid = ptask.getString("taskid");
        for (int i = ctr; i < tk.length(); i++) {
            JSONObject temp = tk.getJSONObject(i);
            if (!StringUtil.isNullOrEmpty(temp.getString("startdate"))) {
                if (temp.getString("parent").equals(pTaskid)) {
                    Task mst = t.addTask();
                    setTaskValue(conn, mst, temp, idMap, rMap, projid, rl);
                    task1.add(mst);
                    addChilds(conn, mst, tk, i, temp, idMap, task1, rMap, projid, rl);
                }
            }
        }
    }

    public static void addChilds(Task t, JSONArray tk, JSONArray res, List<Resource> rs, List<String> pred, int j,
            List<Task> task1, int cnt) {

        try {
            for (int i = 0; i < tk.length(); i++) {
                if (tk.getJSONObject(i).getString("parent").compareTo(tk.getJSONObject(j).getString("taskid")) == 0
                        && i != j) {
                    JSONObject tempObj = tk.optJSONObject(i);
                    String abc = tempObj.getString("startdate");
                    String as = "";
                    String dur = null;
                    if (abc.compareTo(as) != 0) {
                        Task t1 = t.addTask();
                        t1.setID(tempObj.getInt("tindex"));
                        t1.setName(tempObj.getString("taskname"));
                        String temppred = getPredecessorValue(tk, tempObj.getString("predecessor"));
                        pred.add(temppred);
                        t1.setPercentageComplete((double) tempObj.getInt("percentcomplete"));
                        if (abc.compareTo(as) != 0) {
                            t1.setStart(df.parse(abc));
                            String as1 = tempObj.getString("duration");
                            int duri = as1.indexOf("h");
                            if (duri != -1) {
                                dur = as1.substring(0, duri);
                                t1.setDuration(Duration.getInstance(Double.parseDouble(dur), TimeUnit.HOURS));
                            } else {
                                if (duri != -1) {
                                    t1.setDuration(Duration.getInstance(Double.parseDouble(as1.substring(0, duri)),
                                            TimeUnit.DAYS));
                                    dur = as1.substring(0, duri);
                                } else {
                                    t1.setDuration(Duration.getInstance(Double.parseDouble(as1), TimeUnit.DAYS));
                                    dur = as1;
                                }
                            }
                        }

                        if (as.compareTo(tempObj.getString("enddate")) != 0) {
                            t1.setFinish(df.parse(tempObj.getString("enddate")));
                        }
                        if (as.compareTo(tempObj.getString("actstartdate")) != 0) {
                            t1.setActualStart(df.parse(tempObj.getString("actstartdate")));
                        }
                        if (dur.compareTo("0") == 0) {
                            t1.setMilestone(true);
                        }
                        t1.setNotes(tempObj.getString("notes"));
                        if (cnt != 0) {
                            String resource = tempObj.getString("resourcename");
                            String[] res1 = resource.split(",");
                            if (res1.length != 0) {
                                for (int l = 0; l < res1.length; l++) {
                                    for (int m = 0; m < rs.size(); m++) {
                                        if (res1[l].equals(rs.get(m).getName())) {
                                            ResourceAssignment assignment1 = t1.addResourceAssignment(rs.get(m));
                                        }
                                    }
                                }
                            }
                        }
                        task1.add(t1);
                        addChilds(t1, tk, res, rs, pred, i, task1, cnt);
                    }
                }
            }
        } catch (JSONException e) {
            KrawlerLog.op.warn("Problem During Creating JSON Object :" + e.toString());

        } catch (java.text.ParseException e1) {
            KrawlerLog.op.warn("Problem While Parsing Data :" + e1.toString());
        }
    }

    private static HashMap getWBSTypeParentValue(Connection conn, String projid, int curLevel,
            HashMap<String, String> hs) {
        try {
            int cnt = 1;
            DbResults rs = DbUtil.executeQuery(conn,
                    "SELECT * FROM proj_task WHERE projectid = ? AND level = ? order by taskindex",
                    new Object[] { projid, curLevel });
            if (rs.size() != 0) {
                String lastWBS = "";
                while (rs.next()) {
                    String taskid = rs.getString("taskid");
                    String parent = rs.getString("parent");
                    if (!parent.equals("0")) { // has a parent
                        if (hs.containsKey(parent)) { // parent present in HS
                            String parWbs = hs.get(parent);
                            if (!lastWBS.equals(parWbs)) {
                                lastWBS = parWbs;
                                cnt = 1;
                            }
                            String curWbs = parWbs.concat(".").concat(Integer.toString(cnt)); //create this task's WBS
                            if (!hs.containsKey(taskid)) {
                                hs.put(taskid, curWbs); // insert in HS
                            }
                        }
                    } else {
                        if (!hs.containsKey(rs.getString("taskid"))) {
                            hs.put(rs.getString("taskid"), Integer.toString(cnt));
                        }
                    }
                    cnt++;
                }
                curLevel++;
                hs = getWBSTypeParentValue(conn, projid, curLevel, hs);
            }
        } finally {
            return hs;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on
    // the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}