問題: 用java生成圖片上傳到linux服務器,中文出現亂碼問題解決
思路: 查看本地java字符集編碼格式 查看linux服務器字符集編碼 如果編碼格式不一致會導致程序在服務器運行時報錯
解決: 1、查看linux服務器字符集編碼格式: echo $LANG
修改linux服務器字符集編碼格式的命令:
1、用root用戶登錄服務器 export LANG=zh_CN.UTF-8
2、vim /etc/sysconfig/i18n 修改LANG="zh_CN.UTF-8" source /etc/sysconfig/i18n
查看linux環境可編譯字符集的命令:
1、fc-list|grep 宋
2、fc-list :lang=zh-cn | sort
3、查看之后加入不存在漢字編碼字符集,可以將windows環境的字符集編碼腳本上傳到linux環境
C:\Windows\Fonts下找到字體文件simsun.ttc,重命名為simsun.ttf;
在linux服務器/usr/share/fonts/ 路徑下創建fallback文件夾,如果后期有問題,可能是文件夾名稱有問題,可以修改為zh_CN嘗試
修改文件權限755 chmod 775 fallback
mkfontscale (如果提示 mkfontscale: command not found,需自行安裝 # yum install mkfontscale )
mkfontdir
fc-cache -fv (如果提示 fc-cache: command not found,則需要安裝# yum install fontconfig )或 fc-cache /usr/share/fonts/zh_CN/
上述三個命令必須要執行,否則上傳的腳本無法正常使用
fc-list :lang=zh-cn | sort 查看字符集編譯是否成功
重啟服務器
用java生成圖片的源碼 :
package com.sinosoft.tphi.task.mail; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.Charset; import java.text.ParseException; import java.util.Arrays; import org.apache.log4j.Logger; import com.sinosoft.utility.CErrors; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * author: wcg * time: 2019-05-17 * funnction: 生成發送郵件的圖片 * */ public class ImageUtilCommon { public CErrors mErrors = new CErrors(); private final Logger logger = Logger.getLogger("ImageUtilCommon"); /** * 生成發送郵件的圖片 * */ public boolean myGraphicsGeneration(String cellsValue[][], String path) { String csn = Charset.defaultCharset().name(); System.out.println("字符集"+csn); System.out.println("=======開始生成圖片============"); System.out.println(Arrays.deepToString(cellsValue)); // 字體大小 int fontTitileSize = 11; // 橫線的行數 int totalrow = cellsValue.length+1; // 豎線的行數 int totalcol = 0; if (cellsValue[0] != null) { totalcol = cellsValue[0].length; } // 圖片寬度 int imageWidth = 1024; // 行高 int rowheight = 40; //圖片高度 int imageHeight = totalrow*rowheight+50; // 起始高度 int startHeight = 10; // 起始寬度 int startWidth = 10; //單元格寬度 int colwidth = (int)((imageWidth-20)/totalcol); BufferedImage image = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB); Graphics graphics = image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0,0, imageWidth, imageHeight); graphics.setColor(new Color(220,240,240)); //畫橫線 for(int j=0;j<totalrow; j++){ graphics.setColor(Color.black); graphics.drawLine(startWidth, startHeight+(j+1)*rowheight, startWidth+colwidth*totalcol, startHeight+(j+1)*rowheight); } //畫豎線 for(int k=0;k<totalcol+1;k++){ graphics.setColor(Color.black); graphics.drawLine(startWidth+k*colwidth, startHeight+rowheight, startWidth+k*colwidth, startHeight+rowheight*totalrow); } //設置字體 Font font = new Font("微軟雅黑",Font.BOLD,fontTitileSize); graphics.setFont(font); //寫標題 String title = "【報送批次查詢結果】"; graphics.drawString(title, startWidth, startHeight+rowheight-10); //寫入內容 for(int n=0;n<cellsValue.length;n++){ for(int l=0;l<cellsValue[n].length;l++){ if (n == 0) { font = new Font("微軟雅黑",Font.BOLD,fontTitileSize); graphics.setFont(font); }else if (n > 0 && l >0) { font = new Font("微軟雅黑",Font.PLAIN,fontTitileSize); graphics.setFont(font); graphics.setColor(Color.RED); } else { font = new Font("微軟雅黑",Font.PLAIN,fontTitileSize); graphics.setFont(font); graphics.setColor(Color.BLACK); } graphics.drawString(cellsValue[n][l].toString(), startWidth+colwidth*l+5, startHeight+rowheight*(n+2)-10); } } // 保存圖片 System.out.println("++輸出文件的生成路勁+++"+path); delAllFile(path); createImage(image, path); System.out.println("+++調用createImage++++"); return true; } /** * 用IO流將圖片寫入到指定目錄下面 * * @param image * @param fileLocation */ public void createImage(BufferedImage image, String fileLocation) { try { System.out.println("+++調用createImage++6666++"); FileOutputStream fos = new FileOutputStream(fileLocation); BufferedOutputStream bos = new BufferedOutputStream(fos); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); encoder.encode(image); bos.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 清空存放圖片的文件夾 * * */ public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } temp.delete(); } return true; } public static void main(String[] args) throws ParseException{ /*MonitorWaiSubmit mMonitorWaiSubmit = new MonitorWaiSubmit(); mMonitorWaiSubmit.submitData("");*/ String csn = Charset.defaultCharset().name(); System.out.println("字符集"+csn); } }
用java生成統計圖源碼:
package com.sinosoft.tphi.task.mail; import java.awt.Color; import java.awt.Font; import java.io.File; import java.io.FileOutputStream; import java.text.DecimalFormat; import java.text.NumberFormat; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardPieSectionLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot3D; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.chart.renderer.category.StackedBarRenderer; import org.jfree.chart.title.TextTitle; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; /** * 壓力點測試工具類 * @author WangLiping */ public class SendEmailTest3 { private static final String CHART_PATH = "E://"; /** * 測試 * @param args * @author WangLiping */ public static void main(String[] args) { // TODO Auto-generated method stub SendEmailTest3 pm = new SendEmailTest3(); // 生成餅狀圖 pm.makePieChart(); // 生成單組柱狀圖 /* pm.makeBarChart(); // 生成多組柱狀圖 pm.makeBarGroupChart(); // 生成堆積柱狀圖 pm.makeStackedBarChart(); // 生成折線圖 pm.makeLineAndShapeChart();*/ } /** * 生成折線圖 */ public void makeLineAndShapeChart() { double[][] data = new double[][] { { 672, 766, 223, 540, 126 }, { 325, 521, 210, 340, 106 }, { 332, 256, 523, 240, 526 } }; String[] rowKeys = { "蘋果", "梨子", "葡萄" }; String[] columnKeys = { "北京", "上海", "廣州", "成都", "深圳" }; CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createTimeXYChar("折線圖", "x軸", "y軸", dataset, "lineAndShap.jpg"); } /** * 生成分組的柱狀圖 */ public void makeBarGroupChart() { double[][] data = new double[][] { { 672, 766, 223, 540, 126 }, { 325, 521, 210, 340, 106 }, { 332, 256, 523, 240, 526 } }; String[] rowKeys = { "蘋果", "梨子", "葡萄" }; String[] columnKeys = { "北京", "上海", "廣州", "成都", "深圳" }; CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐標", "y坐標", "柱狀圖", "barGroup.png"); } /** * 生成柱狀圖 */ public void makeBarChart() { double[][] data = new double[][] { { 672, 766, 223, 540, 126 } }; String[] rowKeys = { "蘋果" }; String[] columnKeys = { "北京", "上海", "廣州", "成都", "深圳" }; CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐標", "y坐標", "柱狀圖", "bar.png"); } /** * 生成堆棧柱狀圖 */ public void makeStackedBarChart() { double[][] data = new double[][] { { 0.21, 0.66, 0.23, 0.40, 0.26 }, { 0.25, 0.21, 0.10, 0.40, 0.16 } }; String[] rowKeys = { "蘋果", "梨子" }; String[] columnKeys = { "北京", "上海", "廣州", "成都", "深圳" }; CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createStackedBarChart(dataset, "x坐標", "y坐標", "柱狀圖", "stsckedBar.png"); } /** * 生成餅狀圖 */ public void makePieChart() { double[] data = { 9, 91 }; String[] keys = { "失敗率", "成功率" }; createValidityComparePimChar(getDataPieSetByUtil(data, keys), "餅狀圖", "pie2.png", keys); } // 柱狀圖,折線圖 數據集 public CategoryDataset getBarData(double[][] data, String[] rowKeys, String[] columnKeys) { return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); } // 餅狀圖 數據集 public PieDataset getDataPieSetByUtil(double[] data, String[] datadescription) { if (data != null && datadescription != null) { if (data.length == datadescription.length) { DefaultPieDataset dataset = new DefaultPieDataset(); for (int i = 0; i < data.length; i++) { dataset.setValue(datadescription[i], data[i]); } return dataset; } } return null; } /** * 柱狀圖 * *@param dataset * 數據集 * @param xName * x軸的說明(如種類,時間等) * @param yName * y軸的說明(如速度,時間等) * @param chartTitle * 圖標題 * @param charName * 生成圖片的名字 * @return */ public String createBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle, String charName) { JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 圖表標題 xName, // 目錄軸的顯示標簽 yName, // 數值軸的顯示標簽 dataset, // 數據集 PlotOrientation.VERTICAL, // 圖表方向:水平、垂直 true, // 是否顯示圖例(對於簡單的柱狀圖必須是false) false, // 是否生成工具 false // 是否生成URL鏈接 ); Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); /* * VALUE_TEXT_ANTIALIAS_OFF表示將文字的抗鋸齒關閉, * 使用的關閉抗鋸齒后,字體盡量選擇12到14號的宋體字,這樣文字最清晰好看 */ // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.white); // create plot CategoryPlot plot = chart.getCategoryPlot(); // 設置橫虛線可見 plot.setRangeGridlinesVisible(true); // 虛線色彩 plot.setRangeGridlinePaint(Color.gray); // 數據軸精度 NumberAxis vn = (NumberAxis) plot.getRangeAxis(); // vn.setAutoRangeIncludesZero(true); DecimalFormat df = new DecimalFormat("#0.00"); vn.setNumberFormatOverride(df); // 數據軸數據標簽的顯示格式 // x軸設置 CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabelFont(labelFont);// 軸標題 domainAxis.setTickLabelFont(labelFont);// 軸數值 // Lable(Math.PI/3.0)度傾斜 // domainAxis.setCategoryLabelPositions(CategoryLabelPositions // .createUpRotationLabelPositions(Math.PI / 3.0)); domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 橫軸上的 Lable 是否完整顯示 // 設置距離圖片左端距離 domainAxis.setLowerMargin(0.1); // 設置距離圖片右端距離 domainAxis.setUpperMargin(0.1); // 設置 columnKey 是否間隔顯示 // domainAxis.setSkipCategoryLabelsToFit(true); plot.setDomainAxis(domainAxis); // 設置柱圖背景色(注意,系統取色的時候要使用16位的模式來查看顏色編碼,這樣比較准確) plot.setBackgroundPaint(new Color(255, 255, 204)); // y軸設置 ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setLabelFont(labelFont); rangeAxis.setTickLabelFont(labelFont); // 設置最高的一個 Item 與圖片頂端的距離 rangeAxis.setUpperMargin(0.15); // 設置最低的一個 Item 與圖片底端的距離 rangeAxis.setLowerMargin(0.15); plot.setRangeAxis(rangeAxis); BarRenderer renderer = new BarRenderer(); // 設置柱子寬度 renderer.setMaximumBarWidth(0.05); // 設置柱子高度 renderer.setMinimumBarLength(0.2); // 設置柱子邊框顏色 renderer.setBaseOutlinePaint(Color.BLACK); // 設置柱子邊框可見 renderer.setDrawBarOutline(true); // // 設置柱的顏色 renderer.setSeriesPaint(0, new Color(204, 255, 255)); renderer.setSeriesPaint(1, new Color(153, 204, 255)); renderer.setSeriesPaint(2, new Color(51, 204, 204)); // 設置每個地區所包含的平行柱的之間距離 renderer.setItemMargin(0.0); // 顯示每個柱的數值,並修改該數值的字體屬性 renderer.setIncludeBaseInRange(true); renderer .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true); plot.setRenderer(renderer); // 設置柱的透明度 plot.setForegroundAlpha(1.0f); FileOutputStream fos_jpg = null; try { isChartPathExist(CHART_PATH); String chartName = CHART_PATH + charName; fos_jpg = new FileOutputStream(chartName); ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10); return chartName; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 橫向圖 * * @param dataset * 數據集 * @param xName * x軸的說明(如種類,時間等) * @param yName * y軸的說明(如速度,時間等) * @param chartTitle * 圖標題 * @param charName * 生成圖片的名字 * @return */ public String createHorizontalBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle, String charName) { JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 圖表標題 xName, // 目錄軸的顯示標簽 yName, // 數值軸的顯示標簽 dataset, // 數據集 PlotOrientation.VERTICAL, // 圖表方向:水平、垂直 true, // 是否顯示圖例(對於簡單的柱狀圖必須是false) false, // 是否生成工具 false // 是否生成URL鏈接 ); CategoryPlot plot = chart.getCategoryPlot(); // 數據軸精度 NumberAxis vn = (NumberAxis) plot.getRangeAxis(); // 設置刻度必須從0開始 // vn.setAutoRangeIncludesZero(true); DecimalFormat df = new DecimalFormat("#0.00"); vn.setNumberFormatOverride(df); // 數據軸數據標簽的顯示格式 CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的 // Lable Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); domainAxis.setLabelFont(labelFont);// 軸標題 domainAxis.setTickLabelFont(labelFont);// 軸數值 domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 橫軸上的 Lable 是否完整顯示 // domainAxis.setVerticalCategoryLabels(false); plot.setDomainAxis(domainAxis); ValueAxis rangeAxis = plot.getRangeAxis(); // 設置最高的一個 Item 與圖片頂端的距離 rangeAxis.setUpperMargin(0.15); // 設置最低的一個 Item 與圖片底端的距離 rangeAxis.setLowerMargin(0.15); plot.setRangeAxis(rangeAxis); BarRenderer renderer = new BarRenderer(); // 設置柱子寬度 renderer.setMaximumBarWidth(0.03); // 設置柱子高度 renderer.setMinimumBarLength(30); renderer.setBaseOutlinePaint(Color.BLACK); // 設置柱的顏色 renderer.setSeriesPaint(0, Color.GREEN); renderer.setSeriesPaint(1, new Color(0, 0, 255)); // 設置每個地區所包含的平行柱的之間距離 renderer.setItemMargin(0.5); // 顯示每個柱的數值,並修改該數值的字體屬性 renderer .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); // 設置柱的數值可見 renderer.setBaseItemLabelsVisible(true); plot.setRenderer(renderer); // 設置柱的透明度 plot.setForegroundAlpha(0.6f); FileOutputStream fos_jpg = null; try { isChartPathExist(CHART_PATH); String chartName = CHART_PATH + charName; fos_jpg = new FileOutputStream(chartName); ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10); return chartName; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 餅狀圖 * * @param dataset * 數據集 * @param chartTitle * 圖標題 * @param charName * 生成圖的名字 * @param pieKeys * 分餅的名字集 * @return */ public String createValidityComparePimChar(PieDataset dataset, String chartTitle, String charName, String[] pieKeys) { JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // chart // title dataset,// data true,// include legend true, false); // 使下說明標簽字體清晰,去鋸齒類似於 // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);的效果 chart.setTextAntiAlias(false); // 圖片背景色 chart.setBackgroundPaint(Color.white); // 設置圖標題的字體重新設置title Font font = new Font("隸書", Font.BOLD, 25); TextTitle title = new TextTitle(chartTitle); title.setFont(font); chart.setTitle(title); PiePlot3D plot = (PiePlot3D) chart.getPlot(); // 圖片中顯示百分比:默認方式 // 指定餅圖輪廓線的顏色 // plot.setBaseSectionOutlinePaint(Color.BLACK); // plot.setBaseSectionPaint(Color.BLACK); // 設置無數據時的信息 plot.setNoDataMessage("無對應的數據,請重新查詢。"); // 設置無數據時的信息顯示顏色 plot.setNoDataMessagePaint(Color.red); // 圖片中顯示百分比:自定義方式,{0} 表示選項, {1} 表示數值, {2} 表示所占比例 ,小數點后兩位 plot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0}={1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%"))); // 圖例顯示百分比:自定義方式, {0} 表示選項, {1} 表示數值, {2} 表示所占比例 plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator( "{0}={1}({2})")); plot.setLabelFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12)); // 指定圖片的透明度(0.0-1.0) plot.setForegroundAlpha(0.65f); // 指定顯示的餅圖上圓形(false)還橢圓形(true) plot.setCircular(false, true); // 設置第一個 餅塊section 的開始位置,默認是12點鍾方向 plot.setStartAngle(90); // // 設置分餅顏色 plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144)); plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144)); FileOutputStream fos_jpg = null; try { // 文件夾不存在則創建 isChartPathExist(CHART_PATH); String chartName = CHART_PATH + charName; fos_jpg = new FileOutputStream(chartName); // 高寬的設置影響橢圓餅圖的形狀 ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 230); return chartName; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); System.out.println("create pie-chart."); } catch (Exception e) { e.printStackTrace(); } } } /** * 判斷文件夾是否存在,如果不存在則新建 * * @param chartPath */ private void isChartPathExist(String chartPath) { File file = new File(chartPath); if (!file.exists()) { file.mkdirs(); // log.info("CHART_PATH="+CHART_PATH+"create."); } } /** * 折線圖 * * @param chartTitle * @param x * @param y * @param xyDataset * @param charName * @return */ public String createTimeXYChar(String chartTitle, String x, String y, CategoryDataset xyDataset, String charName) { JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y, xyDataset, PlotOrientation.VERTICAL, true, true, false); chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.WHITE); // 設置圖標題的字體重新設置title Font font = new Font("隸書", Font.BOLD, 25); TextTitle title = new TextTitle(chartTitle); title.setFont(font); chart.setTitle(title); // 設置面板字體 Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); chart.setBackgroundPaint(Color.WHITE); CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); // x軸 // 分類軸網格是否可見 categoryplot.setDomainGridlinesVisible(true); // y軸 //數據軸網格是否可見 categoryplot.setRangeGridlinesVisible(true); categoryplot.setRangeGridlinePaint(Color.WHITE);// 虛線色彩 categoryplot.setDomainGridlinePaint(Color.WHITE);// 虛線色彩 categoryplot.setBackgroundPaint(Color.lightGray); // 設置軸和面板之間的距離 // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); CategoryAxis domainAxis = categoryplot.getDomainAxis(); domainAxis.setLabelFont(labelFont);// 軸標題 domainAxis.setTickLabelFont(labelFont);// 軸數值 domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的 // Lable // 45度傾斜 // 設置距離圖片左端距離 domainAxis.setLowerMargin(0.0); // 設置距離圖片右端距離 domainAxis.setUpperMargin(0.0); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); numberaxis.setAutoRangeIncludesZero(true); // 獲得renderer 注意這里是下嗍造型到lineandshaperenderer!! LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot .getRenderer(); lineandshaperenderer.setBaseShapesVisible(true); // series 點(即數據點)可見 lineandshaperenderer.setBaseLinesVisible(true); // series 點(即數據點)間有連線可見 // 顯示折點數據 // lineandshaperenderer.setBaseItemLabelGenerator(new // StandardCategoryItemLabelGenerator()); // lineandshaperenderer.setBaseItemLabelsVisible(true); FileOutputStream fos_jpg = null; try { isChartPathExist(CHART_PATH); String chartName = CHART_PATH + charName; fos_jpg = new FileOutputStream(chartName); // 將報表保存為png文件 ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 510); return chartName; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); System.out.println("create time-createTimeXYChar."); } catch (Exception e) { e.printStackTrace(); } } } /** * 堆棧柱狀圖 * * @param dataset * @param xName * @param yName * @param chartTitle * @param charName * @return */ public String createStackedBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle, String charName) { // 1:得到 CategoryDataset // 2:JFreeChart對象 JFreeChart chart = ChartFactory.createStackedBarChart(chartTitle, // 圖表標題 xName, // 目錄軸的顯示標簽 yName, // 數值軸的顯示標簽 dataset, // 數據集 PlotOrientation.VERTICAL, // 圖表方向:水平、垂直 true, // 是否顯示圖例(對於簡單的柱狀圖必須是false) false, // 是否生成工具 false // 是否生成URL鏈接 ); // 圖例字體清晰 chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.WHITE); // 2 .2 主標題對象 主標題對象是 TextTitle 類型 chart .setTitle(new TextTitle(chartTitle, new Font("隸書", Font.BOLD, 25))); // 2 .2.1:設置中文 // x,y軸坐標字體 Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); // 2 .3 Plot 對象 Plot 對象是圖形的繪制結構對象 CategoryPlot plot = chart.getCategoryPlot(); // 設置橫虛線可見 plot.setRangeGridlinesVisible(true); // 虛線色彩 plot.setRangeGridlinePaint(Color.gray); // 數據軸精度 NumberAxis vn = (NumberAxis) plot.getRangeAxis(); // 設置最大值是1 vn.setUpperBound(1); // 設置數據軸坐標從0開始 // vn.setAutoRangeIncludesZero(true); // 數據顯示格式是百分比 DecimalFormat df = new DecimalFormat("0.00%"); vn.setNumberFormatOverride(df); // 數據軸數據標簽的顯示格式 // DomainAxis (區域軸,相當於 x 軸), RangeAxis (范圍軸,相當於 y 軸) CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabelFont(labelFont);// 軸標題 domainAxis.setTickLabelFont(labelFont);// 軸數值 // x軸坐標太長,建議設置傾斜,如下兩種方式選其一,兩種效果相同 // 傾斜(1)橫軸上的 Lable 45度傾斜 // domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 傾斜(2)Lable(Math.PI 3.0)度傾斜 // domainAxis.setCategoryLabelPositions(CategoryLabelPositions // .createUpRotationLabelPositions(Math.PI / 3.0)); domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 橫軸上的 Lable 是否完整顯示 plot.setDomainAxis(domainAxis); // y軸設置 ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setLabelFont(labelFont); rangeAxis.setTickLabelFont(labelFont); // 設置最高的一個 Item 與圖片頂端的距離 rangeAxis.setUpperMargin(0.15); // 設置最低的一個 Item 與圖片底端的距離 rangeAxis.setLowerMargin(0.15); plot.setRangeAxis(rangeAxis); // Renderer 對象是圖形的繪制單元 StackedBarRenderer renderer = new StackedBarRenderer(); // 設置柱子寬度 renderer.setMaximumBarWidth(0.05); // 設置柱子高度 renderer.setMinimumBarLength(0.1); // 設置柱的邊框顏色 renderer.setBaseOutlinePaint(Color.BLACK); // 設置柱的邊框可見 renderer.setDrawBarOutline(true); // // 設置柱的顏色(可設定也可默認) renderer.setSeriesPaint(0, new Color(204, 255, 204)); renderer.setSeriesPaint(1, new Color(255, 204, 153)); // 設置每個地區所包含的平行柱的之間距離 renderer.setItemMargin(0.4); plot.setRenderer(renderer); // 設置柱的透明度(如果是3D的必須設置才能達到立體效果,如果是2D的設置則使顏色變淡) // plot.setForegroundAlpha(0.65f); FileOutputStream fos_jpg = null; try { isChartPathExist(CHART_PATH); String chartName = CHART_PATH + charName; fos_jpg = new FileOutputStream(chartName); ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10); return chartName; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); } catch (Exception e) { e.printStackTrace(); } } } }
java發送郵件的類源碼:
package com.sinosoft.tphi.task.mail; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.log4j.Logger; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.ExeSQL; import com.sinosoft.utility.SSRS; import com.sinosoft.utility.TransferData; public class EmailUtilCommon { /** * @param 發送郵件的工具類 * @author wcg * @time 2019-04-11 */ private TransferData mTransferData = new TransferData(); private final String tport = "mail.host"; private final String tprotocol = "mail.transport.protocol"; private final String tauth = "mail.smtp.auth"; private final Logger logger = Logger.getLogger("SentMailTest"); private String mport = ""; private String mprotocol = ""; private String mauth = ""; private String msusername = ""; private String mpassword = ""; private String mRusername = ""; private String mTransdate = ""; private String mBatchno = ""; private String mMSG = ""; private String mErrorAtio = ""; private List<String> tList = new ArrayList<String>(); public CErrors mErrors = new CErrors(); private Transport ts; private static String mas = null; private static String title = null; private static String path = null; public boolean submitData(String mas ,String title,String path) { this.mas = mas; this.title = title; this.path = path; if (!checkData()) { CError tError = new CError(); tError.moduleName = "DealBatchData"; tError.functionName = "checkData"; tError.errorMessage = "輸入有誤,開始時間大於結束時間!"; this.mErrors.addOneError(tError); return false; } // 查詢數據推送情況 logger.info("===========>>>==開始進行郵件發送操作,當前時間:"+java.util.Calendar.getInstance().getTime()); if (!dealData()) { logger.info("===========>>>==郵件發送操作結束!結束時間:"+java.util.Calendar.getInstance().getTime()); return false; } logger.info("===========>>>==成功發送郵件!結束時間:"+java.util.Calendar.getInstance().getTime()); return true; } private boolean dealData() { String tSQL = ""; ExeSQL tExeSQL = new ExeSQL(); /** * 查詢郵箱服務器的ip地址 * */ tSQL = "select sysvarvalue from ldsysvar where sysvar='EmailPortServiceType'"; mport = tExeSQL.getOneValue(tSQL); System.out.println("=======mport====="+mport); if (mport == null || mport.equals("")) { CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取郵件服務器ip地址失敗!"; this.mErrors.addOneError(tError); return false; } /** * 查詢郵箱服務器的發送協議類型 * */ tSQL = "select sysvarvalue from ldsysvar where sysvar='EmProtoServiceType'"; mprotocol = tExeSQL.getOneValue(tSQL); System.out.println("=======mprotocol====="+mprotocol); if (mprotocol == null || mprotocol.equals("")) { CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取郵件服務協議失敗!"; this.mErrors.addOneError(tError); return false; } /** * 查詢是否啟用郵件debug模式 * */ tSQL = "select sysvarvalue from ldsysvar where sysvar='EmAuthServiceType'"; mauth = tExeSQL.getOneValue(tSQL); System.out.println("=======mauth====="+mauth); if (mauth == null || mauth.equals("")) { CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取郵件dubug模式失敗!"; this.mErrors.addOneError(tError); return false; } /** * 查詢發送郵件郵箱的用戶名 * */ tSQL = "select sysvarvalue from ldsysvar where sysvar='EmSuserServiceType'"; msusername = tExeSQL.getOneValue(tSQL); System.out.println("=======msusername====="+msusername); if (msusername == null || msusername.equals("")) { CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取發送郵件用戶名失敗!"; this.mErrors.addOneError(tError); return false; } /** * 查詢發送郵件郵箱的密碼 * */ tSQL = "select sysvarvalue from ldsysvar where sysvar='EmPassServiceType'"; mpassword = tExeSQL.getOneValue(tSQL); System.out.println("=======mpassword=====" + mpassword); if (mpassword == null || mpassword.equals("")) { CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取發送郵件密碼失敗!"; this.mErrors.addOneError(tError); return false; } /** * 設置發送郵件的參數 * */ Properties prop = new Properties(); prop.setProperty(tport, mport); prop.setProperty(tprotocol, mprotocol); prop.setProperty(tauth, mauth); //使用JavaMail發送郵件的5個步驟 //1、創建session Session session = Session.getInstance(prop); //開啟Session的debug模式,這樣就可以查看到程序發送Email的運行狀態 session.setDebug(true); //2、通過session得到transport對象 try { //2、通過session得到transport對象 ts = session.getTransport(); //3、使用郵箱的用戶名和密碼連上郵件服務器,發送郵件時,發件人需要提交郵箱的用戶名和密碼給smtp服務器,用戶名和密碼都通過驗證之后才能夠正常發送郵件給收件人。 ts.connect(mport, msusername, mpassword); //查詢加收郵件的郵箱地址 tSQL = "select distinct useremail from dxusermess where usergroup = '保單登記平台' and messflag = 'YJ'"; SSRS tSSRS = tExeSQL.execSQL(tSQL); for (int i=1;i<=tSSRS.getMaxRow();i++){ mRusername = tSSRS.GetText(i, 1); if(mRusername == null || mRusername.equals("")){ CError tError = new CError(); tError.moduleName = "SentMailTest"; tError.functionName = "dealData"; tError.errorMessage = "獲取收件人郵箱失敗!"; this.mErrors.addOneError(tError); return false; } //4、創建郵件 Message message = createSimpleMail(session,mRusername); //5、發送郵件 ts.sendMessage(message, message.getAllRecipients()); } } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ if (ts!=null){ try { ts.close(); } catch (MessagingException e) { e.printStackTrace(); } } } return true; } private boolean checkData() { // TODO Auto-generated method stub return true; } public static MimeMessage createSimpleMail(Session session,String mRuserName) throws Exception { //創建郵件對象 MimeMessage message = new MimeMessage(session); //指明郵件的發件人 message.setFrom(new InternetAddress("mail@192.168.XX.XX")); //指明郵件的發送人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(mRuserName)); //郵件的標題 message.setSubject(title); /* //郵件的文本內容 message.setContent("你好啊!", "text/html;charset=UTF-8"); */ //創建郵件正文,為了避免郵件正文中文亂碼問題,需要使用charset=UTF-8指明字符編碼 /* MimeBodyPart text = new MimeBodyPart(); text.setContent("使用JavaMail創建的帶附件的郵件", "text/html;charset=UTF-8");*/ MimeBodyPart text = new MimeBodyPart(); // 描述數據關系 MimeMultipart mm = new MimeMultipart(); if(path == null || path.equals("")){ text.setContent(mas, "text/html;charset=UTF-8"); }else{ text.setContent(mas+"<br/><img src='cid:myPic.jpg'>", "text/html;charset=UTF-8"); // 准備圖片數據 MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource(path)); image.setDataHandler(dh); image.setContentID("myPic.jpg"); mm.addBodyPart(image); } mm.addBodyPart(text); mm.setSubType("related"); message.setContent(mm); message.saveChanges(); //返回創建好的郵件對象 return message; } }
短信發送的類源碼:
import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.MMap; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.pubfun.PubFun1; import com.sinosoft.lis.pubfun.PubSubmit; import com.sinosoft.lis.schema.DXUSERMESSSchema; import com.sinosoft.lis.schema.PTSENDRECORDSchema; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.ExeSQL; import com.sinosoft.utility.SSRS; import com.sinosoft.utility.TransferData; import com.sinosoft.utility.VData; /** * * @作者:wcg * @時間:2019-03-14 * @描述:短信發送工具類 * @version: 1.0 */ public class PtSendCommon { /** 錯誤處理類,每個需要錯誤處理的類中都放置該類 */ public CErrors mErrors = new CErrors(); /** 往界面傳輸數據的容器 */ private VData mResult = new VData(); private MMap mMap = new MMap(); /** 數據操作字符串 */ private String mOperate; /** 往后面傳輸數據的容器 */ private VData mInputData; private String CurrDate = PubFun.getCurrentDate(); private String mTransDate = null; private String CurrTime = PubFun.getCurrentTime(); private GlobalInput mGlobalInput = new GlobalInput(); Logger mLog = Logger.getLogger("UWSMSLog"); private String mXMLToString; private String mEndPoint = ""; private String mUser = ""; private String mComCode = ""; private String mPass = ""; private int mMaxNum = 5000; private String msendflag = "你好"; private String mContent = ""; private String mtablename = ""; private String mbatchno = ""; private int mcount = 0; private String MobilePhone = "";//聯系人手機號 private String mFailureReason = ""; private String mServiceType = ""; private String mtransdate = ""; private static final String mExtension = "true"; private TransferData mTransferData; public boolean submitData(VData cInputData, String tsendflag) { mTransDate = PubFun.calDate(CurrDate, -1, "D", ""); System.out.println("-------send message begin----"); this.msendflag = tsendflag; //將操作數據拷貝到本類中 mInputData = (VData) cInputData.clone(); //得到外部傳入的數據,將數據備份到本類中 if (!getInputData(cInputData)) { return false; } System.out.println("aftergetInputData send message:::"); if (!checkData()) { return false; } //數據准備操作(dealData()) if (!dealData()) { return false; } System.out.println("afterdealDate send message:"); //數據准備操作(dealData()) if (!prepareData()) { return false; } if (!doPubSubmit()){ return false; } return true; } private boolean doPubSubmit() { PubSubmit tPubSubmit = new PubSubmit(); if (!tPubSubmit.submitData(mResult, "")){ CError tError = new CError(); tError.moduleName = "短信信息插入表提交"; tError.functionName = "tPubSubmit"; tError.errorMessage = "向表PTSENDRECORD中提交短信信息失敗!"; this.mErrors.addOneError(tError); return false; } return true; } /** * 初始化數據:獲取發送短信類型的標志sendflag 和 需要發送短信的表范圍 * * @param cInputData * @return */ private boolean getInputData(VData cInputData) { mTransferData = (TransferData) mInputData.getObjectByObjectName("TransferData",0); if(msendflag.equals("LT")){ mtablename = (String) mTransferData.getValueByName("mtablename"); }else if(msendflag.equals("YC")){ mtablename = (String) mTransferData.getValueByName("mtablename"); }else if(msendflag.equals("CW")){ mbatchno = (String)mTransferData.getValueByName("mbatchno"); mcount = (Integer)mTransferData.getValueByName("mcount"); } return true; } /** * 對外傳數據進行校驗,目前不需要添加校驗的功能 * * @return */ private boolean checkData() { return true; } /** * 具體處理短信發送業務,按照不同的要求發送短信 * * @return */ private boolean dealData() { //調用短信發送的類發送陪你過短信 if (msendflag.equals("LT")){ if(!SendMessage()){ System.out.println("==短信發送失敗=="); return false; } }else if (msendflag.equals("YC")){ if(!SendMessage()){ System.out.println("==短信發送失敗=="); return false; } }else if (msendflag.equals("cw")){ if(!SendMessage1()){ System.out.println("==短信發送失敗=="); return false; } } return true; } /** * 對數據進行前期准備 * * * @return */ private boolean prepareData() { mResult.clear(); mResult.add(mMap); return true; } private boolean SendMessage(){ ExeSQL tExeSQL = new ExeSQL(); String tSQL = ""; tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtSMServiceType'"; mServiceType = tExeSQL.getOneValue(tSQL); System.out.println("=======mServiceType====="+mServiceType); if (mServiceType == null || mServiceType.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台服務類型失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtSMWebServiceURL'"; mEndPoint = tExeSQL.getOneValue(tSQL); System.out.println("=======mEndPoint====="+mEndPoint); if (mEndPoint == null || mEndPoint.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台WebService地址失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQID'"; mUser = tExeSQL.getOneValue(tSQL); if (mUser == null || mUser.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台用戶名失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQCOM'"; mComCode = tExeSQL.getOneValue(tSQL); if (mComCode == null || mComCode.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台機構代碼失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQPASS'"; mPass = tExeSQL.getOneValue(tSQL); if (mPass == null || mPass.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台密碼失敗!"; this.mErrors.addOneError(tError); return false; } // 一次最多可以發送的條數 tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtMaxNum'"; String tNum = tExeSQL.getOneValue(tSQL); if (tNum == null || tNum.equals("")) { mMaxNum = 500; } else { try { mMaxNum = Integer.parseInt(tNum); } catch (NumberFormatException e) { mMaxNum = 500; } } //查詢用戶的手機號,因為一張表可能對應多個用戶,所以需要循環查詢出所有需要發送短信的用戶 String mobile_sql = " select userphone from dxusermess where tablename = '"+mtablename+"'"; SSRS tSSRS = tExeSQL.execSQL(mobile_sql); for (int i=1;i<=tSSRS.getMaxRow();i++){ MobilePhone = tSSRS.GetText(i, 1); if(MobilePhone == null || MobilePhone.equals("")){ CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取聯系人手機號失敗!"; this.mErrors.addOneError(tError); return false; } //循環每一個手機號並進行處理 mLog.info("GEdorValidBL->dealData:開始進行業務邏輯處理"); if (!makeXML()) { mLog.info("GEdorValidBL->dealData:生成xml數據失敗"); return false; } if (!modifyStauts("1")) { mLog.info("GEdorValidBL->dealData:短信成功狀態更新失敗"); return false; } if (!callRemoteService()) { mLog.info("GEdorValidBL->dealData:短信調用失敗,開始進行短信狀態的置值"); if (!modifyStauts("2")) { mLog.info("GEdorValidBL->dealData:短信失敗狀態更新失敗"); return false; } return false; } } mLog.info("GEdorValidBL->dealData:業務邏輯處理結束!"); return true; } /** * 函數功能:為每天監控的錯誤數據量發送日志 * * */ private boolean SendMessage1(){ ExeSQL tExeSQL = new ExeSQL(); String tSQL = ""; tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtSMServiceType'"; mServiceType = tExeSQL.getOneValue(tSQL); System.out.println("=======mServiceType====="+mServiceType); if (mServiceType == null || mServiceType.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台服務類型失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtSMWebServiceURL'"; mEndPoint = tExeSQL.getOneValue(tSQL); System.out.println("=======mEndPoint====="+mEndPoint); if (mEndPoint == null || mEndPoint.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台WebService地址失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQID'"; mUser = tExeSQL.getOneValue(tSQL); if (mUser == null || mUser.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台用戶名失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQCOM'"; mComCode = tExeSQL.getOneValue(tSQL); if (mComCode == null || mComCode.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台機構代碼失敗!"; this.mErrors.addOneError(tError); return false; } tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtBQPASS'"; mPass = tExeSQL.getOneValue(tSQL); if (mPass == null || mPass.equals("")) { CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取短信平台密碼失敗!"; this.mErrors.addOneError(tError); return false; } // 一次最多可以發送的條數 tSQL = "select sysvarvalue from ldsysvar where sysvar='CsPtMaxNum'"; String tNum = tExeSQL.getOneValue(tSQL); if (tNum == null || tNum.equals("")) { mMaxNum = 500; } else { try { mMaxNum = Integer.parseInt(tNum); } catch (NumberFormatException e) { mMaxNum = 500; } } //為保單登記平台的每個用戶發送一條短信 String mobile_sql = " select userphone from dxusermess where messflag = 'CW'"; SSRS tSSRS = tExeSQL.execSQL(mobile_sql); for (int i=1;i<=tSSRS.getMaxRow();i++){ MobilePhone = tSSRS.GetText(i, 1); if(MobilePhone == null || MobilePhone.equals("")){ CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "SendMessage"; tError.errorMessage = "獲取聯系人手機號失敗!"; this.mErrors.addOneError(tError); return false; } //循環每一個手機號並進行處理 mLog.info("GEdorValidBL->dealData:開始進行業務邏輯處理"); if (!makeXML()) { mLog.info("GEdorValidBL->dealData:生成xml數據失敗"); return false; } if (!modifyStauts("1")) { mLog.info("GEdorValidBL->dealData:短信成功狀態更新失敗"); return false; } if (!callRemoteService()) { mLog.info("GEdorValidBL->dealData:短信調用失敗,開始進行短信狀態的置值"); if (!modifyStauts("2")) { mLog.info("GEdorValidBL->dealData:短信失敗狀態更新失敗"); return false; } return false; } } mLog.info("GEdorValidBL->dealData:業務邏輯處理結束!"); return true; } /** * 該方法用於生成XML文件,然后包裝到mVData中 * * @return */ public boolean makeXML() { String ipnum = getServerIp(); System.out.println("+++++輸出服務器的ip地址++++++"+ipnum); mLog.info("GEdorValidBL->makeXML:開始生成短信xml格式"); // MMap tMap = new MMap(); Element tRoot, tSubRoot, tMessage, tReceiver, tContents; Document tDocument; tRoot = new Element("Messages");// 首先建立根元素 tDocument = new Document(tRoot); tSubRoot = new Element("Organization"); tSubRoot.setText(mComCode); tRoot.addContent(tSubRoot); tSubRoot = new Element("ServiceType"); tSubRoot.setText(mServiceType); tRoot.addContent(tSubRoot); tSubRoot = new Element("Extension"); tSubRoot.setText(mExtension); tRoot.addContent(tSubRoot); tSubRoot = new Element("StartDate"); tSubRoot.setText(CurrDate); tRoot.addContent(tSubRoot); tSubRoot = new Element("EndDate"); tSubRoot.setText(PubFun.calDate(CurrDate, 1, "D", "")); tRoot.addContent(tSubRoot); tSubRoot = new Element("StartTime"); tSubRoot.setText("00:00:00"); tRoot.addContent(tSubRoot); tSubRoot = new Element("EndTime"); tSubRoot.setText("23:59:59"); tRoot.addContent(tSubRoot); String[] dateSign1; String[] dateSign2; String year1 = ""; String month1 = ""; String day1 = ""; String year2 = ""; String month2 = ""; String day2 = ""; tMessage = new Element("Message"); tReceiver = new Element("Receiver"); tReceiver.setText(MobilePhone); System.out.println("==1===="+MobilePhone); System.out.println("==輸出短信發送標志===="+msendflag); if(msendflag.equals("LT")){ mContent = "lsm:早上好! 外圍表" + mtablename + "在" + mTransDate + "的數據" + "沒有推送到北京查詢機,請及時處理,祝好!"; }else if("YC".equals(msendflag)){ mContent = "lsm:早上好! 外圍表" + mtablename + "在" + mTransDate +"的數據沒有按時推送到北京查詢機,保單登記平台提數時數據還在推送,請及時排查原因,祝好!"; }else if ("cw".equals(msendflag)){ mContent = "lsm:您有一條新短消息! 今天的增量批次 " + mbatchno + "在" + mTransDate + "這天插入lderrorlog表中的錯誤數據量達到了" + mcount +" 請及時排查原因,祝好!"; } System.out.println("==輸出短信發送內容===="+mContent); tContents = new Element("Contents"); tContents.setText(mContent); tMessage.addContent(tReceiver); tMessage.addContent(tContents); tRoot.addContent(tMessage); XMLOutputter tXMLOutputter = new XMLOutputter(); // xml導出對象 OutputStream tOutputStream = new ByteArrayOutputStream(); try { tXMLOutputter.setEncoding("GBK"); tXMLOutputter.setTrimText(true); tXMLOutputter.setIndent(" ");// 調整輸出xml的縮進值 tXMLOutputter.setExpandEmptyElements(true);// 是否擴展空值標簽 tXMLOutputter.setNewlines(true);// 是否分行輸出 tXMLOutputter.output(tDocument, tOutputStream); this.mXMLToString = tOutputStream.toString(); System.out.println(mXMLToString); mLog.info("GEdorValidBL->makeXML:短信信息-》" + mXMLToString); // tXMLOutputter.output(tDocument, new // FileOutputStream("c:/test1.xml")); //輸出 } catch (Exception e) { e.printStackTrace(); mLog.info("GEdorValidBL->makeXML:生成xml失敗," + e.getMessage()); return false; } System.out.println("短信接口:MakeXmlBL生成xml成功-------------"); mLog.info("GEdorValidBL->makeXML:生成xml成功,處理結束"); return true; } /** * 修改短信發送狀態 add by chenrong 2011-6-10 * * @param cStatus * @return */ private boolean modifyStauts(String cStatus) { System.out.println("++++開始將錯誤數據插入短信數據表中 +++++"); PubFun1 pubFun = new PubFun1(); String[] dateSign1; String[] dateSign2; String year1 = ""; String month1 = ""; String day1 = ""; String year2 = ""; String month2 = ""; String day2 = ""; String PtMSS = pubFun.CreateMaxNo("PtMSS", 20); System.out.println("+++++短信內容插入信息表中的流水號+++++"+PtMSS); //將發送短信的信息插入到短信信息表中 PTSENDRECORDSchema tPTSENDRECORDSchema = new PTSENDRECORDSchema(); if (cStatus.equals("1")) { tPTSENDRECORDSchema.setSERIALNO(PtMSS); tPTSENDRECORDSchema.setSMSTYPE(mServiceType); tPTSENDRECORDSchema.setMOBILENO(MobilePhone); tPTSENDRECORDSchema.setSMSCONTENTS(mContent); tPTSENDRECORDSchema.setSENDSTATE(cStatus); tPTSENDRECORDSchema.setSENDDATE(PubFun.getCurrentDate()); tPTSENDRECORDSchema.setSENDTIME(PubFun.getCurrentTime()); tPTSENDRECORDSchema.setOPERATOR("zl"); tPTSENDRECORDSchema.setMAKEDATE(PubFun.getCurrentDate()); tPTSENDRECORDSchema.setMAKETIME(PubFun.getCurrentTime()); tPTSENDRECORDSchema.setMODIFYDATE(PubFun.getCurrentDate()); tPTSENDRECORDSchema.setMODIFYTIME(PubFun.getCurrentTime()); mMap.put(tPTSENDRECORDSchema, "INSERT"); } return true; } /** * 調用遠程短信接口 * * @return */ private boolean callRemoteService() { System.out.println("++++開始調用短信發送接口 +++++"); try { mLog.info("GEdorValidBL->callRemoteService:開始調用短信接口"); WsClientLocator tService = new WsClientLocator(); WsClientHttpBindingStub tWsClientHttpBindingStub; tService.setWsClientHttpPortWSDDServiceName(mEndPoint); tWsClientHttpBindingStub = (WsClientHttpBindingStub) tService .getWsClientHttpPort(); tWsClientHttpBindingStub.sendSMS(mUser, mPass, mComCode, mXMLToString); mLog .info("GEdorValidBL->callRemoteService:調用短信接口成功,callRemoteService處理結束"); return true; } catch (ClientException e) { System.out.println("短信接口->ClientException:"); System.out.println("mFailureReason:"+ e.toString()); e.printStackTrace(); System.out.println("remFailureReason:"+ e.toString()); mFailureReason = e.toString(); CError tError = new CError(); tError.moduleName = "SMSSendBL"; tError.functionName = "callRemoteService"; tError.errorMessage = "調用遠程短信接口失敗:" + e.toString(); this.mErrors.addOneError(tError); mLog.info("GEdorValidBL->callRemoteService:調用短信接口失敗," + mFailureReason); return false; } catch (Exception e) { System.out.println("短信接口->Exception:"); System.out.println("mFailureReason:"+ e.toString()); e.printStackTrace(); mFailureReason = e.toString(); System.out.println("remFailureReason:"+ e.toString()); CError tError = new CError(); tError.moduleName = "GEdorValidBL"; tError.functionName = "callRemoteService"; tError.errorMessage = "調用遠程短信接口失敗:" + e.toString(); this.mErrors.addOneError(tError); mLog.info("GEdorValidBL->callRemoteService:調用短信接口失敗," + mFailureReason); return false; } } public String getServerIp(){ String SERVER_IP = null; try { Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (netInterfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); ip = (InetAddress) ni.getInetAddresses().nextElement(); SERVER_IP = ip.getHostAddress(); if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { SERVER_IP = ip.getHostAddress(); break; } else { ip = null; } } } catch (SocketException e) { e.printStackTrace(); } return SERVER_IP; } }