基于JavaEye-API实现的Gerry-聊天Dos版v1.0

目录结构如下:

--bean
----------MessageBean.java
----------ReceiveBean.java
----------SenderBean.java

---je
----------ClientUtilsMain.java
----------ReadThread.java

---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;   
        }   
         
         
         
}   

 

  

  

ClientUtilsMain.java


package je;   
  
import java.io.BufferedReader;   
import java.io.IOException;   
import java.io.InputStreamReader;   
import java.sql.Timestamp;   
import java.util.ArrayList;   
import java.util.List;   
  
import net.sf.json.JSONArray;   
  
import org.apache.http.client.ClientProtocolException;   
import tools.ClientUtils;   
import tools.Native2AsciiUtils;   
import tools.TimeUtil;   
import bean.MessageBean;   
  
/**  
 *   
 * Notes:Main Class  
 * Created:2010-8-9  
 * @author:Gerry  
 * @version:1.0  
 */   
public class ClientUtilsMain {   
    /*User param setting*/   
    private static String  user_name = "11" ;   
    private static String  user_pass = "11" ;   
    private static String  receive_name = "11" ;   
    private static boolean isproxy = true ;   
    private static final  String  NOTICE_STR = "Notice: `.refresh; 1.shownew ; 2.send ;3.history; 4.cls screen ; 5.help ; 6.exit" ;   
  
    /*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" ;   
  
    /**  
     * @param  args  
     * @throws Exception   
     * @throws Exception   
     */   
  
    @SuppressWarnings("deprecation")   
    public static void main(String[] args) throws Exception {   
        System.out.println("please input your username:");   
        BufferedReader stdin1 =new BufferedReader(new InputStreamReader(System.in));    
        String str1=stdin1.readLine();    
        if(!str1.equals("")){user_name = str1 ;}   
           
        System.out.println("please input your password:");   
        String str2=stdin1.readLine();    
        if(!str2.equals("")){user_pass = str2 ;}   
           
        System.out.println("please input your receivename:");   
        String str3=stdin1.readLine();    
        if(!str3.equals("")){receive_name = str3 ;}   
           
        clsScreen();   
        showNotice();   
           
        //Read line   
        ReadThread readThread = new ReadThread();   
        readThread.start();   
           
        while(true){   
            System.out.println("+++++++++++++++++++++++++++++++++++");   
            String str=stdin1.readLine();    
            if(str!=null){   
                if(str.equals("`") || str.equals("refresh")){   
                    receiveNewMessage();   
                }   
                if(str.equals("1")){   
                    showLastListMsg();   
                }   
                if(str.equals("2")){   
                    System.out.println("please wait...");   
                    sendMessage();   
                    clsScreen();   
                    showNotice();   
                }   
                if(str.equals("3")){   
                    System.out.println("please wait...");   
                    receiveMessage();   
                }   
                if(str.equals("4") || str.equals("cls")){   
                    //Process k = Runtime.getRuntime().exec("cmd /c cls");   
                    clsScreen();   
                }   
                if(str.equals("5") || str.equals("help")){   
                    showNotice();   
                }   
                if(str.equals("6") || str.equals("exit")){   
                    readThread.stop();   
                    break;   
                }   
            }   
        }   
           
    }  


public static List<MessageBean> showLastListMsg(){   
  
           
        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();//取最后一条记录的时间   
            }   
            System.out.println("No."+(i+1)+": ["+bean.getCreated_at()+"] "+bean.getSender().getName()+" :"+bean.getPlain_body());   
        }   
           
        for(int i=0;i<listBean.size();i++){   
            listBean.remove(i);   
            i--;   
        }   
           
        return listBean ;   
    }   
       
       
    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);   
        for(int i=0;i<beans.length;i++){   
           System.out.println("No."+(i+1)+": ["+beans[i].getCreated_at()+"] "+beans[i].getSender().getName()+" :"+beans[i].getPlain_body());   
        }   
        return Native2AsciiUtils.ascii2Native(strResult);   
    }   
       
       
    public static int receiveNewMessage(){   
  
        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();   
        }   
        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]);   
            }   
        }   
  
        if(listBean.size()>0){   
            System.out.println("Notice: There is "+listBean.size()+" to press 1 shownew!");   
        }   
        return 1 ;   
    }   
       
       
    public static String sendMessage() throws Exception {   
  
        String str=null;   
        String strResult = null;   
        System.out.println("Please input the text:");   
        BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));    
        str=stdin.readLine();    
        try {   
            //The third param is true for proxy,false for no proxy .   
            strResult = ClientUtils.getJsonContent("api.iteye.com","api/messages/create?title=Message:&receiver_name="+receive_name+"&body="+str, user_name,user_pass,isproxy);   
        } catch (ClientProtocolException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        System.out.println(Native2AsciiUtils.ascii2Native(strResult));   
        return "" ;   
    }   
       
       
    public static String showNotice(){   
        System.out.println(NOTICE_STR);   
        return "" ;   
    }    
       
       
    public static String clsScreen(){   
        for(int i=0;i<10;i++){   
            System.out.println("");   
        }   
        return "" ;   
    }   
       
  
}  

 

  

ReadThread.java

package je;   
  
  
public class ReadThread extends Thread{   
  
    public long times = 30000L ; //30000ms   
       
    public ReadThread(){}   
       
    @SuppressWarnings("static-access")   
    public void run()  {   
        while(true){   
            ClientUtilsMain.receiveNewMessage();//程序后台接收数据   
            try {   
                this.sleep(times);   
            } catch (InterruptedException e) {   
                e.printStackTrace();   
            }   
        }   
    }   
       
       
}   

 

  

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;   
    }   
       
}   

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值