目录结构如下:
--bean
----------MessageBean.java
----------ReceiveBean.java
----------SenderBean.java
---gerry
----------ClientViewMain.java
----------IconThread.java
----------ShowThread.java
---images
----------pmt.gif
----------pmtwhite.gif
---lib
----------commons-beanutils-1.8.0.jar
----------commons-codec-1.3.jar
----------commons-collections-3.2.1.jar
----------commons-lang-2.4.jar
----------commons-logging-1.1.1.jar
----------ezmorph-1.0.6.jar
----------httpclient-4.0-beta2.jar
----------httpcore-4.0-beta3.jar
----------json-lib-2.3-jdk15.jar
---tools
----------ClientUtils.java
----------Native2AsciiUtils.java
----------TimeUtil.java
1.
json-lib-2.3-jdk15.jar
http://sourceforge.net/projects/json-lib/files
2.
http-client , http-core
http://hc.apache.org/
3.ezmorph-1.0.3.jar,commons-lang.jar,commons-logging.jar,commons-beanutils.jar,commons-collections-3.2.jar
可以下载jar包的网站http://www.docjar.com/
MessageBean.java
package bean;
public class MessageBean {
private String system_notice ;
private String created_at ;
private String plain_body ;
private String title ;
private String id ;
private String has_read ;
private String attach ;
private SenderBean sender ;
private ReceiveBean receiver ;
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getHas_read() {
return has_read;
}
public void setHas_read(String has_read) {
this.has_read = has_read;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlain_body() {
return plain_body;
}
public void setPlain_body(String plain_body) {
this.plain_body = plain_body;
}
public ReceiveBean getReceiver() {
return receiver;
}
public void setReceiver(ReceiveBean receiver) {
this.receiver = receiver;
}
public SenderBean getSender() {
return sender;
}
public void setSender(SenderBean sender) {
this.sender = sender;
}
public String getSystem_notice() {
return system_notice;
}
public void setSystem_notice(String system_notice) {
this.system_notice = system_notice;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
ReceiveBean.java
package bean;
public class ReceiveBean {
private String name ;
private String logo ;
private String domain ;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
SenderBean.java
package bean;
public class SenderBean {
private String name ;
private String logo ;
private String domain ;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ClientViewMain.java
package gerry;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.sf.json.JSONArray;
import org.apache.http.client.ClientProtocolException;
import tools.ClientUtils;
import tools.Native2AsciiUtils;
import tools.TimeUtil;
import bean.MessageBean;
/**
* @author Gerry Cheung(V1.0)
* @version 2010-09-03 (恋爱三个月纪念版)
*/
public class ClientViewMain {
/*User param setting*/
private static String user_name = "111" ;
private static String user_pass = "111" ;
private static String receive_name = "111" ;
private static boolean isproxy = false ;
/*System param*/
//The JE only can show fifteen rows by api
public static List<MessageBean> listBean = new ArrayList<MessageBean>();
public static String last_update_time = "2000/01/01 00:00:00.00" ;
private static URL pmt_url = ClientViewMain.class.getClass().getResource("/images/pmt.gif");
private static URL pmt_urlwhite = ClientViewMain.class.getClass().getResource("/images/pmtwhite.gif");
private static Image image = Toolkit.getDefaultToolkit().getImage(pmt_url);
private static java.awt.TrayIcon ti = new java.awt.TrayIcon(image);
private static int count = 0 ;
private static ShowThread showThread = new ShowThread();
private static IconThread iconThread = new IconThread();
private static int screenWidth =Toolkit.getDefaultToolkit().getScreenSize().width;
private static int screenHeight=Toolkit.getDefaultToolkit().getScreenSize().height;
//Login Frame
private static JFrame f1 = new JFrame("Login");
private static TextField tName = new TextField();
private static TextField tPass = new TextField();
private static TextField tReceive = new TextField();
private static JButton b_login = new JButton("Login");
//Send Frame
private static JFrame f2 = new JFrame("Send");
private static TextArea sContent = new TextArea("",10,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
private static JButton s_send = new JButton("Send");
//Show Last Message
private static JFrame f3 = new JFrame("Show");
private static TextArea textareashow = new TextArea("",10,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
//Show History
private static JFrame f4 = new JFrame("History");
private static TextArea textareahistory = new TextArea("",10,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
public static void systemTray(){
try{
if (SystemTray.isSupported()){
SystemTray st = SystemTray.getSystemTray();
PopupMenu menu = new PopupMenu();
menu.add("O(∩_∩)O From:2010-06-03 To forever... O(∩_∩)O");
menu.add("O(∩_∩)O Ling:Gerry in your heart ! O(∩_∩)O");
menu.add("O(∩_∩)O GerryLing [恋爱三个月纪念版] O(∩_∩)O");
MenuItem item0 = new MenuItem();
item0.setLabel("Send");
item0.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
sendMessage();
}
});
menu.add(item0);
MenuItem item1 = new MenuItem();
item1.setLabel("Refresh");
item1.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
receiveNewMessage();
}
});
menu.add(item1);
MenuItem item3 = new MenuItem();
item3.setLabel("History");
item3.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
receiveMessage();
}
});
menu.add(item3);
menu.add("About Version1.0 2010-09-03");
MenuItem item2 = new MenuItem();
item2.setLabel("Quit");
item2.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae){
showThread.stop();
iconThread.stop();
System.exit(0);
}
});
menu.add(item2);
//show last message
ti.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae){
showLastListMsg();
}
});
ti.setToolTip ("["+user_name+"]"+"You have 0 message to Read !");
ti.setPopupMenu (menu);
st.add(ti);
}
}catch (Exception e){
System.exit(0);
}
}
public static String receiveMessage(){
String strResult = null;
try {
strResult = ClientUtils.getJsonContent("api.iteye.com","api/messages/inbox", user_name,user_pass,isproxy);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Use JSON-LIB parse data
JSONArray jsonArray = JSONArray.fromObject(Native2AsciiUtils.ascii2Native(strResult));
MessageBean[] beans = (MessageBean[])JSONArray.toArray(jsonArray, MessageBean.class);
String strMsg = "" ;
for(int i=0;i<beans.length;i++){
strMsg = strMsg + "No."+(i+1)+": ["+beans[i].getCreated_at()+"] "+beans[i].getSender().getName()+" :"+beans[i].getPlain_body()+"\n";
}
if(null!=strMsg && !"".equals(strMsg)){
textareahistory.setText(strMsg);
f4.setSize(550, 200);
f4.setLocation((screenWidth-f4.getWidth())/2, (screenHeight-f4.getHeight())/2);
f4.setResizable(true);
Container contentPane = f4.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,2));
contentPane.add(textareahistory);
f4.show();
}
return Native2AsciiUtils.ascii2Native(strResult);
}
/**
* Get the new msg
* @return
*/
public static List<MessageBean> showLastListMsg(){
String strMsg = "" ;
for(int i=0;i<listBean.size();i++){
MessageBean bean = listBean.get(i);
Timestamp stamp1 = TimeUtil.getTimeFromString(bean.getCreated_at());
Timestamp stamp2 = TimeUtil.getTimeFromString(last_update_time);
long diff = TimeUtil.timeDiff2Timestamp(stamp1, stamp2);
if(diff>0){
last_update_time = bean.getCreated_at();//取最后一条记录的时间
}
strMsg = strMsg + "No."+(i+1)+": ["+bean.getCreated_at()+"] "+bean.getSender().getName()+" :"+bean.getPlain_body()+"\n";
}
//Show List on the Window
if(null!=strMsg && !"".equals(strMsg)){
textareashow.setText(strMsg);
f3.setSize(550, 200);
f3.setLocation((screenWidth-f3.getWidth())/2, (screenHeight-f3.getHeight())/2);
f3.setResizable(true);
Container contentPane = f3.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,2));
contentPane.add(textareashow);
f3.show();
}
for(int i=0;i<listBean.size();i++){
listBean.remove(i);
i--;
}
ti.setToolTip ("["+user_name+"]"+"You have "+listBean.size()+" message to Read !");
return listBean ;
}
public static int receiveNewMessage(){
String strResult = null;
try {
strResult = ClientUtils.getJsonContent("api.iteye.com","api/messages/inbox", user_name,user_pass,isproxy);
strResult = Native2AsciiUtils.ascii2Native(strResult);
JSONArray jsonArray = JSONArray.fromObject(Native2AsciiUtils.ascii2Native(strResult));
MessageBean[] beans = (MessageBean[])JSONArray.toArray(jsonArray, MessageBean.class);
for(int i=0;i<listBean.size();i++){
listBean.remove(i);
i--;
}
for(int i=0;i<beans.length;i++){
Timestamp stamp1 = TimeUtil.getTimeFromString(beans[i].getCreated_at());
Timestamp stamp2 = TimeUtil.getTimeFromString(last_update_time);
long diff = TimeUtil.timeDiff2Timestamp(stamp1, stamp2);
if(diff > 0){
listBean.add(beans[i]);
}
}
} catch (Exception e) {
Label label1 = null;
JFrame f = new JFrame("Error");
f.setLocation((screenWidth-250)/2, (screenHeight-80)/2);
f.setSize(250, 80);
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new Label("username/password is incorrect!"+"or Error:"+e.getMessage());
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1,1));
contentPane.add(label1);
//f.pack();
f.show();
}
return 1 ;
}
public static int receiveNewMessageIcon(){
// If have new msg ,there must to change the status of the program!
if(listBean.size()>0){
ti.setToolTip ("["+user_name+"]"+"You have "+listBean.size()+" message to Read !");
if(count%2==0){
ti.setImage(Toolkit.getDefaultToolkit().getImage(pmt_urlwhite));
}else{
ti.setImage(Toolkit.getDefaultToolkit().getImage(pmt_url));
}
}else{
count = 0 ;
ti.setImage(Toolkit.getDefaultToolkit().getImage(pmt_url));
}
if(count==1000000000){count=0;}
count++ ;
return 1 ;
}
public static String sendMessage(){
f2.setSize(500, 180);
f2.setLocation((screenWidth-f2.getWidth())/2, (screenHeight-f2.getHeight())/2);
f2.setResizable(true);
Container contentPane = f2.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,2));
s_send.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae){
String str=null;
String strResult = null;
str = sContent.getText();
try {
//The third param is true for proxy,false for no proxy .
f2.hide();
str = str.replaceAll("\r", "[Line]");
str = str.replaceAll("\n", "");
//str = str.replaceAll(" ", "");
str = str.replaceAll("\"", "“");
strResult = ClientUtils.getJsonContent("api.iteye.com","api/messages/create?title=Message:&receiver_name="+receive_name+"&body="+str, user_name,user_pass,isproxy);
JOptionPane pane = new JOptionPane();
pane.showMessageDialog(null, "Message sent successfully!");
} catch (Exception e) {
f2.hide();
JOptionPane pane = new JOptionPane();
pane.showMessageDialog(null, "Message failed,Please try again!");
}
}
});
contentPane.add(sContent);
contentPane.add(s_send);
f2.show();
return "" ;
}
public static void main(String[] args){
Container contentPane = f1.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,3));
Label label1 = new Label("please input the username,userpass,receivename by order !");
tPass.setEchoChar('*');
b_login.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae){
user_name = tName.getText();
user_pass = tPass.getText();
receive_name = tReceive.getText();
showThread.start();
iconThread.start();
f1.hide();
systemTray();
}
});
f1.setSize(350, 150);
f1.setLocation((screenWidth-f1.getWidth())/2, (screenHeight-f1.getHeight())/2);
f1.setResizable(false);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.add(label1);
contentPane.add(tName);
contentPane.add(tPass);
contentPane.add(tReceive);
contentPane.add(b_login);
//f1.pack();
f1.show();
}
}
IconThread.java
package gerry;
public class IconThread extends Thread{
public long times = 500L ; //500ms
public IconThread(){}
@SuppressWarnings("static-access")
public void run() {
while(true){
ClientViewMain.receiveNewMessageIcon();//图标闪动
try {
this.sleep(times);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ShowThread.java
package gerry;
public class ShowThread extends Thread{
public long times = 30000L ; //30000ms
public ShowThread(){}
@SuppressWarnings("static-access")
public void run() {
while(true){
ClientViewMain.receiveNewMessage();//程序后台接收数据
try {
this.sleep(times);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
images 文件夹
两个图片文件:pmt.gif 托盘图标
pmtwhite.gif 16X16透明图片
ClientUtils.java
package tools;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class ClientUtils {
/**
* 基于Basic认证的httpclient 连接
* @param hostUrl 要请求的host name 如:http://api.iteye.com/api/twitters/list -> api.iteye.com
* @param getUrl 要请求的get url 如:http://api.iteye.com/api/twitters/list -> api/twitters/list
* @param userName username
* @param password password
* @param isProxy isProxy
* @return javaeye api 返回的json字符串
* @throws IOException
* @throws ClientProtocolException
*/
public static String getJsonContent(String hostUrl,String getUrl,String userName,String password,boolean isProxy) throws ClientProtocolException, IOException{
String jsonStr="";
getUrl = getUrl.replaceAll(" ", ",");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(new AuthScope(hostUrl, 80), new UsernamePasswordCredentials(userName, password));
BasicHttpContext localcontext = new BasicHttpContext();
BasicScheme basicAuth = new BasicScheme();
localcontext.setAttribute("preemptive-auth", basicAuth);
httpclient.addRequestInterceptor((HttpRequestInterceptor) new PreemptiveAuth(), 0);
HttpHost targetHost = new HttpHost(hostUrl);
//Set proxy
if(isProxy){
HttpHost proxy = new HttpHost("openproxy.xxx.com",8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet httpget = new HttpGet("/" + getUrl);
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
if (entity != null) {
jsonStr = EntityUtils.toString(entity);
//System.out.println(jsonStr);
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return jsonStr;
}
static class PreemptiveAuth implements HttpRequestInterceptor {
public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(
new AuthScope(
targetHost.getHostName(),
targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}
}
}
}
Native2AsciiUtils.java
package tools;
/**
* 仿照JDK-native2ascii.exe功能实现的(Java源代码)
* Unicode编码转码
* 2010-08-06
* @author Gerry
* @version 1.0
*/
public class Native2AsciiUtils {
/**
* prefix of ascii string of native character
*/
private static String PREFIX = "\\u";
/**
* Native to ascii string. It's same as execut native2ascii.exe.
* @param str
* native string
* @return ascii string
*/
public static String native2Ascii(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
sb.append(char2Ascii(chars[i]));
}
return sb.toString();
}
/**
* Native character to ascii string.
* @param c
* native character
* @return ascii string
*/
private static String char2Ascii(char c) {
if (c > 255) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX);
int code = (c >> 8);
String tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
code = (c & 0xFF);
tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
return sb.toString();
} else {
return Character.toString(c);
}
}
/**
* Ascii to native string. It's same as execute native2ascii.exe -reverse.
* @param str
* ascii string
* @return native string
*/
public static String ascii2Native(String str) {
StringBuilder sb = new StringBuilder();
int begin = 0;
int index = str.indexOf(PREFIX);
while (index != -1) {
sb.append(str.substring(begin, index));
sb.append(ascii2Char(str.substring(index, index + 6)));
begin = index + 6;
index = str.indexOf(PREFIX, begin);
}
sb.append(str.substring(begin));
return sb.toString();
}
/**
* Ascii to native character.
* @param str
* ascii string
* @return native character
*/
private static char ascii2Char(String str) {
if (str.length() != 6) {
throw new IllegalArgumentException("Ascii string of a native character must be 6 character.");
}
if (!PREFIX.equals(str.substring(0, 2))) {
throw new IllegalArgumentException("Ascii string of a native character must start with \"\\u\".");
}
String tmp = str.substring(2, 4);
int code = Integer.parseInt(tmp, 16) << 8;
tmp = str.substring(4, 6);
code += Integer.parseInt(tmp, 16);
return (char) code;
}
}
TimeUtil.java
package tools;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
public class TimeUtil {
/**
*
* Notes: 格式转换
* @param strTime
* @return
* Created:2010-8-11
* @author:Gerry
*/
public static Timestamp getTimeFromString(Object strTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH);
Date date = new Date();
if (!strTime.equals("")) {
try {
String s=strTime.toString();
if(s.indexOf(".")!=-1){
if(s.substring(s.indexOf(".")).length()>4){
s=s.substring(0, s.indexOf(".")+4);
}
}
date = format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
Timestamp t = new Timestamp(date.getTime());
return t;
}
/**
* 计算指定的两个时间的时间差数值
* @param time
* @param anotherTime "2009-12-12 00:55:25.000 "
* 前面的时间减去后面的时间
* @return
*/
public static long timeDiff2Timestamp(Timestamp time, Timestamp anotherTime) {
long timeDiff = 1000;// 时间的差数值
timeDiff = time.getTime()-anotherTime.getTime();
return timeDiff;
}
/**
* 当前时间
* Notes:TODO Please specify the functions of the method.
* @return
* Created:2010-8-11
* @author:Gerry
*/
public static String getCurrentTimeString() {
return getCurrentTimeByFormat("yyyy/MM/dd HH:mm:ss");
}
private static String getCurrentTimeByFormat(String format) {
GregorianCalendar calendar = new GregorianCalendar();
java.util.Date date = calendar.getTime();
SimpleDateFormat sformat = new SimpleDateFormat(format);
String currentDate = sformat.format(date);
return currentDate;
}
}