• 2007-09-14

    设计模式 MVC - [Java]

    /*
     * model 
     * observed
     */
    import java.util.*;

    public class ObservableInt extends Observable{
        int value;   
        public ObservableInt(){
            value = 0;
        }   
        public ObservableInt(int newValue){
            value = newValue;
        }   
        public synchronized void setValue(int newValue){
            value = newValue;
            setChanged();
            notifyObservers();
        }
        public synchronized int getValue(){
            return value;
        }
    }

    /*
     * view
     * observer to observe observed
     */
    import java.util.*;
    import java.awt.*;
    public class IntLabel extends Label implements Observer{
        private ObservableInt intValue;
       
        public IntLabel(ObservableInt theInt){

            intValue = theInt;
            intValue.addObserver(this);
            setText("" + intValue.getValue());
        }
       
        public void update(Observable abs, Object arg){
            setText("" + intValue.getValue());
        }

    }

     

    /*
     * control
     */
    import java.awt.Scrollbar;
    import java.util.*;
    import java.awt.Event;

    public class IntScrollbar extends Scrollbar implements Observer {
        private ObservableInt intValue;
       
        public IntScrollbar(ObservableInt newValue){
            super();
            intValue = newValue;
            intValue.addObserver(this);
            setValue(intValue.getValue());
        }

        public IntScrollbar(ObservableInt newValue, int orientation){
            super(orientation);
            intValue = newValue;
            intValue.addObserver(this);
            setValue(intValue.getValue());
        }
       
        public IntScrollbar(ObservableInt newValue, int orientation, int value, int pageSize, int lowValue, int highValue){
            super(orientation, value, pageSize, lowValue, highValue);
            intValue = newValue;
            intValue.addObserver(this);
            setValue(intValue.getValue());
        }
       
        public boolean handleEvent(Event evt){
            if(super.handleEvent(evt)){
                return true;
            }
           
            intValue.setValue(getValue());
            return true;
        }
       
        public void update(Observable obs, Object arg){
            setValue(intValue.getValue());
        }
    }
     

  • 2007-09-07

    设计模式 adaptor - [Java]

    //define interface

    public interface SomeEventListener extends EventListener{
           public void someEvent(EventObject e);
    };


    //implement interface
    public class SomeEventAdaptor implements SomeEventListener{
           public SomeEventAdaptor(TargetObject target){
               this.target = target;
           }
          
          public  void someEvent(java.util.EventObject e){
               target.userDefinedMethod();
           }
        
          private TargetObject target;
    }


    //fire what to do

    public class TargetObject {
           public TargetObject(){
               adaptor = new SomeEventAdaptor(this);
           }
           public void userDefinedMethod(){          
           }    
           private SomeEventAdaptor adaptor;
    }
     

    //how to use the adaptor
    public class SomeButton extends java.awt.Button{        
        public synchronized  void addSomeEventListener(SomeEventListener l) throws                                                                       java.util.TooManyListenersException{
        if(listener != null){
            listener = l;
           }else throw new java.util.TooManyListenersException();        
        }
        
        private void fireSomeEvent(){
            listener.someEvent(new java.util.EventObject(this));    
        }    
        private SomeEventListener listener = null;
    }

  • 转载 http://blog.csdn.net/ccsdba/archive/2007/08/29/1763893.aspx

     

    1Thinking in Java (Bruce Eckel)

    Thinking in Java, 3rd edition Bruce Eckel; Prentice Hall PTR2002 年)Java 编程思想:第3(陈昊鹏 等译; 机械工业出版社,2005 年)Eckel 的书对于学习如何在 Java 语言环境中使用好面向对象技术极其实用。书中大量的代码样例解释了他所介绍的概念。

    2Effective Java (Joshua Bloch)

    Effective Java: Programming Language Guide Joshua Bloch; Addison-Wesley2001 年)ffective Java 中文版 (潘爱民 ; 机械工业出版社,2003 年)本书是理解优秀 Java 程序设计原则的最佳书籍。大多数材料从其他的 “学习 Java 的书中根本找不到。他编写了该语言中大量有用的库。本书必读!

     3The Java Programming Language (Ken Arnold, James Gosling, David Holmes)

    The Java Programming Language Ken ArnoldJames GoslingDavid Holmes;Addison-Wesley2000 年)Java 编程语言(第 3 版) (虞万荣 等译,中国电力出版社,2003 年)这也许是能弄到的最好的 Java 入门读物。它并不是一个标准规范,而是一本介绍每门语言特性的可读书籍。这本书在严谨性和教育性方面权衡得很好,能够让懂编程的人迅速被 Java 语言(和其丰富的类库)所吸引。

     

    4Concurrent Programming in Java: Design Principles and Patterns (Doug Lea)

    Concurrent Programming in Java: Design Principles and Patterns, 2nd edition Doug Lea; Addison-Wesley1999 年)Java 并发编程—设计原则与模式(第二版) (赵涌 等译,中国电力出版社,2004 年)不是每个开发人员都需要如此细致地了解并发性,也不是每个工程师都能达到本书的水准,

     

    5Expert One-On-One J2EE Design and Development (Rod Johnson)

    Expert One-On-One J2EE Design and Development Rod Johnson)WROX: J2EE 设计开发编程指南 (魏海萍 译,电子工业出版社,2003 年)对于刚接触 J2EE 人来说,这是唯一的一本如实反映这项技术的书。本书收录了多年的成功经验和失败经验。

     

    6Refactoring (Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts)

    Refactoring: Improving the Design of Existing Code Martin FowlerKent BeckJohn BrantWilliam OpdykeDon Roberts; Addison-Wesley1999 年)重构:改善既有代码的设计(中文版) (侯捷 等译,中国电力出版社 2003 年)

     

    7Design Patterns (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides)

    Design Patterns: Elements of Reusable Object Oriented Software Erich GammaRichard HelmRalph JohnsonJohn Vlissides; Addison-Wesley1997 年)

    设计模式:可复用面向对象软件的基础 (李英军 等译,机械工业出版社 2005 年)这是一本在专业程序员圈子里更为有名的书,基于作者共同的绰号,这本书被认为是 “四人帮GOF)之书”。

     

    8Patterns of Enterprise Application Architecture (Martin Fowler)

    Patterns of Enterprise Application Architecture Martin Fowler; Addison-Wesley2002 年)

    企业应用架构模式 (王怀民 等译,机械工业出版社 2004 年)比起小型、一次性项目来说,企业开发当然代表了更大的挑战。那并不意味着企业开发带来的所有挑战都是新挑战。

     

    9UML Distilled (Martin Fowler)

    UML Distilled: A Brief Guide to the Standard Object Modeling Language Martin Fowler; Addison-Wesley 2003 年)UML精粹:标准对象语言简明指南(第3版) (徐家福 译,清华大学出版社 2005 年)

     

     

     

  • 2007-08-31

    UDP 通讯的例子 - [Java]

    这个服务器端一个迭代模型,tcp的服务器是并发模型

    //client

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;

    public class TimeCompare {

        private static final int TIME_PORT = 11113;
        private static final int TIME_OUT = 10000;
        private static final int SMALL_ARRAY = 1;
        private static final int TIME_ARRAY = 100;
       
        DatagramSocket timeSocket = null;
        private InetAddress remoteMachines[];//server address array
        private Date localTime;
        private DatagramPacket timeResponses[]; 
       
       
        public static void main(String[] args) {
            //if(args.length < 1){
            //    System.out.println("Usage: TimeCompare host1(host2...)");
            //    System.exit(1);
            //}
            args = new String[1];
            args[0] = "127.0.0.1";
            TimeCompare runCompare = new TimeCompare(args);
            runCompare.printTimes();
            System.exit(0);

        }
        /*
         * @get remote address
         * @create socket
         */
        public TimeCompare(String[] hosts){
            //assign each remoteMachines a address
            remoteMachines = new InetAddress[hosts.length];
            for(int hostsFound = 0; hostsFound < hosts.length; hostsFound++){
                try{
                    //assign address to a member
                    remoteMachines[hostsFound] = InetAddress.getByName(hosts[hostsFound]);
                }catch(UnknownHostException excpt){
                    remoteMachines[hostsFound] = null;
                    System.err.println("Unknown host" + hosts[hostsFound] + ":" + excpt);
                }
            }
           
            //create socket
            try{
                timeSocket = new DatagramSocket();           
            }catch(SocketException excpt){
                System.err.println("Unable to bind UDP socket:" + excpt);
                System.exit(1);           
            }
           
            getTimes();
        }

        public void getTimes(){
            DatagramPacket timeQuery;
            DatagramPacket response;
            byte emptyBuffer[];
            int datagramsSent = 0;
            //send require packet to each server
            for(int ips = 0; ips < remoteMachines.length; ips++){
                if(remoteMachines[ips]!= null ){
                    try{
                        emptyBuffer = new byte[SMALL_ARRAY];
                        timeQuery = new DatagramPacket(emptyBuffer, emptyBuffer.length, remoteMachines[ips], TIME_PORT);
                        timeSocket.send(timeQuery);   
                        datagramsSent++;
                    }catch(IOException excpt){
                        System.err.println("Unable to send to " + remoteMachines[ips] + ":" + excpt);
                    }
                }
            }
           
            localTime = new Date();
            timeResponses = new DatagramPacket[datagramsSent];
            try{
                timeSocket.setSoTimeout(TIME_OUT);           
            }catch(SocketException e){}
           
            try{
                for(int got = 0; got < timeResponses.length; got++){
                    emptyBuffer = new byte[TIME_ARRAY];
                    response = new DatagramPacket(emptyBuffer,emptyBuffer.length);
                    timeSocket.receive(response);
                    timeResponses[got] = response;
                }
            }catch(InterruptedIOException excpt){
                System.err.println("Timeout on receive:" + excpt);
            }catch(IOException excpt){
                System.err.println("Failed I/O:" + excpt);
            }
           
            timeSocket.close();
            timeSocket = null;       
        }
       
        protected void printTimes(){
            Date remoteTime;
            String timeString;
            long secondsOff;
            InetAddress dgAddr;
            SimpleDateFormat daytimeFormat;
           
            System.out.print("TIME COMPARISON \n\tCurrent time" + "is:" + localTime + "n\n");
            for(int hosts = 0; hosts < remoteMachines.length; hosts++){
               
                //make sure response address equals remote machine address
                if (remoteMachines[hosts] != null) {
                    boolean found = false;
                    int dataIndex;
                    for (dataIndex = 0; dataIndex < timeResponses.length; dataIndex++) {
                        if (timeResponses[dataIndex] != null) {
                            dgAddr = timeResponses[dataIndex].getAddress();
                            if (dgAddr.equals(remoteMachines[hosts])) {
                                found = true;
                                break;
                            }
                        }
                    }

                    //print remote address
                    System.out.println("Host:" + remoteMachines[hosts]);
                   
                    if (found) {
                        //get response time string
                        timeString = new String(timeResponses[dataIndex].getData());
                        int endOfLine = timeString.indexOf("\n");
                        if (endOfLine != -1) {
                            timeString = timeString.substring(0, endOfLine);
                        }

                        daytimeFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy HH:mm:ss");
                        //remoteTime = daytimeFormat.parse(timeString, new ParsePosition(0));
                        //secondsOff = (localTime.getTime() - remoteTime.getTime()) / 1000;
                        //secondsOff = Math.abs(secondsOff);
                        System.out.println("Time:" + timeString);
                        //System.out.println("Difference: " + secondsOff + "seconds\n");

                    } else {
                        System.out.println("Time: NO PESPOSNSE FROM" + "TOST\n");
                    }
                }
            }
        }
       
        protected void finalize(){
            if(timeSocket != null){
                timeSocket.close();
            }
        }
       
    }

     

     

    //server

    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;

    public class DaytimeServer {
        private static final int TIME_PORT = 11113;
        private DatagramSocket timeSocket = null;
        private static final int SMALL_ARRAY = 1;
        private static final int TIME_ARRAY = 100;
        private boolean keepRunning = true;
       

        public static void main(String[] args) {
            DaytimeServer server = new DaytimeServer();
            server.startServing();
        }
        /*
         * @ create a datagramsocket
         */
        public DaytimeServer(){
            try{
                timeSocket = new DatagramSocket(TIME_PORT);
            }catch(SocketException excpt){
                System.err.println("Unable to open socket:" + excpt);
            }
        }
       
        /**
         * @ receive data from client
         * @ send data and time to client
         */
        public void startServing(){
            DatagramPacket datagram;
            InetAddress clientAddr;
            int clientPort;
            byte dataBuffer[];
            String timeString;
           
            while(keepRunning){
                try{
                    dataBuffer = new byte[SMALL_ARRAY];
                    datagram = new DatagramPacket(dataBuffer, dataBuffer.length);
                    timeSocket.receive(datagram);
                   
                    clientAddr = datagram.getAddress();
                    clientPort = datagram.getPort();
                    dataBuffer = getTimeBuffer();
                   
                    datagram = new DatagramPacket(dataBuffer, dataBuffer.length, clientAddr, clientPort);
                    timeSocket.send(datagram);               
                }catch(IOException excep){
                    System.err.println("Failed I/O:" + excep);
                }
            }
           
            timeSocket.close();       
        }
       
        /*
         * @return data and time string
         */
        protected byte[] getTimeBuffer(){
            String timeString;
            SimpleDateFormat daytimeFormat;
            Date currentTime;
           
            currentTime = new Date();
            daytimeFormat = new SimpleDateFormat("EEEE, MMMMddd,yyyy HH:mm:ss");
            timeString = daytimeFormat.format(currentTime);
            return timeString.getBytes();   
           
        }
       
        protected void stop(){
            if(keepRunning){
                keepRunning = false;
            }
        }
       
        public void finalize(){
            if(timeSocket != null){
                timeSocket.close();
            }
        }

    }

     

  • //server

    import java.io.*;
    import java.net.*;
    import java.util.*;

    public class StockQuoteServer {

        //class members
        private static final int SERVER_PORT = 11112;
        private static final int MAX_CLIENTS = 50;       
        private static final File STOCK_QUOTES_FILE = new File("Stockquotes.txt");
        private ServerSocket listenStocket = null;
        private Hashtable stockInfo;  //save id and value
        private Date stockInfoTime;   //?
        private long stockFileMod;    //last modify time
        private boolean keepRunning = true;

        //main function
        public static void main(String[] args) {

            StockQuoteServer server = new StockQuoteServer();
            server.serveQuote();     
        }

        /*
         * 1 initalize hashtable stockInfo
         * 2 create server socket
         */
        public StockQuoteServer(){
           
            //get stock information
            if(!loadQuotes())
                System.exit(1);
            try{
                //create server socket
                listenStocket = new ServerSocket(SERVER_PORT, 2);           
            }catch(IOException excpt){
                System.err.println("Unable to listen on port" + SERVER_PORT + ":" + excpt);
                System.exit(1);
            }
        }

        /*
         * read id and value from the stock file
         * and write these data to the hashtable stockInfo
         */
        protected boolean loadQuotes(){
            String fileLine;
            StringTokenizer tokenize;
            String id;
            StringBuffer value;
           
            //read data from file
            //and make it to hashtable
            //i think it is the same as map
            try{
                BufferedReader stockInput = new BufferedReader(new FileReader(STOCK_QUOTES_FILE));
                //new hashtable
                stockInfo = new Hashtable();
                //read one line string from file
                while((fileLine = stockInput.readLine())!= null){
                    //new StringTokenizer
                    tokenize = new StringTokenizer(fileLine);
                    try{
                        //get upperCase id
                        id = tokenize.nextToken();
                        id = id.toUpperCase();
                        value = new StringBuffer();
                        //get other strings of the fileline
                        //and add it to the value with space each other
                        while(tokenize.hasMoreTokens()){
                            value.append(tokenize.nextToken());
                            if(tokenize.hasMoreTokens()){
                                value.append(" ");
                            }
                        }
                        //add id and value to the Hashtable
                        stockInfo.put(id, value.toString());

                    }catch(NullPointerException excpt){
                        System.err.println("Error creating stock data" + "entry:" + excpt);
                    }catch(NoSuchElementException excpt){
                        System.err.println("Invalid stock data record" + "in file:" + excpt);
                    }               
                }
                //close BufferedReader
                stockInput.close();
                stockFileMod = STOCK_QUOTES_FILE.lastModified();

            }catch(FileNotFoundException excpt){
                System.err.println("Unable to find file:" + excpt);
                return false;
            }catch(IOException excpt){
                System.err.println("Failed I/O:" + excpt);
                return false;
            }

            stockInfoTime = new Date();
            return true;
        }

        /*
         * 1. accept a client socket
         * 2. create one thread and run
         */
        public void serveQuote(){
           
            //client socket
            Socket clientSocket = null;
            try{
                while(keepRunning){
                   
                    //accept a client socket
                    clientSocket = listenStocket.accept();
                   
                    //make sure stock is new
                    if(stockFileMod != STOCK_QUOTES_FILE.lastModified()){
                        loadQuotes();
                    }

                    StockQuoteHandler newHandler = new StockQuoteHandler(clientSocket, stockInfo, stockInfoTime);
                    Thread newHandlerThread = new Thread(newHandler);
                    newHandlerThread.start();
                }

                listenStocket.close();

            }catch(IOException excpt){
                System.err.println("Failed I/O:" + excpt);
            }
        }

        protected void stop(){
            if(keepRunning){
                keepRunning = false;
            }
        }

        class StockQuoteHandler implements Runnable{
            private static final boolean AUTOFLUSH = true;
            private Socket mySocket = null;
            private PrintWriter clientSend = null;
            private BufferedReader clientReceive = null;
            private Hashtable stockInfo;
            private Date stockInfoTime;

            /*
             * constructor
             */
            public StockQuoteHandler(Socket newSocket, Hashtable info, Date time){
                mySocket = newSocket;
                stockInfo = info;
                stockInfoTime = time;
            }
           
            /*
             * receive command from client and send response
             * @see java.lang.Runnable#run()
             */
            public void run(){
                String nextLine;
                StringTokenizer tokens;
                String command;
                String quoteID;
                String quoteResponse;
                try{
                    clientSend = new PrintWriter(mySocket.getOutputStream(), AUTOFLUSH);
                    clientReceive = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
                   
                    //send HELLO and timestamp to client first
                    clientSend.println("+ HELLO" + stockInfoTime);
                   
                    //receive one line string from client
                    while((nextLine = clientReceive.readLine())!= null){
                       
                        //initialize StringTokenizer
                        tokens = new StringTokenizer(nextLine);
                        try{
                            //read command of client
                            command = tokens.nextToken();
                            if(command.equalsIgnoreCase("QUIT"))break; //quit
                            else if(command.equalsIgnoreCase("STOCK:")){//send client stock if asked stock
                                //get socket id
                                quoteID = tokens.nextToken();
                                //get socket id ' value
                                quoteResponse = getQuote(quoteID);
                                //send it client
                                clientSend.println(quoteResponse);
                            }else{
                                clientSend.println("-ERR UNKNOWN COMMMAD");
                            }
                        }catch(NoSuchElementException excpt){
                            clientSend.println("-ERR MALFORMED COMMMAND");
                        }
                    }

                    clientSend.println("+ BYE");

                }catch(IOException excpt){
                    System.err.println("Failed I/O:" + excpt);
                }finally{
                    try{
                        if(clientSend != null) clientSend.close();
                        if(clientReceive != null)clientReceive.close();
                        if(mySocket != null)mySocket.close();

                    }catch(IOException excpt){
                        System.err.println("Failed I/O:" + excpt);
                    }
                }
            }
            /*
             * get stock value by id and hashtable
             */
            protected String getQuote(String quoteID){
                String info;
                quoteID = quoteID.toUpperCase();
                info = (String)stockInfo.get(quoteID);
                if(info != null){
                    return "+" + quoteID + " " + info;
                }else{
                    return "-ERR UNKNOWN STOCK ID";
                }
            }
        }
    }
     

     

    //client

    import java.io.*;
    import java.net.*;

    public class StockQuoteClient {

        private static final int SERVER_PORT = 11112;
        private static final boolean AUTOFLUSH = true;
        private String serverName;                 //server name
        private Socket quoteSocket = null;         //socket
        private BufferedReader quoteReceive = null;//receive data
        private PrintWriter quoteSend = null;      //send data
        private String[] stockIDs;
        private String[] stockInfo;
        private String currentAsOf = null;//Time stamp of data
       
       
       
       
        public static void main(String[] args) {
            //if(args.length < 2){
            //    System.out.println("Usage: SocketQuoteClient<server><stock ids>");
            //    System.exit(1);
            //}
     
            args = new String[2];
            args[0]= "AAA";
            args[1]= "BBB";
            StockQuoteClient client = new StockQuoteClient(args);
           
            client.printQuotes(System.out);
           
            System.exit(0);
        }
       
        public StockQuoteClient(String[] args){
           
            String serverInfo;
           
            //server name
            serverName = null;//args[0];
           
            //
            stockIDs = new String[args.length -1];
            stockInfo = new String[args.length - 1];
           
            //initialize stockIDs array with args
            for(int index = 1; index < args.length; index++){
                stockIDs[index-1] = args[index];
            }
           
            //contact the server and return the hello message
            serverInfo = contactServer();
           
            //parse out the timestamp,which is everything after the first space
            if(serverInfo != null){
                currentAsOf = serverInfo.substring(serverInfo.indexOf(" ") - 1);
            }
           
            //send and receive data
            getQuotes();
           
            //quit
            quitServer();
        }
        
        /*
         * initalize input and output stream
         * receive hello and time stamp message
         */
        protected String contactServer(){

            String serverWelcome = null;
            try{
                //create socket
                quoteSocket = new Socket(serverName, SERVER_PORT);
                //initialize receive and send stream
                quoteReceive = new BufferedReader(new InputStreamReader(quoteSocket.getInputStream()));
                quoteSend = new PrintWriter(quoteSocket.getOutputStream(), AUTOFLUSH);

                //first receive HELLO and time stamp strings
                serverWelcome = quoteReceive.readLine();

            }catch(UnknownHostException except){
                System.err.println("Unknown host" +  serverName + ":" + except);
            }catch(IOException except){
                System.err.println("Failed I/0" + serverName + ":" + except);
            }

            return serverWelcome;
        }
       
        /*
         * send require and receive data
         */
        protected void getQuotes(){
            String response;
           
            if(connectOK()){
                try{
                    for(int index = 0; index < stockIDs.length; index ++){
                       
                        //send require
                        quoteSend.println("STOCK: " + stockIDs[index]);
                       
                        //receive response
                        response = quoteReceive.readLine();
                       
                        //set stocket value
                        stockInfo[index] = response.substring(response.indexOf(" ")+1);                   
                    }
                }catch(IOException excpt){
                    System.err.println("Failed I/O to" + serverName + ":" + excpt);
                }
            }
           
            //if the connection is still up
        }
       
        /*
         * send quit require
         * release resource
         */
        protected String quitServer(){
            String serverBye = null;
            try{
                if(connectOK()){
                    //send quit require
                    quoteSend.print("QUIT");
                   
                    //receive BYE message
                    serverBye = quoteReceive.readLine();
                }

                //release resources
                if(quoteSend != null)quoteSend.close();
                if(quoteReceive != null)quoteReceive.close();
                if(quoteSocket != null)quoteSocket.close();
            }catch(IOException excpt){
                System.err.print("Failed I/O to server" + serverName + ":" + excpt);
            }
            return serverBye;
        }
       
        /*
         * print stock information
         */
        public void printQuotes(PrintStream sendOutput){
            if(currentAsOf != null){
                sendOutput.print("INFORMATION ON REQUESTED QUOTES"
                        +"n\tCurrent As of :" + currentAsOf + "n\n");
                for(int index = 0; index < stockIDs.length; index++){
                    sendOutput.print(stockIDs[index] + ":");
                    if(stockInfo[index] != null){
                        sendOutput.println(" " + stockInfo[index]);
                        sendOutput.flush();}
                    else{
                        sendOutput.println();
                        sendOutput.flush();}
                   
                }
            }
        }
       
        /*
         * make sure socket, input and output stream ok
         */
        protected boolean connectOK(){
            return (quoteSend != null && quoteReceive != null && quoteSocket != null);
        }
    }