Java tutorial
/* * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is fourfive code, released 12 July 2003. * * The Initial Developer of the Original Code is Jacek. * * Portions created by the Initial Developer are Copyright (C) 2003 Jacek. All Rights Reserved. * * Contributor(s): * - * check http://www.fourfive.org for the latest version of this file. * Written by Jacek. */ package org.fourfive.servlets; import java.io.IOException; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.Region; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.fourfive.adt.I_Report; import org.fourfive.adt.SerialHashtab; import org.fourfive.bcm.report.GlobalConstant; import org.fourfive.config.report.easy.Column; import org.fourfive.config.report.easy.Columns; import org.fourfive.config.report.easy.EasyReport; import org.fourfive.engine2.component.ReportCell; import org.fourfive.engine2.util.Names; import org.fourfive.exceptions.SerialHashtabException; import org.fourfive.factory.CacheFactory; import org.fourfive.factory.ClusterFactory; import org.fourfive.factory.ParserFactory; import org.fourfive.factory.RequestResolverFactory; import org.fourfive.factory.ResourceFactory; import org.fourfive.factory.SecurityFactory; import org.fourfive.highservice.LocalManager2; import org.fourfive.kernel.DefaultKernel; import org.fourfive.kernel.ReportDataUtil; import org.fourfive.lowservice.BasicExceptionHandler; import org.fourfive.lowservice.DefaultRequestResolver; import org.fourfive.tree.ArcTreeReport; import org.fourfive.tree.TreeBuilder; import org.fourfive.tree.TreeElement; import org.fourfive.tree.TreeRow; import org.fourfive.util.InterFrameWriteHelper; import org.fourfive.webobjects.TreeReport; import com.lowagie.text.Paragraph; import com.manthan.promax.config.ConfigurationSettings; import com.manthan.promax.report.PdfExcelCreator; import com.manthan.promax.report.ReportUtil; import com.manthan.promax.util.ExcelUtil; /* Changelog * ========================================== * created on 02.08.2003 * */ /**<code>TreeServlet</code> * @author Jacek * @version 1.0 * @since 1.0 */ public class ArcTreeServlet extends HttpServlet { private int mergetEnd = 0; private int mergeStart = 0; private ArrayList nonCurrItems = null; public static final String WEB_XML_NAME = "tree"; public int count_row = 1; /*=================================== * E X P O S E D * ================================== */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { try { // we are getting the tree root from executing the method again to build the report // which we are building the entitre tree so that is crashing the server so we l pass // the root object from jsp and get it from request attribute and then pass thar // root object for printing so that all query is not executed again for //===> so we are commenting next line for future implementation ArcTreeReport rootNode = null; HttpSession session = req.getSession(); if (session.getAttribute("TREE_REPORT_DATA") != null) rootNode = (ArcTreeReport) session.getAttribute("TREE_REPORT_DATA"); //TreeElement root = (TreeElement)req.getSession().getAttribute(TreeBuilder.ROOT_LITERAL); if ((Names.CSV_SELL.equals(req.getParameter(Names.OUTPUT_TYPE))) || (Names.CSV_ALL.equals(req.getParameter(Names.OUTPUT_TYPE)))) { // if(null!=req.getParameter("opt") && req.getParameter("opt").equals("print")) // { // res.setContentType("application/vnd.ms-excel"); // } // else // { // res.setContentType("application/x-download"); // res.setHeader("Content-Disposition", "attachment; filename=report.xls"); // } // ServletOutputStream sos = res.getOutputStream(); // writeExcelToOut( // rootNode, // sos, // req.getSession(),req); PdfExcelCreator pdfExcelCreator = new PdfExcelCreator(); String outputMessage = pdfExcelCreator.execute(req, res, null, true, false, false, "", ""); if (!outputMessage.equalsIgnoreCase("Successful")) { res.setContentType("text/html"); PrintWriter writer = res.getWriter(); writer.println("<HTML><HEAD><TITLE>Error</TITLE>" + "</HEAD><BODY><FORM METHOD=POST><H3><b>" + outputMessage + "</b></H3></FORM></BODY></HTML>"); writer.close(); } } } catch (Exception e) { e.printStackTrace(); } } // nikhil ====> another method added to get the tree report object and then display // it in jsp how we want public TreeElement getRoot(HttpServletRequest req, HttpServletResponse res) throws Exception { /* TODO //###### DO THE SECURITY CHECKING FOR XML ############## int SecurityLavel=0; HttpSession session = req.getSession(); if(null!=session.getAttribute("SecurityL")){ SecurityLavel=Integer.parseInt(""+session.getAttribute("SecurityL")); } if(SecurityLavel==2){ boolean status=com.manthan.promax.security.SecurityEngine.checkXMLPermission(req.getParameter(DefaultRequestResolver.CONFIGURATION),req); if(status==false){ System.out.println(" NO permission found return null.."); return null; } } //################ END ######################### */ System.out.println("we are in TRee Servlet ................"); LocalManager2 manager = new LocalManager2(CacheFactory.EASY_CACHE, ResourceFactory.EASY_RESOURCE, ClusterFactory.NO_CLUSTER, RequestResolverFactory.DEFAULT_RESOLVER, ParserFactory.TREE, SecurityFactory.EASY_SECURITY, true); SerialHashtab params = new SerialHashtab(); String configurationFileName = null; /* String configurationFileName = null; if ( (config_file == null) || (config_file.length() == 0)) { configurationFileName = req.getParameter(DefaultRequestResolver. CONFIGURATION); } else { configurationFileName = config_file; }*/ try { Date date = new Date(); /* * this section should be * in all servlets. * Refactoring ? */ try { if (req.getParameter(DefaultRequestResolver.USERNAME) != null) { params.put(DefaultRequestResolver.USERNAME, req.getParameter(DefaultRequestResolver.USERNAME)); } if (req.getParameter(DefaultRequestResolver.USERID) != null) { params.put(DefaultRequestResolver.USERID, req.getParameter(DefaultRequestResolver.USERID)); } if (req.getParameter(DefaultRequestResolver.PASSWORD) != null) { params.put(DefaultRequestResolver.PASSWORD, req.getParameter(DefaultRequestResolver.PASSWORD)); } if (req.getParameter(InterFrameWriteHelper.URT_REDIRECT) != null) { params.put(InterFrameWriteHelper.URT_REDIRECT, req.getParameter(InterFrameWriteHelper.URT_REDIRECT)); } params.put(DefaultRequestResolver.CLIENTIP, req.getRemoteAddr()); params.put(DefaultRequestResolver.SERVLET_NAME, WEB_XML_NAME); params.put("USERSESSION", req.getSession()); /* specials */ /* if (req.getParameter(TreeBuilder.NODE_LITERAL) != null) { params.put(TreeBuilder.NODE_LITERAL, req.getParameter(TreeBuilder.NODE_LITERAL)); } if (req.getParameter(TreeBuilder.STATE_LITERAL) != null) { params.put(TreeBuilder.STATE_LITERAL, req.getParameter(TreeBuilder.STATE_LITERAL)); } /* end of specials */ /* added : nikhil */ if (req.getParameter(TreeBuilder.NODE_LITERAL) != null) { if (req.getSession().getAttribute(TreeBuilder.ROOT_LITERAL) != null) { params.put(TreeBuilder.ROOT_LITERAL, req.getSession().getAttribute(TreeBuilder.ROOT_LITERAL)); } // nikhil : added for comparing the two trees in vendor performance /// comparison if (req.getSession().getAttribute("Root1") != null) { params.put("Root1", req.getSession().getAttribute("Root1")); } if (req.getSession().getAttribute("RootAdmin") != null) { params.put("RootAdmin", req.getSession().getAttribute("RootAdmin")); } } // nikhil : method written to set the parameters in parmas which we are getting from request for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String param = (String) e.nextElement(); String paramVal = req.getParameter(param); if (!paramVal.equals("All") && (!paramVal.equals("null"))) params.put(param, paramVal); } for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();) { String param = (String) e.nextElement(); if (req.getAttribute(param) instanceof String[]) { String[] paramVal = (String[]) req.getAttribute(param); params.put(param, paramVal); } else { //String paramval = (String) req.getAttribute(param); params.put(param, req.getAttribute(param)); } } if ((null != req.getSession()) && req.getSession().getAttribute("SecurityL").equals("3") && !((ArrayList) req.getSession().getAttribute("UserGroup")).contains("administrator") && (null != params.get("sector")) && params.get("sector").equals("null")) { params.put("sector", com.manthan.promax.report.RegionSectorFilterData .getPermittedSectorsAsStringForUser(req)); } configurationFileName = (String) params.get(DefaultRequestResolver.CONFIGURATION); } catch (SerialHashtabException e) { e.printStackTrace(); } I_Report rep = manager.getReport(configurationFileName, params); return ((TreeReport) rep).getTree().getRoot(); } catch (Exception e) { res.setContentType("text/html"); PrintWriter writer = res.getWriter(); writer.println("<HTML><BODY>"); writer.println(new BasicExceptionHandler().constructErrorMessage(e)); writer.println("</BODY></HTML>"); writer.flush(); writer.close(); } return null; } private void writeExcelToOut(ArcTreeReport root, ServletOutputStream out, HttpSession session, HttpServletRequest req) throws MarshalException, ValidationException { EasyReport component = root.getEasyReport(); ArrayList rows = (ArrayList) root.getTreeRows(); TreeRow row = (TreeRow) rows.get(0); ReportCell cell = null; ArrayList rowCells = row.getRowCells(); ArrayList nonVisibleCol = new ArrayList(); for (int j = 0; j < rowCells.size(); j++) { cell = (ReportCell) rowCells.get(j); if (!cell.getVisible()) { nonVisibleCol.add(new Integer(j)); } } nonCurrItems = root.getNonCurrencyColumns(); HSSFWorkbook wb = new HSSFWorkbook(); // title of the report Hashtable ht = (Hashtable) com.manthan.promax.report.ReportUtil.getLabels(session); String repGenTime = "Report Generated Time : "; if (ht != null && ht.get("export.reportgenerated.time") != null && ht.get("export.reportgenerated.time").toString().trim().length() > 0) { repGenTime = (String) ht.get("export.reportgenerated.time"); } String nameKey = (String) session.getAttribute("NAME_KEY"); int rowStart = 4; int colStart = 0; int colWidth = 10; //String dataInString = null; ExcelUtil excelUtil = new ExcelUtil(wb); excelUtil.setSession(session); excelUtil.getCurrentSelection(req); HSSFSheet sheet1 = wb.createSheet(excelUtil.getSheetTitle(nameKey)); excelUtil.setSheetStyle(); HSSFRow showTimeRow = sheet1.createRow((short) (rowStart)); HSSFCell showTimeCell = showTimeRow.createCell((short) (colStart)); showTimeCell.setCellStyle(excelUtil.getSelectionStyle()); showTimeCell.setCellValue(new HSSFRichTextString(repGenTime + new Date().toString())); sheet1.addMergedRegion(new Region(rowStart, (short) (colStart), rowStart, (short) (colStart + 7))); rowStart = rowStart + 2; HSSFRow titleRow = sheet1.createRow((short) rowStart); HSSFCell titleCell = titleRow.createCell((short) colStart); titleCell.setCellStyle(excelUtil.getTitleStyle()); titleCell.setCellValue(new HSSFRichTextString(nameKey)); sheet1.addMergedRegion(new Region(rowStart, (short) (colStart), rowStart, (short) (colStart + 10))); rowStart = rowStart + 2; HSSFRow selectionRow = sheet1.createRow((short) rowStart); //selectionRow.setHeightInPoints(40); HSSFCell selectionCell = selectionRow.createCell((short) colStart); selectionCell.setCellStyle(excelUtil.getSelectionStyle()); java.util.ArrayList summaryData = (java.util.ArrayList) session.getAttribute("FILTER_SUMMARY_DATA"); selectionCell.setCellValue(new HSSFRichTextString((String) ht.get("arc.current.selection"))); sheet1.addMergedRegion(new Region(rowStart, (short) (colStart), rowStart, (short) (colStart + 5))); int filterSize = 1; if (summaryData != null) { for (int sumCnt = 0; sumCnt < summaryData.size(); sumCnt++) { java.util.ArrayList sumdata = (java.util.ArrayList) summaryData.get(sumCnt); rowStart++; selectionRow = sheet1.createRow((short) rowStart); selectionCell = selectionRow.createCell((short) (colStart)); selectionCell.setCellStyle(excelUtil.getSelectionStyle()); String value = (String) sumdata.get(1); value = value.replaceAll("<span>", ""); value = value.replaceAll("</span>", ""); selectionCell .setCellValue(new HSSFRichTextString(" " + (String) sumdata.get(0) + " -- " + value)); sheet1.addMergedRegion(new Region(rowStart, (short) (colStart), rowStart, (short) (colStart + 10))); } //sheet1.addMergedRegion(new Region(rowStart-summaryData.size(),(short)(colStart),rowStart,(short)(colStart))); filterSize = summaryData.size(); } rowStart++; excelUtil.setPrintAndPageSettings(rowStart + 1, rowStart + 2, (String) ReportUtil.getLabels(session).get(nameKey), rowCells.size() + 3); excelUtil.setStartWidthColumn(rowStart + 1); HSSFCell excel_cell = null; HSSFRow excelRow = sheet1.createRow((short) rowStart); String reportType = ReportDataUtil.getReportType(component); HashMap crossTabDetails = root.getCrossTabReportDetails(); //----- for displaying unit measure by Gowri ----------------- Columns columns = component.getDefinition().getSelect().getColumns(); ArrayList crosstabColumnIds = new ArrayList(); for (int colCnt = 0; colCnt < columns.getColumnCount(); colCnt++) { Column column = columns.getColumn(colCnt); crosstabColumnIds.add(column.getId()); } //------------------------------------------------------------- if (reportType != null && reportType.equalsIgnoreCase(DefaultKernel.CROSSTAB_REPORT_TYPE)) { crosstabColumnIds = (ArrayList) crossTabDetails.get("COLUMN_IDS_LIST"); ArrayList columnList = (ArrayList) crossTabDetails.get("COLUMN_LIST"); ArrayList growingColumns = (ArrayList) crossTabDetails.get(DefaultKernel.XTAB_DYNAMIC); ArrayList staticColumns = (ArrayList) crossTabDetails.get(DefaultKernel.XTAB_STATIC); int noGrowingColumns = growingColumns.size(); int noStaticColumns = staticColumns.size(); int staticColSpan = noStaticColumns; int dynamicColSpan = noGrowingColumns; for (int colCount = 0; colCount < staticColumns.size(); colCount++) { if (nonVisibleCol.contains(new Integer(colCount))) { staticColSpan--; } } for (int colCount = 0; colCount < growingColumns.size(); colCount++) { if (nonVisibleCol.contains(new Integer(colCount + noStaticColumns))) { dynamicColSpan--; } } for (int i = 0; i < columnList.size(); i++) { short cellIndex = (short) (1 + (staticColSpan - 1) + (dynamicColSpan * i)); excel_cell = excelRow.createCell(cellIndex); excel_cell.setCellStyle(excelUtil.getHeaderStyle()); excel_cell.setCellValue(new HSSFRichTextString((String) columnList.get(i))); for (short index = (short) (cellIndex + 1); index < cellIndex + dynamicColSpan; index++) { excel_cell = excelRow.createCell(index); excel_cell.setCellStyle(excelUtil.getHeaderStyle()); } sheet1.addMergedRegion(new Region(rowStart, (short) (cellIndex), rowStart, (short) (cellIndex + dynamicColSpan - 1))); } } rowStart++; sheet1.createFreezePane(2, 12 + filterSize); excelRow = sheet1.createRow((short) rowStart); HashMap hierarchyLevels = root.getHierarchyLevels(); row = (TreeRow) root.getTreeRows().get(0); int colCout = colStart; //Columns columns = component.getDefinition().getSelect().getColumns(); Hashtable measures = com.manthan.promax.db.ApplicationConfig.getAllMeasures(); for (int cellCount = 0; cellCount < row.getRowCells().size(); cellCount++) { ReportCell rCell = (ReportCell) row.getRowCells().get(cellCount); String colId = crosstabColumnIds.get(cellCount).toString(); if (rCell.getVisible()) { String cellValue = rCell.getName(); //----- for displaying unit measure by Gowri ----------------- String unitMeasures = ""; HashMap measure = (HashMap) measures.get(colId); if (null != measure && null != measure.get("COLUMN_TYPE") && measure.get("COLUMN_TYPE").toString().equalsIgnoreCase("currency") && ((measure.get("RULE") != null && !measure.get("RULE").toString().trim().equals("") && measure.get("RULE").toString().indexOf("100") == -1) || (measure.get("DB_COLUMN_NAME") != null && !measure.get("DB_COLUMN_NAME").toString().trim().equals("")) || (measure.get("MEASURE_EXPRESSION") != null && !measure.get("MEASURE_EXPRESSION").toString().trim().equals("")))) { unitMeasures = (session.getAttribute("unitMeasureInDigits") != null && !session.getAttribute("unitMeasureInDigits").toString().equals("1")) ? "[in " + ((String) session.getAttribute("unitMeasureInDigits")).substring(1) + "]" : ""; } //------------------------------------------------------------- excel_cell = excelRow.createCell((short) (colCout)); excel_cell.setCellStyle(excelUtil.getHeaderStyle()); excel_cell.setCellValue(new HSSFRichTextString(cellValue + "\n" + unitMeasures)); colCout++; } } rowStart++; excelRow = sheet1.createRow((short) rowStart); excelRow.setHeightInPoints(20); row = (TreeRow) root.getTreeRows().get(1); HSSFCell totCell = excelRow.createCell((short) colStart); totCell.setCellStyle(excelUtil.getTotalStyle(excelUtil.format(nonCurrItems, 0))); totCell.setCellValue(new HSSFRichTextString(((ReportCell) row.getRowCells().get(0)).getName())); cell = null; colCout = colStart + 1; for (int cellCount = 1; cellCount < row.getRowCells().size(); cellCount++) { cell = (ReportCell) row.getRowCells().get(cellCount); if (cell.getVisible()) { String cellValue = cell.getName(); excel_cell = excelRow.createCell((short) (colCout)); try { double val = Double.parseDouble(cellValue); excel_cell.setCellStyle(excelUtil.getTotalStyle(excelUtil.format(nonCurrItems, cellCount))); excel_cell.setCellValue(val); } catch (NumberFormatException e) { excel_cell.setCellStyle(excelUtil.getTotalStyle(excelUtil.format(nonCurrItems, cellCount))); excel_cell.setCellValue(new HSSFRichTextString(cellValue)); } colCout++; } } count_row = rowStart + 1; writeArcTreeElementToExcel(root, sheet1, excelUtil); excelUtil.getLogo(session.getServletContext()); excelUtil.setWidth(); excelUtil.removeCell(sheet1); HSSFRow compConfidentialRow = sheet1.createRow((short) (count_row + 1)); HSSFCell compConfidentialCell = compConfidentialRow.createCell((short) (0)); compConfidentialCell.setCellStyle(excelUtil.getSelectionStyle()); compConfidentialCell.setCellValue(new HSSFRichTextString((String) ht.get("arc.company.confidential"))); sheet1.addMergedRegion(new Region(count_row + 1, (short) (0), rowStart, (short) (5))); try { wb.write(out); out.flush(); out.close(); } catch (IOException e) { } } public void writeArcTreeElementToExcel(ArcTreeReport node, HSSFSheet sheet1, ExcelUtil excelUtil) { EasyReport component = node.getEasyReport(); String reportType = ReportDataUtil.getReportType(component); HashMap dataformat = null; ArrayList crosstabColumnIds = null; HashMap crossTabDetails = node.getCrossTabReportDetails(); if (reportType != null && reportType.equalsIgnoreCase(DefaultKernel.CROSSTAB_REPORT_TYPE)) { if (crossTabDetails.get("COLUMN_IDS_LIST") != null) { crosstabColumnIds = (ArrayList) crossTabDetails.get("COLUMN_IDS_LIST"); } if (crossTabDetails.get("CROSSTABDATAFORMAT") != null) { dataformat = (HashMap) crossTabDetails.get("CROSSTABDATAFORMAT"); } } ArrayList treeRows = (ArrayList) node.getTreeRows(); TreeRow row = null; ReportCell cell = null; String cellValue = null; int level = 0; int colStart = 0; for (int i = 2; i < treeRows.size(); i++) { row = (TreeRow) treeRows.get(i); level = row.getLevel(); HSSFRow excelRow = sheet1.createRow((short) count_row); count_row = count_row + 1; excelRow.setHeightInPoints(20); HSSFCell dcsCell = excelRow.createCell((short) (colStart)); String space = ""; dcsCell.setCellStyle(excelUtil.getDataTextStyle()); for (int k = 1; k < level; k++) { if (level - 1 == 0) space = ""; else space = space + " "; } cell = (ReportCell) (row.getRowCells()).get(0); String cellVal = space + cell.getName(); dcsCell.setCellValue(new HSSFRichTextString(cellVal)); int count = colStart + 1; for (int j = 1; j < row.getRowCells().size(); j++) { cell = (ReportCell) (row.getRowCells()).get(j); if (cell.getVisible()) { cellValue = cell.getName(); HSSFCell excel_cell = excelRow.createCell((short) (count)); String datatype = ""; try { if (null != component.getDefinition().getReportType() && component.getDefinition().getReportType().equalsIgnoreCase("crosstab")) { datatype = dataformat.get(crosstabColumnIds.get(j).toString()).toString(); } else { datatype = ((Column) component.getDefinition().getSelect().getColumns().getColumn(j)) .getDataFormat(); } double val = Double.parseDouble(cellValue); excel_cell.setCellValue(val); if (datatype.equalsIgnoreCase("currency")) { excel_cell.setCellStyle(excelUtil.getDataStyleFormat()); } else if (datatype.equalsIgnoreCase("number")) { excel_cell.setCellStyle(excelUtil.getDataStyleFormatLess()); } else { excel_cell.setCellValue(new HSSFRichTextString(cellValue)); excel_cell.setCellStyle(excelUtil.firstColStyle()); } } catch (NumberFormatException ee) { excel_cell.setCellStyle(excelUtil.getDataTextStyle()); excel_cell.setCellValue(new HSSFRichTextString(cellValue)); } count++; } } if (row.getChild() != null && row.getState().equalsIgnoreCase(GlobalConstant.EXPANDED)) writeArcTreeElementToExcel(row.getChild(), sheet1, excelUtil); } } // nikhil : method added to export the tree report public void writeExcelToOut(TreeElement root, ServletOutputStream out, HttpSession session, HttpServletRequest req) { /* String reportType = ReportDataUtil.getReportType(component); HashMap crossTabDetails = data.getCrossTabReportDetails(); if (reportType != null && reportType.equalsIgnoreCase(DefaultKernel.CROSSTAB_REPORT_TYPE)) { ArrayList columnList = (ArrayList)crossTabDetails.get("COLUMN_LIST"); ArrayList growingColumns = (ArrayList) crossTabDetails.get(DefaultKernel.XTAB_DYNAMIC); ArrayList staticColumns = (ArrayList) crossTabDetails.get(DefaultKernel.XTAB_STATIC); int noGrowingColumns = growingColumns.size(); int noStaticColumns = staticColumns.size(); int staticColSpan = noStaticColumns; int dynamicColSpan = noGrowingColumns; for(int colCount=0; colCount < staticColumns.size(); colCount++){ if(nonVisibleCol.contains(new Integer(colCount))){ staticColSpan--; } } for(int colCount=noStaticColumns; colCount < growingColumns.size(); colCount++){ if(nonVisibleCol.contains(new Integer(colCount))){ dynamicColSpan--; } } int columnSetSize = columnList.size(); StringBuffer buffer = new StringBuffer(); buffer.append("<tr class='tbhdr'>"); buffer.append("<td colspan="+staticColSpan+"></td>"); for (int i = 0; i < columnList.size(); i++) { buffer.append("<td colspan=" + dynamicColSpan + " align='center'>"); buffer.append(columnList.get(i)); buffer.append("</td>"); } buffer.append("</tr>"); buffer.append("<tr class='tbhdr'>"); header.append(buffer); //vFloaterHeader.append(buffer); // we are getting first row for column headers or column titles }*/ HSSFWorkbook wb = new HSSFWorkbook(); // title of the report HSSFSheet sheet1 = wb.createSheet(root.getParentId()); // iterate through the tree report and then export the data to excel // adding first row as column titles we will get from root HSSFRow excelRow = sheet1.createRow((short) 0); if (req.getParameter("treecountrymdxreporttype") != null) { excelRow.createCell((short) 0).setCellValue(new HSSFRichTextString("Country Name")); excelRow.createCell((short) 1).setCellValue(new HSSFRichTextString("Region Name")); excelRow.createCell((short) 2).setCellValue(new HSSFRichTextString("Sector Name")); excelRow.createCell((short) 3).setCellValue(new HSSFRichTextString("Store Name")); } else { excelRow.createCell((short) 0).setCellValue(new HSSFRichTextString("Department Name")); excelRow.createCell((short) 1).setCellValue(new HSSFRichTextString("Class Name")); excelRow.createCell((short) 2).setCellValue(new HSSFRichTextString("SubClass Name")); excelRow.createCell((short) 3).setCellValue(new HSSFRichTextString("Item Name")); } if (root.getNodeType().equals(TreeBuilder.ROOT_LITERAL)) for (int j = 1; j < root.getColumnTitles().size(); j++) excelRow.createCell((short) (j + 3)) .setCellValue(new HSSFRichTextString((String) root.getColumnTitles().get(j))); // var for counting the row as we have to create row for excel sheet // and we have to make count on that as using nested loop for evry // children for each tree elemnt count_row = 1; writeTreeElementToExcel(root, sheet1); //count_row = count_row+1; //=====> logic to create total row in excel if (root.getTotalRow() != null) { excelRow = sheet1.createRow((short) (count_row)); excelRow.createCell((short) 0).setCellValue(new HSSFRichTextString((String) root.getTotalRow().get(0))); for (int tot = 1; tot < root.getTotalRow().size(); tot++) { try { // nikhil added to get the excel output as number double val = 0; val = Double.parseDouble((String) root.getTotalRow().get(tot)); excelRow.createCell((short) (tot + 3)).setCellValue(val); } catch (Exception e) { excelRow.createCell((short) (tot + 3)) .setCellValue(new HSSFRichTextString((String) root.getTotalRow().get(tot))); } } } /*for (int i = 0; i < root.getChildrenCount(); i++) { TreeElement el = (TreeElement) root.getChildren().get(i); System.out.println("el name" + el.getName()); excelRow = sheet1.createRow( (short) i); //row_count = row_count + 1; for (int j = 0; j < el.getCells().size(); j++) { System.out.println((String) el.getCells(). get(j)); excelRow.createCell( (short) j).setCellValue( (String) el.getCells(). get(j)); } }*/ try { wb.write(out); out.flush(); out.close(); } catch (IOException e) { } } // nikhil : method to write data to excel rows public void writeTreeElementToExcel(TreeElement root, HSSFSheet sheet1) { // we are getting the row_count for first time as 1 and then we have to // increment for every children in first loop so as to create that row in // export try { for (int i = 0; i < root.getChildrenCount(); i++) { TreeElement el = (TreeElement) root.getChildren().get(i); HSSFRow excelRow = sheet1.createRow((short) count_row); count_row = count_row + 1; int start_cells = el.getNestingLevel() - 1; excelRow.createCell((short) start_cells).setCellValue(new HSSFRichTextString(el.getName())); for (int j = 0; j < el.getCells().size(); j++) { double val = 0; try { // nikhil added to get the excel output as number val = Double.parseDouble((String) el.getCells().get(j)); excelRow.createCell((short) (4 + j)).setCellValue(val); } catch (Exception e) { excelRow.createCell((short) (4 + j)) .setCellValue(new HSSFRichTextString((String) el.getCells().get(j))); } } if (el.getChildrenCount() > 0) { writeTreeElementToExcel(el, sheet1); } } } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doPost(req, res); } /*=================================== * I N H E R I T E D * ================================== */ /*=================================== * I M P L E M E N T A T I O N S * ================================== */ /*=================================== * P A T T E R N S U P P O R T * ================================== */ /*================================== * B E A N S U P P O R T * ================================== */ /*=================================== * P R O P E R T I E S * ================================== */ } /* * $Author: fourfive $ * $Log: TreeServlet.java,v $ * Revision 1.5 2004/06/14 10:00:11 fourfive * extended live debug capabilities. * * Revision 1.4 2004/01/30 08:21:37 fourfive * added cvs tags. * */