PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/myproject/src/com/bp/pensionline/sqlreport/app/poi/PLReportPOIProducer.java

https://bitbucket.org/tuannguyen/mytest
Java | 368 lines | 261 code | 68 blank | 39 comment | 28 complexity | 63a273d409ae831d3fa6baba9e6bcd31 MD5 | raw file
  1. package com.bp.pensionline.sqlreport.app.poi;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.OutputStreamWriter;
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.ResultSetMetaData;
  13. import java.sql.SQLException;
  14. import java.util.Scanner;
  15. import org.apache.commons.logging.Log;
  16. import org.apache.poi.hssf.usermodel.HSSFCell;
  17. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  18. import org.apache.poi.hssf.usermodel.HSSFFont;
  19. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  20. import org.apache.poi.hssf.usermodel.HSSFRow;
  21. import org.apache.poi.hssf.usermodel.HSSFSheet;
  22. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  23. import org.apache.poi.hssf.util.HSSFColor;
  24. import org.opencms.main.CmsLog;
  25. import com.bp.pensionline.database.DBConnector;
  26. public class PLReportPOIProducer
  27. {
  28. public static final Log LOG = CmsLog.getLog(PLReportPOIProducer.class);
  29. /**
  30. * Generate a report section with data source and query provided
  31. * @param dataSource
  32. * @param query
  33. * @return
  34. */
  35. public HSSFWorkbook generateReportSectionToXLS(String database, String query)
  36. {
  37. HSSFWorkbook workBook = null;
  38. Connection connection = null;
  39. try
  40. {
  41. connection = DBConnector.getInstance().establishConnection(database);
  42. System.out.println("connection: " + connection);
  43. }
  44. catch (SQLException sqle)
  45. {
  46. LOG.error("Error in establishing SQL connection to " + database + ": " + sqle.toString());
  47. }
  48. // get the template file
  49. try
  50. {
  51. if (connection != null && query != null)
  52. {
  53. workBook = new HSSFWorkbook ();
  54. HSSFSheet sheet = workBook.createSheet();
  55. HSSFCellStyle cellStyleHeader = workBook.createCellStyle();
  56. cellStyleHeader.setWrapText(true);
  57. cellStyleHeader.setVerticalAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
  58. cellStyleHeader.setFillForegroundColor(HSSFColor.GREEN.index);
  59. cellStyleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  60. HSSFFont headerCellFont = workBook.createFont();
  61. headerCellFont.setFontHeightInPoints((short)10);
  62. headerCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  63. headerCellFont.setColor(HSSFColor.WHITE.index);
  64. cellStyleHeader.setFont(headerCellFont);
  65. HSSFCellStyle cellStyleData = workBook.createCellStyle();
  66. cellStyleData.setWrapText(true);
  67. cellStyleData.setVerticalAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
  68. HSSFFont dataCellFont = workBook.createFont();
  69. dataCellFont.setFontHeightInPoints((short)10);
  70. dataCellFont.setColor(HSSFColor.GREY_80_PERCENT.index);
  71. cellStyleData.setFont(dataCellFont);
  72. /*
  73. * Start generate the report
  74. */
  75. PreparedStatement pstm = connection.prepareStatement(query);
  76. ResultSet rs = pstm.executeQuery();
  77. // get column names from ResutlSet MetaData
  78. ResultSetMetaData rsMD = rs.getMetaData();
  79. int numCols = rsMD.getColumnCount();
  80. String[] columnClassNames = new String[numCols];
  81. // generate header
  82. int rowIndex = 0;
  83. HSSFRow headerRow = sheet.createRow(0);
  84. HSSFCell headerCell = null;
  85. for (int i = 0; i < numCols; i++)
  86. {
  87. String colName = rsMD.getColumnName(i + 1);
  88. //System.out.println("colName: " + colName);
  89. String className = rsMD.getColumnClassName(i + 1);
  90. if (className != null){
  91. if(className.equals("java.math.BigInteger"))
  92. className = "java.lang.Long";
  93. if(className.equals("java.sql.Clob"))
  94. className = "java.lang.String";
  95. }
  96. columnClassNames[i] = className;
  97. headerCell = headerRow.createCell(i);
  98. headerCell.setCellStyle(cellStyleHeader);
  99. headerCell.setCellValue(new HSSFRichTextString(colName));
  100. }
  101. // generate data rows
  102. rowIndex++;
  103. while (rs.next())
  104. {
  105. System.out.println("Add row: " + rowIndex);
  106. HSSFRow row = sheet.createRow(rowIndex++);
  107. for (int i = 0; i < columnClassNames.length; i++)
  108. {
  109. HSSFCell dataCell = row.createCell(i);
  110. String dataCellContent = rs.getString(i + 1);
  111. dataCell.setCellStyle(cellStyleData);
  112. sheet.autoSizeColumn((short)i);
  113. dataCell.setCellValue(new HSSFRichTextString(dataCellContent));
  114. }
  115. }
  116. }
  117. }
  118. catch (Exception e)
  119. {
  120. LOG.error("Error while generating regulations to XLS: " + e.toString());
  121. }
  122. return workBook;
  123. }
  124. public byte[] generateReportSectionToCSV (String database, String query)
  125. {
  126. Connection connection = null;
  127. byte[] content = null;
  128. try
  129. {
  130. connection = getDBConn(database);//DBConnector.getInstance().establishConnection(database);
  131. System.out.println("connection: " + connection);
  132. }
  133. catch (SQLException sqle)
  134. {
  135. LOG.error("Error in establishing SQL connection to " + database + ": " + sqle.toString());
  136. }
  137. // get the template file
  138. try
  139. {
  140. if (connection != null && query != null)
  141. {
  142. ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
  143. OutputStreamWriter streamWriter = new OutputStreamWriter(byteOutputStream);
  144. /*
  145. * Start generate the report
  146. */
  147. PreparedStatement pstm = connection.prepareStatement(query);
  148. ResultSet rs = pstm.executeQuery();
  149. // get column names from ResutlSet MetaData
  150. ResultSetMetaData rsMD = rs.getMetaData();
  151. int numCols = rsMD.getColumnCount();
  152. String[] columnClassNames = new String[numCols];
  153. // generate header
  154. int rowIndex = 0;
  155. StringBuffer headerRow = new StringBuffer();
  156. for (int i = 0; i < numCols; i++)
  157. {
  158. String colName = rsMD.getColumnName(i + 1);
  159. //System.out.println("colName: " + colName);
  160. String className = rsMD.getColumnClassName(i + 1);
  161. if (className != null){
  162. if(className.equals("java.math.BigInteger"))
  163. className = "java.lang.Long";
  164. if(className.equals("java.sql.Clob"))
  165. className = "java.lang.String";
  166. }
  167. columnClassNames[i] = className;
  168. headerRow.append("\"" + colName + "\"");
  169. if (i < numCols - 1)
  170. {
  171. headerRow.append(",");
  172. }
  173. }
  174. headerRow.append("\n");
  175. streamWriter.write(headerRow.toString());
  176. // generate data rows
  177. rowIndex++;
  178. while (rs.next())
  179. {
  180. StringBuffer dataRow = new StringBuffer();
  181. System.out.println("Add row: " + rowIndex);
  182. for (int i = 0; i < columnClassNames.length; i++)
  183. {
  184. String dataCellContent = rs.getString(i + 1);
  185. dataRow.append("\"" + dataCellContent + "\"");
  186. if (i < numCols - 1)
  187. {
  188. dataRow.append(",");
  189. }
  190. }
  191. dataRow.append("\n");
  192. streamWriter.write(dataRow.toString());
  193. rowIndex++;
  194. }
  195. streamWriter.flush();
  196. content = byteOutputStream.toByteArray();
  197. //byteOutputStream.close();
  198. }
  199. }
  200. catch (Exception e)
  201. {
  202. LOG.error("Error while generating regulations to XLS: " + e.toString());
  203. }
  204. return content;
  205. }
  206. public static void main(String[] args)
  207. {
  208. PLReportPOIProducer producer = new PLReportPOIProducer();
  209. String query = producer.readQueryFromFile("F:/before_se.txt");
  210. byte[] content = producer.generateReportSectionToCSV("aquila", query);
  211. if (content != null)
  212. {
  213. try
  214. {
  215. producer.outputToFileSystem("F:/section.csv", content);
  216. System.out.println("Export Done!");
  217. }
  218. catch (Exception e)
  219. {
  220. e.printStackTrace();
  221. }
  222. }
  223. }
  224. private Connection getDBConn(String jndiEnv) throws SQLException{
  225. Connection conn = null;
  226. try {
  227. //log.info("Create a new connection for DBConnector, OracleConnectionCacheImpl");
  228. /* Create an instance of ConnCacheBean */
  229. // ConnCacheBean connCacheBean = ConnCacheBean.getInstance();
  230. //
  231. // /* Get OracleDataSource from the ConnCacheBean */
  232. // OracleDataSource ods = connCacheBean.getDataSource();
  233. String driverName = "oracle.jdbc.driver.OracleDriver";
  234. Class.forName(driverName);
  235. // String url = CheckConfigurationKey.getStringValue("calcURL");
  236. // String userName = CheckConfigurationKey.getStringValue("calcUserName");
  237. // String password = CheckConfigurationKey.getStringValue("calcPassword");
  238. // conn = DriverManager.getConnection(url, userName, password);
  239. conn = DriverManager.getConnection("jdbc:oracle:thin:@127.1.1.204:4522:BP101S", "BPPL4CMS", "BPPL4CMS");
  240. }
  241. catch (Exception ex) {
  242. //LOG.error("Get a connection from ods is fail", ex);
  243. ex.printStackTrace();
  244. }
  245. return conn;
  246. }
  247. /**
  248. *
  249. * @param fileName
  250. * @return
  251. */
  252. private String readQueryFromFile (String fileName)
  253. {
  254. String query = null;
  255. StringBuffer queryBuffer = null;
  256. try
  257. {
  258. File queryFile = new File(fileName);
  259. if (queryFile.exists())
  260. {
  261. queryBuffer = new StringBuffer();
  262. FileInputStream queryFileInputStream = new FileInputStream(queryFile);
  263. String NL = System.getProperty("line.separator");
  264. Scanner scanner = new Scanner(queryFileInputStream, "UTF-8");
  265. try
  266. {
  267. while (scanner.hasNextLine())
  268. {
  269. queryBuffer.append(scanner.nextLine() + NL);
  270. }
  271. }
  272. finally
  273. {
  274. scanner.close();
  275. }
  276. query = queryBuffer.toString();
  277. }
  278. }
  279. catch (Exception e)
  280. {
  281. LOG.error("Error while reading query from " + fileName + ": " + e.toString());
  282. }
  283. return query;
  284. }
  285. private void outputToFileSystem(String fileName, HSSFWorkbook workbook) throws IOException
  286. {
  287. File outputFile = new File(fileName);
  288. FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
  289. workbook.write(fileOutputStream);
  290. fileOutputStream.close();
  291. }
  292. public void outputToFileSystem(String fileName, byte[] reportContent) throws IOException
  293. {
  294. File outputFile = new File(fileName);
  295. FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
  296. fileOutputStream.write(reportContent);
  297. fileOutputStream.flush();
  298. fileOutputStream.close();
  299. }
  300. }