`
meiyaa2008
  • 浏览: 1221 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
httpClient推送xml数据
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ruanko.ebook.entity.SourceUpdate;
import com.ruanko.ebook.service.SourceUpdateService;
import com.ruanko.ebook.utils.Dom4jUtils;
import com.ruanko.ebook.utils.PropertiesTool;

public class PostSourceXml {
	
	private SourceUpdateService sourceUpdateService;
	
	public void setSourceUpdateService(SourceUpdateService sourceUpdateService) {
		this.sourceUpdateService = sourceUpdateService;
	}

	
	private DefaultHttpClient client;
	/**
	 * httpClient推送xml数据到知识库引擎
	 * @param xmlString拼接好的xml数据
	 * @throws Exception 
	 */
	public void postXmlData(String id,String handlerType) throws Exception{
		try{
			SourceUpdate sourceUpdate = null;
			
			String url = "";
			
			String propertiesParam = "resoucreUrl";
			
			url = PropertiesTool.getValue("knowledgeUrl.properties", propertiesParam);//推送url地址
			
			sourceUpdate = this.sourceUpdateService.getXmlData(id);
			
			String xmlString = "";
			
			if("update".equals(handlerType)){
				xmlString = this.sourceUpdateService.getXmlString(sourceUpdate);
			}else if("delete".equals(handlerType)){
				xmlString = this.sourceUpdateService.getDelXmlString(sourceUpdate);
			}
			
			
			 if (client == null) {
			   // Create HttpClient Object
			   client = new DefaultHttpClient();
			 }
			 
			 HttpPost post = new HttpPost(url);
			 
			 StringEntity entity = new StringEntity(xmlString);
			 
			 post.setEntity(entity);
			 
			 post.setHeader("Content-Type", "text/xml;charset=UTF-8");
			 
			 HttpResponse response = client.execute(post);
			 
			 int statusCode = response.getStatusLine().getStatusCode();
			 
			 HttpEntity resEntity = response.getEntity();
			 
			 String repStr = "";
			 
			 String result = "";
			 
			 if(statusCode==200&&resEntity!=null){
				 
				 InputStreamReader reader = new InputStreamReader(resEntity.getContent(), "ISO-8859-1"); 
				 
	             char[] buff = new char[1024]; 
	             
	             int length = 0; 
	             
	             while ((length = reader.read(buff)) != -1) { 
	            	 
	            	 repStr = new String(buff, 0, length); 
	            	 
	             }
	             
	             result = Dom4jUtils.ReaderXmlStr(repStr, "ret"); //dom4j读取返回数据
	             
	             if("0".equals(result)){
	            	 
	            	 System.out.println("推送数据成功!");
	            	 
	             }else{
	            	 
	            	 System.out.println("推送数据失败");
	            	 
	            	 throw new Exception("推送"+id+"电子书失败,"+"返回状态值为:"+result);
	            	 
	             }
			 }else{
				 
				 System.out.println("推送数据失败! ");
				 
				 throw new Exception("推送"+id+"电子书失败,"+"返回状态值为:"+result);
			 }

			 post.abort();
			 
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
	}
	
}

//服务器端接受值
package com; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 

/** 
* 接收XLM请求 
* 
* @author leizhimin 2010-7-8 1:02:42 
*/ 
public class GenXmlServlet extends HttpServlet { 
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
//                String xml = req.getParameter("xmldata"); 
                resp.setContentType("text/xml"); 
                resp.setCharacterEncoding("GBK"); 
                PrintWriter out = resp.getWriter(); 
//                out.println(xml); 
//                System.out.println(xml); 
                System.out.println("----------------------"); 
                InputStreamReader reader = new InputStreamReader(req.getInputStream(), "GBK"); 
                char[] buff = new char[1024]; 
                int length = 0; 
                while ((length = reader.read(buff)) != -1) { 
                        String x = new String(buff, 0, length); 
                        System.out.println(x); 
                        out.print(x); 
                } 
        } 

        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
                resp.setContentType("text/html"); 
                PrintWriter out = resp.getWriter(); 
                out.println("<html>"); 
                out.println("<head>"); 
                out.println("<title>Hello World!</title>"); 
                out.println("</head>"); 
                out.println("<body>"); 
                out.println("<h1>Hello World!!</h1>"); 
                out.println("</body>"); 
                out.println("</html>"); 
        } 
}
dom4j读取xml
SAXReader reader = new SAXReader(); 
Document doc = reader.read(...); 
List childNodes = doc.selectNodes("//Config/Child/ChildNode"); 
for(Object obj:childNodes) { 
Node childNode = (Node)obj; 

String name = childNode.valueOf("@name"); 
String text = childNode.getText(); 
} 



一.Document对象相关

1.读取XML文件,获得document对象.
             SAXReader reader = new SAXReader();
             Document   document = reader.read(new File("input.xml"));

2.解析XML形式的文本,得到document对象.
             String text = "<members></members>";
             Document document = DocumentHelper.parseText(text);
3.主动创建document对象.
             Document document = DocumentHelper.createDocument();
             Element root = document.addElement("members");// 创建根节点
二.节点相关

1.获取文档的根节点.
Element rootElm = document.getRootElement();
2.取得某节点的单个子节点.
Element memberElm=root.element("member");// "member"是节点名
3.取得节点的文字
String text=memberElm.getText();也可以用:
String text=root.elementText("name");这个是取得根节点下的name字节点的文字.

4.取得某节点下名为"member"的所有字节点并进行遍历.
List nodes = rootElm.elements("member");

for (Iterator it = nodes.iterator(); it.hasNext();) {
    Element elm = (Element) it.next();
   // do something
}
5.对某节点下的所有子节点进行遍历.
            for(Iterator it=root.elementIterator();it.hasNext();){
                 Element element = (Element) it.next();
                // do something
             }
6.在某节点下添加子节点.
Element ageElm = newMemberElm.addElement("age");
7.设置节点文字.
ageElm.setText("29");
8.删除某节点.
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
9.添加一个CDATA节点.
         Element contentElm = infoElm.addElement("content");
         contentElm.addCDATA(diary.getContent());

三.属性相关.
1.取得某节点下的某属性
             Element root=document.getRootElement();    
             Attribute attribute=root.attribute("size");// 属性名name
2.取得属性的文字
             String text=attribute.getText();也可以用:
String text2=root.element("name").attributeValue("firstname");这个是取得根节点下name字节点的属性firstname的值.

3.遍历某节点的所有属性
             Element root=document.getRootElement();    
            for(Iterator it=root.attributeIterator();it.hasNext();){
                 Attribute attribute = (Attribute) it.next();
                 String text=attribute.getText();
                 System.out.println(text);
             }
4.设置某节点的属性和文字.
newMemberElm.addAttribute("name", "sitinspring");
5.设置属性的文字
             Attribute attribute=root.attribute("name");
             attribute.setText("sitinspring");
6.删除某属性
             Attribute attribute=root.attribute("size");// 属性名name
             root.remove(attribute);
四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();
2.文档中含有中文,设置编码格式写入的形式.
             OutputFormat format = OutputFormat.createPrettyPrint();
             format.setEncoding("GBK");    // 指定XML编码        
             XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
            
             writer.write(document);
             writer.close();
五.字符串与XML的转换
1.将字符串转化为XML
String text = "<members> <member>sitinspring</member> </members>";
Document document = DocumentHelper.parseText(text);
2.将文档或节点的XML转化为字符串.
             SAXReader reader = new SAXReader();
             Document   document = reader.read(new File("input.xml"));            
             Element root=document.getRootElement();                
             String docXmlText=document.asXML();
             String rootXmlText=root.asXML();
             Element memberElm=root.element("member");
             String memberXmlText=memberElm.asXML();




dom4j API 包含一个解析 XML 文档的工具。本文中将使用这个解析器创建一个示例 XML 文档。清单 1 显示了这个示例 XML 文档,catalog.xml。

清单 1. 示例 XML 文档(catalog.xml) 
<?xml version="1.0" encoding="UTF-8"?> 
<catalog> 
<!--An XML Catalog--> 
<?target instruction?>
  <journal title="XML Zone" 
                  publisher="IBM developerWorks"> 
<article level="Intermediate" date="December-2001">
 <title>Java configuration with XML Schema</title> 
 <author> 
     <firstname>Marcello</firstname> 
     <lastname>Vitaletti</lastname> 
 </author>
  </article>
  </journal> 
</catalog>
 


然后使用同一个解析器修改 catalog.xml,清单 2 是修改后的 XML 文档,catalog-modified.xml。

清单 2. 修改后的 XML 文档(catalog-modified.xml) 
<?xml version="1.0" encoding="UTF-8"?> 
<catalog> 
<!--An XML catalog--> 
<?target instruction?>
  <journal title="XML Zone"
                   publisher="IBM developerWorks"> 
<article level="Introductory" date="October-2002">
 <title>Create flexible and extensible XML schemas</title> 
 <author> 
     <firstname>Ayesha</firstname> 
     <lastname>Malik</lastname> 
 </author> 
  </article>
  </journal> 
</catalog>
 


与 W3C DOM API 相比,使用 dom4j 所包含的解析器的好处是 dom4j 拥有本地的 XPath 支持。DOM 解析器不支持使用 XPath 选择节点。

本文包括以下几个部分:

预先设置 
创建文档 
修改文档 
预先设置

这个解析器可以从 http://dom4j.org 获取。通过设置使 dom4j-1.4/dom4j-full.jar 能够在 classpath 中访问,该文件中包括 dom4j 类、XPath 引擎以及 SAX 和 DOM 接口。如果已经使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向 classpath 中增加 dom4j-1.4/dom4j.jar 。 dom4j.jar 包括 dom4j 类和 XPath 引擎,但是不含 SAX 与 DOM 接口。 



 


 回页首 
 



创建文档

本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。

使用 import 语句导入 dom4j API 类:

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
 


使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。 

 Document document = DocumentHelper.createDocument(); 


使用 addElement() 方法创建根元素 catalog 。 addElement() 用于向 XML 文档中增加元素。 

Element catalogElement = document.addElement("catalog"); 


在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。 

 catalogElement.addComment("An XML catalog"); 


在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。 

catalogElement.addProcessingInstruction("target","text"); 


在 catalog 元素中使用 addElement() 方法增加 journal 元素。 

Element journalElement =  catalogElement.addElement("journal"); 


使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。 

journalElement.addAttribute("title", "XML Zone");
         journalElement.addAttribute("publisher", "IBM developerWorks"); 


向 article 元素中添加 journal 元素。 

Element articleElement=journalElement.addElement("article"); 


为 article 元素增加 level 和 date 属性。 

articleElement.addAttribute("level", "Intermediate");
      articleElement.addAttribute("date", "December-2001"); 


向 article 元素中增加 title 元素。 

Element titleElement=articleElement.addElement("title"); 


使用 setText() 方法设置 article 元素的文本。 

titleElement.setText("Java configuration with XML Schema"); 


在 article 元素中增加 author 元素。 

Element authorElement=articleElement.addElement("author"); 


在 author 元素中增加 firstname 元素并设置该元素的文本。 

Element  firstNameElement=authorElement.addElement("firstname");
     firstNameElement.setText("Marcello"); 


在 author 元素中增加 lastname 元素并设置该元素的文本。 

Element lastNameElement=authorElement.addElement("lastname");
     lastNameElement.setText("Vitaletti"); 


可以使用 addDocType() 方法添加文档类型说明。 

document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd"); 


这样就向 XML 文档中增加文档类型说明:

<!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd"> 


如果文档要使用文档类型定义(DTD)文档验证则必须有 Doctype。

XML 声明 <?xml version="1.0" encoding="UTF-8"?> 自动添加到 XML 文档中。 

清单 3 所示的例子程序 XmlDom4J.java 用于创建 XML 文档 catalog.xml。

清单 3. 生成 XML 文档 catalog.xml 的程序(XmlDom4J.java) 
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.*;
public class XmlDom4J{
public void generateDocument(){
Document document = DocumentHelper.createDocument();
     Element catalogElement = document.addElement("catalog");
     catalogElement.addComment("An XML Catalog");
     catalogElement.addProcessingInstruction("target","text");
     Element journalElement =  catalogElement.addElement("journal");
     journalElement.addAttribute("title", "XML Zone");
     journalElement.addAttribute("publisher", "IBM developerWorks");
     Element articleElement=journalElement.addElement("article");
     articleElement.addAttribute("level", "Intermediate");
     articleElement.addAttribute("date", "December-2001");
     Element  titleElement=articleElement.addElement("title");
     titleElement.setText("Java configuration with XML Schema");
     Element authorElement=articleElement.addElement("author");
     Element  firstNameElement=authorElement.addElement("firstname");
     firstNameElement.setText("Marcello");
     Element lastNameElement=authorElement.addElement("lastname");
     lastNameElement.setText("Vitaletti");
     document.addDocType("catalog",
                           null,"file://c:/Dtds/catalog.dtd");
    try{
    XMLWriter output = new XMLWriter(
            new FileWriter( new File("c:/catalog/catalog.xml") ));
        output.write( document );
        output.close();
        }
     catch(IOException e){System.out.println(e.getMessage());}
}
public static void main(String[] argv){
XmlDom4J dom4j=new XmlDom4J();
dom4j.generateDocument();
}}
 


这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。 



 


 回页首 
 



修改文档

这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。

使用 SAXReader 解析 XML 文档 catalog.xml:

SAXReader saxReader = new SAXReader();
 Document document = saxReader.read(inputXml); 


SAXReader 包含在 org.dom4j.io 包中。 

inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。 

List list = document.selectNodes("//article/@level" );
      Iterator iter=list.iterator();
        while(iter.hasNext()){
            Attribute attribute=(Attribute)iter.next();
               if(attribute.getValue().equals("Intermediate"))
               attribute.setValue("Introductory"); 
       } 


获取 article 元素列表,从 article 元素中的 title 元素得到一个迭代器,并修改 title 元素的文本。 

list = document.selectNodes("//article" );
     iter=list.iterator();
   while(iter.hasNext()){
       Element element=(Element)iter.next();
      Iterator iterator=element.elementIterator("title");
   while(iterator.hasNext()){
   Element titleElement=(Element)iterator.next();
   if(titleElement.getText().equals("Java configuration with XML Schema"))
     titleElement.setText("Create flexible and extensible XML schema");
    }} 


通过和 title 元素类似的过程修改 author 元素。 

清单 4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文档修改成 catalog-modified.xml 文档。

清单 4. 用于修改 catalog.xml 的程序(Dom4Jparser.java) 
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import java.util.List;
import java.util.Iterator;
import org.dom4j.io.XMLWriter;
import java.io.*;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader; 
public class Dom4JParser{
 public void modifyDocument(File inputXml){
  try{
   SAXReader saxReader = new SAXReader();
   Document document = saxReader.read(inputXml);
   List list = document.selectNodes("//article/@level" );
   Iterator iter=list.iterator();
   while(iter.hasNext()){
    Attribute attribute=(Attribute)iter.next();
    if(attribute.getValue().equals("Intermediate"))
      attribute.setValue("Introductory"); 
       }
   
   list = document.selectNodes("//article/@date" );
   iter=list.iterator();
   while(iter.hasNext()){
    Attribute attribute=(Attribute)iter.next();
    if(attribute.getValue().equals("December-2001"))
      attribute.setValue("October-2002");
       }
   list = document.selectNodes("//article" );
   iter=list.iterator();
   while(iter.hasNext()){
    Element element=(Element)iter.next();
    Iterator iterator=element.elementIterator("title");
      while(iterator.hasNext()){
        Element titleElement=(Element)iterator.next();
        if(titleElement.getText().equals("Java configuration with XML
      Schema"))
        titleElement.setText("Create flexible and extensible XML schema");
                                          }
                                }
    list = document.selectNodes("//article/author" );
    iter=list.iterator();
     while(iter.hasNext()){
     Element element=(Element)iter.next();
     Iterator iterator=element.elementIterator("firstname");
     while(iterator.hasNext()){
      Element firstNameElement=(Element)iterator.next();
      if(firstNameElement.getText().equals("Marcello"))
      firstNameElement.setText("Ayesha");
                                     }
                              }
    list = document.selectNodes("//article/author" );
    iter=list.iterator();
     while(iter.hasNext()){
      Element element=(Element)iter.next();
      Iterator iterator=element.elementIterator("lastname");
     while(iterator.hasNext()){
      Element lastNameElement=(Element)iterator.next();
      if(lastNameElement.getText().equals("Vitaletti"))
      lastNameElement.setText("Malik");
                                  }
                               }
     XMLWriter output = new XMLWriter(
      new FileWriter( new File("c:/catalog/catalog-modified.xml") ));
     output.write( document );
     output.close();
   }
 
  catch(DocumentException e)
                 {
                  System.out.println(e.getMessage());
                            }
  catch(IOException e){
                       System.out.println(e.getMessage());
                    }
 }
 public static void main(String[] argv){
  Dom4JParser dom4jParser=new Dom4JParser();
  dom4jParser.modifyDocument(new File("c:/catalog/catalog.xml"));
                                        }
   }
 


http post 发送xml数据 http post 发送xml数据
package WCDMAVideoHttpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;


public class HttpClientUtil {
	
	private HttpClient httpClient = null;
	
	private String url = null;
	
	private String xml = null;
	

	
	public HttpClientUtil(String url, String xml){
		httpClient = new HttpClient();
		this.url = url;
		this.xml = xml;
	}
	
	
	
	public String sendXMLReq(){
		
		PostMethod post = new PostMethod(url);
		//add xml
		RequestEntity requestXml = null;;
		try {
			requestXml = new StringRequestEntity(xml, "text/xml", "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		post.setRequestEntity(requestXml);
		
		//execute post 
		try {
			httpClient.executeMethod(post);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//get resp info
		
		String resp = null;
		try {
			resp = post.getResponseBodyAsString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		post.releaseConnection();
		return resp;
	}
	public static void main(String[] args) {
		HttpClientUtil HttpClientUtil = new HttpClientUtil("url:这是对方的接口","xml:将发的数据以xml的形式发送到对方");
		
		//这里是通过sendXmlReq方法将请求发送出去,返回值为对付给我们的相应,具体返回的格式和联通定义
		String str = HttpClientUtil.sendXMLReq();
		//然后我们解析str就是对方给我们信息了这次请求就算结束了
		System.out.println(str);
	}
}
mysql数据备份脚本
#!/bin/bash
#This is a ShellScript For Auto DB Backup
#Powered by aspbiz
#2012-06
#Setting
#设置数据库名,数据库登录名,密码,备份路径,日志路径,数据文件位置,以及备份方式
#默认情况下备份方式是tar,还可以是mysqldump,mysqldotcopy
#默认情况下,用root(空)登录mysql数据库,备份至/root/dbxxxxx.tgz
DBName=ebook
DBUser=root
DBPasswd=www.ruanko.com
BackupPath=/root/mysqlbackup/
LogFile=/root/mysqlbackup/db.log
DBPath=/var/lib/mysql/
#BackupMethod=mysqldump
#BackupMethod=mysqlhotcopy
#BackupMethod=tar
#Setting End
NewFile="$BackupPath"db$(date +%y%m%d).tgz
DumpFile="$BackupPath"db$(date +%y%m%d)
OldFile="$BackupPath"db$(date +%y%m%d --date='5 days ago').tgz
echo "-------------------------------------------" >> $LogFile
echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile
echo "--------------------------" >> $LogFile
#Delete Old File
if [ -f $OldFile ]
then
rm -f $OldFile >> $LogFile 2>&1
echo "[$OldFile]Delete Old File Success!" >> $LogFile
else
echo "[$OldFile]No Old Backup File!" >> $LogFile
fi
if [ -f $NewFile ]
then
echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile
else
case $BackupMethod in
mysqldump)
if [ -z $DBPasswd ]
then
mysqldump -u $DBUser --opt $DBName > $DumpFile
else
mysqldump -u $DBUser -p$DBPasswd --opt $DBName > $DumpFile
fi
tar czvf $NewFile $DumpFile >> $LogFile 2>&1
echo "[$NewFile]Backup Success!" >> $LogFile
rm -rf $DumpFile
;;
mysqlhotcopy)
rm -rf $DumpFile
mkdir $DumpFile
if [ -z $DBPasswd ]
then
mysqlhotcopy -u $DBUser $DBName $DumpFile >> $LogFile 2>&1
else
mysqlhotcopy -u $DBUser -p $DBPasswd $DBName $DumpFile >>$LogFile 2>&1
fi
tar czvf $NewFile $DumpFile >> $LogFile 2>&1
echo "[$NewFile]Backup Success!" >> $LogFile
rm -rf $DumpFile
;;
*)
/etc/init.d/mysqld stop >/dev/null 2>&1
tar czvf $NewFile $DBPath$DBName >> $LogFile 2>&1
/etc/init.d/mysqld start >/dev/null 2>&1
echo "[$NewFile]Backup Success!" >> $LogFile
;;
esac
fi
echo "------------------" >> $LogFile
jfreechart Demo jfreechart 学习demo 网络
package com.my.jfreechart.test;

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;

/**
 * 实际取色的时候一定要16位的,这样比较准确
 * 
 * @author new
 */
public class CreateChartServiceImpl
{
	private static final String CHART_PATH = "E:/test/";

	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		CreateChartServiceImpl pm = new CreateChartServiceImpl();
		// 生成饼状图
		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.png");
	}

	/**
	 * 生成分组的柱状图
	 */
	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();
			}
		}
	}

}
Global site tag (gtag.js) - Google Analytics