Linux环境下应用生成图片中出现乱码的问题处理

问题:  用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:WindowsFonts下找到字体文件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;
   }
}
       
       
       
原文地址:https://www.cnblogs.com/wcgstudy/p/10941962.html