12 Разработка игрового веб-сервера на Java. Примеры реализации на Java. Паттерн Context. События. Ввод/вывод. Время





base

src/base/Context.java

package base;

import java.util.HashMap;
import java.util.Map;

public class Context {
    private Map<Class<?>, Object> context = new HashMap<Class<?>, Object>();
    
    public void add(Class<?> clazz, Object object){
        if(context.containsKey(clazz)){
            //ERROR
        }
        context.put(clazz, object);
    }
    
    public Object get(Class<?> clazz){
        return context.get(clazz);
    }
}

events

src/events/MyEventListener.java

package events;

import java.util.EventObject;

public interface MyEventListener {
         public void handle(EventObject event);
}


src/events/MyEventListenerImpl.java

package events;

import java.util.EventObject;

public class MyEventListenerImpl implements MyEventListener {
    
    //some code 
    
    public void handle(EventObject event)   {
        //process event
    }
}



src/events/MyEventSource.java

package events;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EventObject;
import java.util.List;

public class MyEventSource {
      private List<MyEventListener> listeners = 
              Collections.synchronizedList(new ArrayList<MyEventListener>());
      
      public void addListener(MyEventListener listener) {
        listeners.add(listener);
      }
      
      public void removeListener(MyEventListener listener)  {
        listeners.remove(listener);
      }

      public void fireEvent()   {
        EventObject event = new EventObject(this);
        for(MyEventListener listner : listeners){
            listner.handle(event);
        }
      }
}


io

src/io/LinesReader.java

package io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class LinesReader {  
    public void read(){
        BufferedReader br = null;
        try{
            FileInputStream fstream = new FileInputStream("textfile.txt");
            DataInputStream in = new DataInputStream(fstream);
          
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            br = new BufferedReader(isr);
            
            String strLine;

            while ((strLine = br.readLine()) != null)   {
                System.out.println (strLine);
            }
          
        } catch (Exception e){
          System.err.println("Error: " + e.getMessage());
        } finally{
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }
        }
    }
}

src/io/SimpleFileReader.java

package io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SimpleFileReader {
    public static void main(String args[]) throws IOException { 
        FileReader fr = new FileReader("SimpleFileReader.java"); 
        BufferedReader br = new BufferedReader(fr); 
        String currentLine; 
        while((currentLine = br.readLine()) != null) { 
            System.out.println(currentLine); 
        } 
        fr.close(); 
    } 
}

time

src/time/TimeHelper.java

package time;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class TimeHelper {
    public static long getTimeInMs(){
        Date date = new Date();
        //return System.currentTimeMillis();
        return date.getTime();
    }
    
    public static int getPOSIX(){
        Date date = new Date();
        return (int)(date.getTime() / 1000);
    }
    
    public static String getUserDateFull(Locale locale){
        Date date = new Date();
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
        return dateFormatter.format(date);
    }
    
    public static String getUserDateShort(Locale locale){
        Date date = new Date();
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        return dateFormatter.format(date);
    }
    
    public static String getUserTimeFull(Locale locale){
        Date date = new Date();
        DateFormat dateFormatter = DateFormat.getTimeInstance(DateFormat.FULL, locale);
        return dateFormatter.format(date);
    }
    
    public static void sleep(int timeMs){
        try {
            Thread.sleep(timeMs);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


src/time/TimeServiceForContext.java

package time;

import java.util.Timer;
import java.util.TimerTask;

import base.Context;

public class TimeServiceForContext {
    
    public static TimeServiceForContext getFromContext(Context context){
        return (TimeServiceForContext) context.get(TimeServiceForContext.class);
    }
    
    public TimeServiceForContext(Context context){
        context.add(this.getClass(), this);
    }
    
    private Timer timer = null;
    
    public void start(){
        timer = new Timer();
    }
    
    public void stop(){
        if(timer != null){
            timer.cancel();
        }
    }
    
    public boolean sheduleTask(TimerTask task, long timeMs){
        if(timer!=null){
            timer.schedule(task, timeMs);
            return true;
        }
        return false;
    }
}

src/time/TimeService.java

package time;

import java.util.Timer;
import java.util.TimerTask;

public class TimeService {
    private static TimeService timeService;
    private Timer timer = null;
    
    public static TimeService instance(){
        if(timeService == null){
            timeService = new TimeService();
        }
        return timeService;
    }
    
    public void start(){
        timer = new Timer();
    }
    
    public void stop(){
        if(timer != null){
            timer.cancel();
        }
    }
    
    public boolean sheduleTask(TimerTask task, long timeMs){
        if(timer!=null){
            timer.schedule(task, timeMs);
            return true;
        }
        return false;
    }
    
    private TimeService(){};
}

vfs

src/vfs/VFS.java

package vfs;

import java.util.Iterator;

public interface VFS {
    boolean isExist(String path);
    
    boolean isDirectory(String path);
    
    String getAbsolutePath(String file);
    
    byte[] getBytes(String file);
    
    String getUFT8Text(String file);
    
    Iterator<String> getIterator(String startDir);
}

src/vfs/VFSImpl.java

package vfs;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class VFSImpl implements VFS {

    private String root;
    
    public VFSImpl(String root){
        this.root = root;
    }
    
    
    public boolean isDirectory(String path) {
        return new File(root + path).isDirectory();
    }

    
    public Iterator<String> getIterator(String startDir) {      
        return new FileIterator(startDir);
    }

    private class FileIterator implements Iterator<String>{

        private Queue<File> files = new LinkedList<File>();
        
        public FileIterator(String path){
            files.add(new File(root + path));
        }
        
        public boolean hasNext() {          
            return !files.isEmpty();
        }

        public String next() {
            File file = files.peek();
            if(file.isDirectory()){
                for(File subFile : file.listFiles()){
                    files.add(subFile);
                }
            }
            
            return files.poll().getAbsolutePath();
        }

        public void remove() {          
            
        }
        
    }

    @Override
    public String getAbsolutePath(String file) {
        return new File(root + file).getAbsolutePath();
    }


    @Override
    public boolean isExist(String path) {
        // TODO Auto-generated method stub
        return false;
    }


    @Override
    public byte[] getBytes(String file) {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public String getUFT8Text(String file) {
        // TODO Auto-generated method stub
        return null;
    }
    
}

main

src/main/Main.java

package main;

import java.util.Iterator;
import java.util.Locale;
import java.util.Random;
import java.util.TimerTask;

import base.Context;

import time.TimeHelper;
import time.TimeService;
import time.TimeServiceForContext;
import vfs.VFS;
import vfs.VFSImpl;

public class Main { 
    
    public static void main(String[] args) {
        //workWithRandom();     
        //workWithTime();
        //workWithTimer();
        //workWithContext();        
        workWithVFS();      
    }


    private static void workWithVFS() {
        VFS vfs= new VFSImpl("");
        System.out.append("Current path: " + vfs.getAbsolutePath(""));
        Iterator<String> iter = vfs.getIterator("./"); 
        while(iter.hasNext()){
            System.out.append(iter.next() + "\n");
        }
    }


    private static void workWithContext() {
        System.out.append("ENGLISH full time: " + TimeHelper.getUserTimeFull(Locale.ENGLISH) + '\n');   
        int timeMs = 5000;
        final Context context = new Context();
        TimeServiceForContext timeService = new TimeServiceForContext(context);
        timeService.start();
        timeService.sheduleTask(new TimerTask(){
             public void run() {
                System.out.append("Timer run!\n");
                System.out.append("ENGLISH full time: " + TimeHelper.getUserTimeFull(Locale.ENGLISH) + '\n');   
                TimeServiceForContext.getFromContext(context).stop();
             }
            
        }, timeMs);
    }


    private static void workWithTimer() {
        System.out.append("ENGLISH full time: " + TimeHelper.getUserTimeFull(Locale.ENGLISH) + '\n');   
        final int timeMs = 10000;
        TimeService.instance().start();
        TimeService.instance().sheduleTask(new TimerTask(){
             public void run() {
                System.out.append("Timer run!\n");
                System.out.append("ENGLISH full time: " + TimeHelper.getUserTimeFull(Locale.ENGLISH) + '\n');   
                TimeService.instance().stop();
             }
            
        }, timeMs);     
    }
    
    
    private static void workWithRandom() {
        Random rnd = new Random();
        System.out.append("R0: " + rnd.nextInt(100) + '\n');
        System.out.append("R1: " + rnd.nextInt(100) + '\n');
        System.out.append("R2: " + rnd.nextInt(100) + '\n');
        System.out.append('\n');
        
        Random rndOnLong = new Random(100500L);
        System.out.append("R(1L)0: " + rndOnLong.nextInt(100) + '\n');
        System.out.append("R(1L)1: " + rndOnLong.nextInt(100) + '\n');
        System.out.append("R(1L)2: " + rndOnLong.nextInt(100) + '\n');
        System.out.append('\n');
        
        Random rndOnTime = new Random(TimeHelper.getTimeInMs());
        System.out.append("R(Time)0: " + rndOnTime.nextInt(100) + '\n');
        System.out.append("R(Time)1: " + rndOnTime.nextInt(100) + '\n');
        System.out.append("R(Time)2: " + rndOnTime.nextInt(100) + '\n');
        System.out.append('\n');        
        
        System.out.append("Math.random(): " + Math.random() + '\n');
    }

    private static void workWithTime() {
        System.out.append("milliseconds: " + TimeHelper.getTimeInMs() + '\n');
        System.out.append("POSIX: " + TimeHelper.getPOSIX() + '\n');
        System.out.append('\n');
        System.out.append("ENGLISH full date: " + TimeHelper.getUserDateFull(Locale.ENGLISH) + '\n');
        System.out.append("GERMAN full date: " + TimeHelper.getUserDateFull(Locale.GERMAN) + '\n');
        System.out.append("FRENCH full date: " + TimeHelper.getUserDateFull(Locale.FRENCH) + '\n');
        System.out.append('\n');
        System.out.append("ENGLISH short date: " + TimeHelper.getUserDateShort(Locale.ENGLISH) + '\n');
        System.out.append("GERMAN short date: " + TimeHelper.getUserDateShort(Locale.GERMAN) + '\n');
        System.out.append("FRENCH short date: " + TimeHelper.getUserDateShort(Locale.FRENCH) + '\n');
        System.out.append('\n');
        System.out.append("ENGLISH full time: " + TimeHelper.getUserTimeFull(Locale.ENGLISH) + '\n');
        System.out.append("GERMAN full time: " + TimeHelper.getUserTimeFull(Locale.GERMAN) + '\n');
        System.out.append("FRENCH full time: " + TimeHelper.getUserTimeFull(Locale.FRENCH) + '\n');
        System.out.append('\n');
    }

}


--
https://github.com/vitaly-chibrikov/tp_java_2013_02/tree/master/lecture6