diff --git a/src/CallListener.java b/src/CallListener.java new file mode 100644 index 0000000..22f85d2 --- /dev/null +++ b/src/CallListener.java @@ -0,0 +1,61 @@ +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + + +public class CallListener { + + + ServerSocket ss; + String NickName; + boolean isBusy; + String ip; + Command c; + NickCommand nc; + + + /*CallListener(String NickName, boolean isBusy) throws IOException{ + ss=new ServerSocket(Connection.port); + + this.NickName=NickName; + this.isBusy=isBusy; + }*/ + + + Connection getConnection(Socket s) throws IOException{ + Connection c=new Connection(s); + c.chatApp2015(Connection.NickName); + if(isBusy){ + + c.userIsBusy(Connection.NickName); + c.disconnect(); + return null; + + }else{ + c.chatApp2015(NickName); + this.c=c.recieve(); + + if(this.c.type==CommandType.NICK){ + nc=(NickCommand) this.c; + return c; + }else{ + return null; + } + /**/ + } + } + + + void setBusy(boolean isBusy){ + this.isBusy=isBusy; + } + + + String getNickName(){ + return NickName; + } + + + + +} diff --git a/src/CallListenerThread.java b/src/CallListenerThread.java new file mode 100644 index 0000000..9844c78 --- /dev/null +++ b/src/CallListenerThread.java @@ -0,0 +1,63 @@ +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Observable; + + +public class CallListenerThread extends Observable implements Runnable { + + + CallListener cl; + Connection c; + String NickName; + volatile boolean b; + ServerSocket ss; + Socket s; + + + @Override + public void run() { + try{ + ss=new ServerSocket(Connection.port); + + while(true){ + + s=ss.accept(); + Connection c=new Connection(s); + + if(c!=null){ + CommandListenerThread clt=new CommandListenerThread(c); + clt.addObserver(Form.obj); + clt.start(); + c.chatApp2015(Connection.NickName); + } + + } + + }catch (IOException e) { + e.printStackTrace();} + + } + + + + + + void start(){ + b=false; + Thread t=new Thread(this); + t.start(); + } + + + void stop(){ + b=true; + } + + + Connection getConnection(){ + return this.c; + } + + +} diff --git a/src/Caller.java b/src/Caller.java new file mode 100644 index 0000000..369a375 --- /dev/null +++ b/src/Caller.java @@ -0,0 +1,23 @@ +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; + + +public class Caller { + + + InetAddress IP; + + + Caller(String ip) throws UnknownHostException{ + IP=InetAddress.getByName(ip); + } + + + Connection call() throws IOException{ + Connection c=new Connection(new Socket(IP, Connection.port)); + c.chatApp2015(Connection.NickName); + return c; + } +} diff --git a/src/Command.java b/src/Command.java new file mode 100644 index 0000000..910eb40 --- /dev/null +++ b/src/Command.java @@ -0,0 +1,41 @@ +import java.util.Scanner; + + +public class Command { + + CommandType type; + Command(CommandType type){ + this.type=type; + } + + + public static Command callCommand(String s){ + + //Scanner in=new Scanner(System.in); + if(s.contains("Accepted")) { + return new Command(CommandType.ACCEPT); + } + if(s.contains("Rejected")) { + return new Command(CommandType.REJECT); + } + if(s.contains("Disconnect")) { + return new Command(CommandType.DISCONNECT); + } + if(s.contains("ChatApp 2015")) { + return new NickCommand(CommandType.NICK, s.replaceAll("user ", "")); + } + if(s.contains("Message")) { + return new MessageCommand(CommandType.MESSAGE,s.replaceAll("Message", "")); + } + return null; + } + + public CommandType getType() { + return type; + } + + + + + +} diff --git a/src/CommandListenerThread.java b/src/CommandListenerThread.java new file mode 100644 index 0000000..ddb4b70 --- /dev/null +++ b/src/CommandListenerThread.java @@ -0,0 +1,44 @@ +import java.util.Observable; + + +public class CommandListenerThread extends Observable implements Runnable{ + + Connection c; + volatile boolean b; + volatile Command com; + + public CommandListenerThread(Connection c) { + this.c=c; + } + + @Override + public void run() { + // TODO Auto-generated method stub + this.addObserver(Form.obj); + while(b!=true){ + synchronized(this){ + this.com=c.recieve(); + setChanged(); + this.notifyObservers(com); + + } + } + } + + public void start() { + this.b=false; + Thread t=new Thread(this); + t.start(); + } + + + public void stop(){ + b=true; + } + + + Connection getConnection(){ + return this.c; + } + +} diff --git a/src/CommandType.java b/src/CommandType.java new file mode 100644 index 0000000..bb0774f --- /dev/null +++ b/src/CommandType.java @@ -0,0 +1,4 @@ + +public enum CommandType { + ACCEPT, REJECT, DISCONNECT, NICK, MESSAGE; +} diff --git a/src/Connection.java b/src/Connection.java new file mode 100644 index 0000000..d3d9493 --- /dev/null +++ b/src/Connection.java @@ -0,0 +1,96 @@ +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.Scanner; + + +class Connection { + + + private Socket socket; + + public final static int port=28411; + public static String NickName; + + private Scanner in; + private DataOutputStream out; + + + + public Connection(Socket socket) throws IOException{ + this.socket=socket; + + in=new Scanner(socket.getInputStream()); + out=new DataOutputStream(socket.getOutputStream()); + } + + + Command recieve(){ + Command c; + String s=in.nextLine(); + c=Command.callCommand(s); + return c; + } + + + void accept(){ + try { + out.writeUTF("Accpeted"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + void reject(){ + try { + out.writeUTF("Rejected"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + void disconnect(){ + try { + out.writeUTF("Disconnect"); + socket.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + void chatApp2015(String NickName){ + try { + out.writeUTF(new StringBuffer("ChatApp 2015").append(Connection.NickName).toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + /*void userIsBusy(String NickName){ + try { + out.writeUTF(new StringBuffer("ChatApp 2015").append(NickName).append("is busy").toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }*/ + + + void sendMessage(String message){ + try { + out.writeUTF(new StringBuffer("Message").append("\n").append(message).toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/src/Form.java b/src/Form.java new file mode 100644 index 0000000..9c33882 --- /dev/null +++ b/src/Form.java @@ -0,0 +1,331 @@ +import java.awt.BorderLayout; +import java.awt.Dimension; +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.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Observable; +import java.util.Observer; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; + + +public class Form implements Observer{ + + JFrame frame = new JFrame("ChatApp2015"); + + + JLabel TextNick = new JLabel(); + JLabel TextIP = new JLabel(); + JLabel forText3 = new JLabel(); + JLabel forText4 = new JLabel(); + + + JFrame frame1 = new JFrame(); //up wdw + JPanel mainPanel = new JPanel(); + JPanel nickip = new JPanel(); //íèê àéïè(?) + JPanel nickPanel = new JPanel(); + JPanel ipPanel = new JPanel(); + JPanel inputPanel = new JPanel(); + JPanel conPanel = new JPanel(); + JPanel outputPanel = new JPanel(); + JPanel panel1 = new JPanel(); + JPanel ioPanel = new JPanel(); + JPanel panel2 = new JPanel(); + + + TextField textfieldloclogin = new TextField(35); + TextField textfieldIP = new TextField(35); + JTextArea textArea = new JTextArea(); + JTextArea textfieldentermess = new JTextArea(); + + + JButton disconnect = new JButton("Disconnect"); + JButton accept = new JButton("Accept"); + JButton reject = new JButton("Reject"); + JButton apply = new JButton("Apply"); + JButton connect = new JButton("Connect"); + JButton send = new JButton("Send"); + + JScrollPane areaScrollPane = new JScrollPane(textArea); + + + private CommandListenerThread comlt; + private CallListenerThread clt; + public static Observer obj; + + + public String NickName; + public String ip; + + + public static void main(String[] args) { + // TODO Auto-generated method stub + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + new Form(); + } + }); + } + + public Form(){ + obj=this; + + clt=new CallListenerThread(); + clt.start(); + + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenWidth = screenSize.width; + int screenHeight = screenSize.height; + frame.setSize(400, 200); + + + mainPanel.setLayout(new BorderLayout()); + + + + + nickip.setOpaque(false); + nickip.setMaximumSize(new Dimension(screenWidth, screenHeight)); + nickip.setPreferredSize(new Dimension(screenWidth /3 ,screenHeight / 8));//input + nickip.setLayout(new BoxLayout(nickip, BoxLayout.X_AXIS)); + + + + nickPanel.setOpaque(false); + nickPanel.add(Box.createVerticalStrut(15)); + nickPanel.setLayout(new BoxLayout(nickPanel, BoxLayout.Y_AXIS)); + nickPanel.setPreferredSize(new Dimension(screenWidth/8,screenHeight / 8));//nickpanel + nickPanel.setMaximumSize(new Dimension(screenWidth/4,screenHeight / 4)); + nickPanel.setMinimumSize(new Dimension(screenWidth/8,screenHeight / 8)); + nickPanel.setOpaque(false); + + TextNick.setText("Nickname: "); + nickPanel.add(TextNick); + textfieldloclogin.setMaximumSize(new Dimension(200 , 25)); + nickPanel.add(textfieldloclogin); + nickPanel.add(apply); + + + ipPanel.setOpaque(false); + ipPanel.add(Box.createVerticalStrut(15)); + ipPanel.setLayout(new BoxLayout(ipPanel, BoxLayout.Y_AXIS)); + ipPanel.setPreferredSize(new Dimension(screenWidth/8,screenHeight / 8)); + ipPanel.setMaximumSize(new Dimension(screenWidth/4,screenHeight / 4)); + ipPanel.setMinimumSize(new Dimension(screenWidth/8,screenHeight / 8)); + ipPanel.setOpaque(false); + + TextIP.setText("IP for conection: "); + ipPanel.add(TextIP); + textfieldIP.setMaximumSize(new Dimension(200 , 25)); + ipPanel.add(textfieldIP, BorderLayout.SOUTH); + + + inputPanel.setOpaque(false); + inputPanel.setMaximumSize(new Dimension(screenWidth /2, screenHeight / 25)); + inputPanel.setPreferredSize(new Dimension(screenWidth /2 ,screenHeight / 25)); + inputPanel.setMinimumSize(new Dimension(screenWidth/2,screenHeight / 25)); + + inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS)); + + inputPanel.add(new JScrollPane(textfieldentermess)); + send.setEnabled(false); + inputPanel.add(send); + + + outputPanel.setOpaque(false); + outputPanel.setMaximumSize(new Dimension(screenWidth/2, 500)); + outputPanel.setPreferredSize(new Dimension(screenWidth/2 ,500)); + outputPanel.setMinimumSize(new Dimension(screenWidth/2,500)); + outputPanel.setLayout(new BorderLayout()); + areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + outputPanel.add(new JScrollPane(textArea)); + textArea.setEditable(false); + + + conPanel.setOpaque(false); + conPanel.setLayout(new BoxLayout(conPanel, BoxLayout.LINE_AXIS)); + disconnect.setEnabled(false); + conPanel.add(connect); + conPanel.add(disconnect); + + + + send.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + String message=textfieldentermess.getText(); + textArea.setText("You: "+message+"\n"); + if(comlt!=null){ + comlt.getConnection().sendMessage(message); + }else{ + clt.getConnection().sendMessage(message); + } + } + + }); + + + connect.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + ip=textfieldIP.getText(); + textArea.setText(ip +"\n"); + connect.setEnabled(false); + disconnect.setEnabled(true); + + + try{ + Caller c=new Caller(ip); + Connection con=c.call(); + if(con!=null){ + send.setEnabled(true); + + comlt=new CommandListenerThread(con); + comlt.addObserver((Observer) Form.this);//!!! + comlt.start(); + }else{ + textArea.setText("Error!" +"\n"); + + connect.setEnabled(true); + disconnect.setEnabled(false); + apply.setEnabled(true); + } + }catch(UnknownHostException e1){ + + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + }); + + + apply.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + Connection.NickName=textfieldloclogin.getText(); + apply.setEnabled(false); + } + + }); + + + + disconnect.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + send.setEnabled(false); + connect.setEnabled(true); + apply.setEnabled(true); + } + + }); + + frame1.setLocationRelativeTo(null); + + panel1.add(accept); + panel1.add(reject); + + forText3.setText("Somebody trying to get connection with you" + "\n"); + frame1.add(forText3); + + frame1.setSize(200, 100); + frame1.add(panel1, BorderLayout.SOUTH); + frame1.setAlwaysOnTop(true); + frame1.setVisible(false); //(?) + + + + + + ioPanel.setPreferredSize(new Dimension(screenWidth/2,600)); + ioPanel.setMaximumSize(new Dimension(screenWidth/2,600)); + ioPanel.setMinimumSize(new Dimension(screenWidth/2,600)); + + ioPanel.add(outputPanel, BorderLayout.CENTER); + ioPanel.add(inputPanel, BorderLayout.SOUTH); + frame.add(mainPanel); + mainPanel.add(ioPanel, BorderLayout.CENTER); + mainPanel.add(panel2, BorderLayout.EAST); + + mainPanel.add(nickip, BorderLayout.NORTH); + nickip.add(nickPanel); + nickip.add(ipPanel); + ipPanel.add(conPanel); + + + frame.pack(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + + } + +public void update(Observable o, Object arg){ + send.setEnabled(true); + connect.setEnabled(false); + + + MessageCommand mc; + Command com; + + + if(arg instanceof MessageCommand){ + mc=(MessageCommand) arg; + + textArea.setText(mc.getMessage()); + } + if(arg instanceof Command){ + com =(Command) arg; + if (com.getType()==CommandType.ACCEPT){ + textArea.setText("Accepted"); + connect.setEnabled(false); + disconnect.setEnabled(true); + send.setEnabled(true); + apply.setEnabled(false); + } + + if (com.getType()==CommandType.REJECT){ + textArea.setText("Declined"); + connect.setEnabled(true); + disconnect.setEnabled(false); + send.setEnabled(false); + apply.setEnabled(true); + } + + if (com.getType()==CommandType.DISCONNECT){ + textArea.setText("Disconnected"); + connect.setEnabled(true); + disconnect.setEnabled(false); + send.setEnabled(false); + apply.setEnabled(true); + } + + + + + + } +} + +} diff --git a/src/Interface.java b/src/Interface.java new file mode 100644 index 0000000..20b4033 --- /dev/null +++ b/src/Interface.java @@ -0,0 +1,25 @@ +/*import javax.swing.*; + +import java.awt.*; +import java.io.IOException; + +public class Interface { + + private static final Integer height = 400; + private static final Integer width = 600; + + public static void main(String[] args) throws IOException{ + + LabelFrame frame = new LabelFrame(); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(width, height); + frame.setResizable(false); + frame.setAlwaysOnTop(true); + frame.setLocationRelativeTo(null); + frame.setTitle("ChatAppMaxIvan"); + frame.setVisible(true); + + } + +}*/ \ No newline at end of file diff --git a/src/LabelFrame.java b/src/LabelFrame.java new file mode 100644 index 0000000..8d676d6 --- /dev/null +++ b/src/LabelFrame.java @@ -0,0 +1,279 @@ +/*import java.awt.*; +import java.awt.event.*; +import java.io.IOException; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.*; +import javax.swing.border.*; + + +public class LabelFrame extends JFrame implements Observer{ + /** + * + */ +/* private static final long serialVersionUID = -4789525072053991912L; + + JFrame frame=new JFrame("ChatApp"); + JFrame upfr=new JFrame(); + + JPanel panel = new JPanel(); + + JTextArea textArea=new JTextArea(); + JTextArea textAreaMessage=new JTextArea(); + + JButton send; //send + JButton connect; //connect + JButton apply; //apply + JButton disconnect; //disconnect + + JPanel main=new JPanel(); + JPanel nickname_ip=new JPanel(); + JPanel nickname=new JPanel(); + + + + + JLabel lable1; + JLabel lable2; + JLabel lable3; + JLabel lable4; + JLabel lable5; + + JTextField textfieldlogin; + JTextField textfieldIP; + JTextField textfieldloclogin; + JTextField textfieldentermess; + + JScrollPane Scroll = new JScrollPane(textArea); + + String name = "Чат"; + + Font font = new Font("Time New Romans", Font.BOLD, 13); + Color col = new Color(200, 200, 200); + LineBorder linebord = new LineBorder(Color.BLUE, 1); + + + String NickName; + String ip; + + CommandListenerThread comlt; + CallListenerThread clt; + + static Observer obj; + + + public static void main(String aggs[]){ + SwingUtilities.invokeLater(new Runnable(){ + + @Override + public void run() { + try { + new LabelFrame(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + }); + } + + + LabelFrame() throws IOException{ + obj=this; + + clt=new CallListenerThread(); + clt.start(); + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenWidth = screenSize.width; + int screenHeight = screenSize.height; + frame.setSize(screenWidth / 2, screenWidth / 2); + frame.setLocationRelativeTo(null); + + JPanel panel = new JPanel(); + panel.setLayout(null); + panel.setBackground(Color.white); + + lable1 = new JLabel("Nickname:"); + lable1.setFont(font); + lable1.setForeground(Color.blue); + lable1.setBounds(15, 20, 100, 30); + + lable2 = new JLabel("IPaddress:"); + lable2.setFont(font); + lable2.setForeground(Color.blue); + lable2.setBounds(250, 20, 100, 30); + + lable4 = new JLabel("UserNickName:"); + lable4.setFont(font); + lable4.setForeground(Color.blue); + lable4.setBounds(220, 50, 120, 30); + + textfieldlogin = new JTextField(); + textfieldlogin.setBounds(90, 22, 115, 25); + textfieldlogin.setBorder(linebord); + + textfieldIP = new JTextField(); + textfieldIP.setBounds(320, 22, 115, 25); + textfieldIP.setBorder(linebord); + + textfieldloclogin = new JTextField(); + textfieldloclogin.setBounds(320, 50, 115, 25); + textfieldloclogin.setBorder(linebord); + + textfieldentermess = new JTextField(); + textfieldentermess.setBounds(45, 315, 400, 25); + textfieldentermess.setBorder(linebord); + + apply = new JButton("Apply"); + apply.setFont(font); + apply.setBounds(90, 50, 115, 25); + apply.setForeground(Color.blue); + + lable3 = new JLabel(); + lable3.setBounds(45, 100, 505, 200); + lable3.setBorder(linebord); + + connect = new JButton("Connect"); + connect.setBounds(435, 22, 115, 25); + connect.setFont(font); + connect.setForeground(Color.blue); + + disconnect = new JButton("Disconnect"); + disconnect.setBounds(435, 50, 115, 25); + disconnect.setFont(font); + disconnect.setForeground(Color.blue); + + send = new JButton("Send"); + send.setBounds(450, 315, 100, 25); + send.setFont(font); + send.setForeground(Color.blue); + + panel.add(lable1); + panel.add(lable2); + panel.add(lable3); + panel.add(lable4); + panel.add(textfieldlogin); + panel.add(textfieldIP); + panel.add(textfieldloclogin); + panel.add(textfieldentermess); + panel.add(send); + panel.add(connect); + panel.add(apply); + panel.add(disconnect); + panel.add(Scroll); + + this.add(panel); + //textAreaMessage.setText("aaaaa"); + + Scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + panel.add(new JScrollPane(textArea)); + textArea.setEditable(false); + + send.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + String message=textfieldentermess.getText(); + long time=System.currentTimeMillis(); + String Stime = new SimpleDateFormat("HH:mm:ss").format(time); + String s="\n" + " " + NickName + " " + Stime + ":" + "\n" + " " + message + "\n"; + //textArea.append(); + textAreaMessage.setText(s); + if(comlt!=null){ + comlt.getConnection().sendMessage(message); + }else{ + clt.getConnection().sendMessage(message); + } + } + + }); + + + connect.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + ip=textfieldIP.getText(); + connect.setEnabled(false); + disconnect.setEnabled(true); + + try{ + Caller c=new Caller(NickName); + Connection con=c.call(); + if(con!=null){ + send.setEnabled(true); + + comlt=new CommandListenerThread(con); + comlt.addObserver(LabelFrame.this); + comlt.start(); + }else{ + //textArea.append(" could not connect ip addr: " + ip +"\n"); + + connect.setEnabled(true); + disconnect.setEnabled(false); + apply.setEnabled(true); + } + }catch(UnknownHostException e1){ + + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + }); + + + apply.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + NickName=textfieldloclogin.getText(); + apply.setEnabled(false); + } + + }); + + + + disconnect.addActionListener(new ActionListener(){ + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + send.setEnabled(false); + connect.setEnabled(false); + apply.setEnabled(true); + } + + }); + + + } + + @Override + public void update(Observable o, Object arg) { + // TODO Auto-generated method stub + send.setEnabled(true); + connect.setEnabled(false); + NickCommand c; + MessageCommand mc; + + if(arg instanceof NickCommand){ + c=(NickCommand) arg; + } + if(arg instanceof MessageCommand){ + mc=(MessageCommand) arg; + textArea.append("Message: "+mc.getMessage()+"\n"); + } + } + +}*/ \ No newline at end of file diff --git a/src/MessageCommand.java b/src/MessageCommand.java new file mode 100644 index 0000000..b984467 --- /dev/null +++ b/src/MessageCommand.java @@ -0,0 +1,27 @@ + +public class MessageCommand extends Command { + + + String message; + + + MessageCommand(CommandType type, String message){ + super(type); + this.setMessage(message); + } + + + MessageCommand(String message){ + super(CommandType.MESSAGE); + this.message=message; + } + + + void setMessage(String message){ + this.message=message; + } + + String getMessage(){ + return message; + } +} diff --git a/src/NickCommand.java b/src/NickCommand.java new file mode 100644 index 0000000..9d99eb5 --- /dev/null +++ b/src/NickCommand.java @@ -0,0 +1,39 @@ + +public class NickCommand extends Command { + + String NickName; + boolean busy; + + + NickCommand(CommandType type, String NickName){ + super(type); + this.NickName=NickName; + } + + + NickCommand(String s){ + super(CommandType.NICK); + if(s.contains("busy")){ + busy=true; + s=s.replace(" busy", ""); + } + s=s.replace("ChatApp 2015", ""); + NickName=s; + } + + + void setNickName(String NickName){ + this.NickName=NickName; + } + + + String getNickName(){ + return NickName; + } + + + boolean isBusy(){ + return busy; + } + +} diff --git a/src/ServerConnection.java b/src/ServerConnection.java new file mode 100644 index 0000000..452c2ff --- /dev/null +++ b/src/ServerConnection.java @@ -0,0 +1,243 @@ +import java.sql.Connection; +import java.sql.*; +import java.util.*; + +public class ServerConnection { + + private String serverAddress; + private String localNick; + + private Connection con; + private Statement st; + + public ServerConnection(){ + + } + + public ServerConnection(String address){ + this(address, null); + } + + public ServerConnection(String address, String nick){ + if(nick!=null) + setLocalNick(nick); + if(address!=null){ + setServerAddress(address); + connect(); + }// if + } + + public void connect(){ + if(isConnected()) + return; + assert(serverAddress != null && !serverAddress.trim().isEmpty()); + try { + con = DriverManager.getConnection(serverAddress,"guest","guest"); + st = con.createStatement(); + } catch (SQLException e) { + // TODO throw real error + e.printStackTrace(); + }// catch + } + + public void disconnect(){ + if(st!=null){ + try { + st.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + st = null; + } + if(con!=null){ + try { + con.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + con=null; + }// if + } + + public boolean isConnected(){ + return st != null; + } + + public String getServerAddress() { + return serverAddress; + } + + public void setServerAddress(String serverAddress) { + if(serverAddress.equals(this.serverAddress)) + return; + boolean connected = isConnected(); + if(connected){ + goOffline(); + disconnect(); + } + this.serverAddress = serverAddress; + if(connected) + connect(); + } + + public String getLocalNick() { + return localNick; + } + + public void setLocalNick(String newNick) { + assert newNick!=null; + newNick = safe(newNick); + if(newNick.equals(this.localNick)) + return; + + boolean online = false; + if(isConnected()){ + online = isNickOnline(localNick); + if(online) + goOffline(); + } + + this.localNick = newNick; + if(online) + goOnline(); + } + + public void goOnline(){ + goOnline(28411); + } + + public void goOnline(int port){ + assert localNick != null; + assert isConnected(); + String q = "INSERT INTO user (nick, ip, online, port) values ('"+localNick+"', SUBSTRING_INDEX(USER(),'@',-1), 1,'"+port+"');"; + try { + st.executeUpdate(q); + } catch (SQLException e) { + boolean nick_collision=true; + try{ + if(getIpForNick(localNick)!=null){ // if nick collision + q = "UPDATE user set ip=SUBSTRING_INDEX(USER(),'@',-1), online=1, port="+port+" WHERE nick='"+localNick+"';"; + nick_collision = true; + } + else{ // if address collision + q = "UPDATE user set nick='"+localNick+"', online=1 WHERE ip=SUBSTRING_INDEX(USER(),'@',-1) AND port="+port+";"; + nick_collision = false; + } + st.executeUpdate(q); + }catch(SQLException e2){ + try { + if(nick_collision) + st.execute("DELETE FROM user WHERE ip=SUBSTRING_INDEX(USER(),'@',-1) AND port="+port+";"); + else + st.execute("DELETE FROM user WHERE nick='"+localNick+"';"); + st.execute(q); + } catch (SQLException e3) { + e2.printStackTrace(); + }// catch3 + }// catch2 + }// catch + }// goOnline + + public void goOffline(){ + assert localNick != null; + assert isConnected(); + try { + st.execute("INSERT INTO user (nick, ip, online) values ('"+localNick+"', SUBSTRING_INDEX(USER(),'@',-1), 0) ON DUPLICATE KEY UPDATE ip=VALUES(ip), online=VALUES(online);"); + } catch (SQLException e) { + e.printStackTrace(); + }// catch + } + + public String getIpForNick(String nick){ + assert isConnected(); + assert nick!=null; + nick = safe(nick); + ResultSet rs; + try { + rs = st.executeQuery("SELECT ip FROM user WHERE nick='"+nick+"'"); + if(!rs.next()) + return null; + return rs.getString(1); + } catch (SQLException e) { + e.printStackTrace(); + }// catch + return null; + } + + public int getPortForNick(String nick){ + assert isConnected(); + assert nick!=null; + nick = safe(nick); + ResultSet rs; + try { + rs = st.executeQuery("SELECT port FROM user WHERE nick='"+nick+"'"); + if(!rs.next()) + return 0; + return rs.getInt(1); + } catch (SQLException e) { + e.printStackTrace(); + }// catch + return 0; + } + + public boolean isNickOnline(String nick){ + if(nick==null) + return false; + + assert isConnected(); + nick = safe(nick); + ResultSet rs; + try { + rs = st.executeQuery("SELECT online FROM user WHERE nick='"+nick+"'"); + if(!rs.next()) + return false; + return rs.getBoolean(1); + } catch (SQLException e) { + e.printStackTrace(); + }// catch + return false; + } + + public String[] getAllNicks(){ + assert isConnected(); + ResultSet rs; + List res = new ArrayList(); + try { + rs = st.executeQuery("SELECT nick FROM user;"); + while(rs.next()){ + String nick = rs.getString(1); + res.add(nick); + }// while + } catch (SQLException e) { + e.printStackTrace(); + }// catch + return res.toArray(new String[0]); + } + + private static String safe(String s){ + return s.replaceAll("['\";]", "").replaceAll("\\s", ""); + } + + public static void main(String[] args) { + String nick1 = "latin&кириллица"; + String nick2 = "another"; + + ServerConnection c = new ServerConnection(); + c.setServerAddress("jdbc:mysql://files.litvinov.in.ua/chatapp_server?characterEncoding=utf-8&useUnicode=true"); + c.connect(); + assert c.isConnected(); + c.setLocalNick(nick1); + System.out.println("Before: " + c.isNickOnline(nick1)); + c.goOnline(); + System.out.println("After: " + c.isNickOnline(nick1)); + c.goOffline(); + System.out.println("After offline: " + c.isNickOnline(nick1)); + + System.out.println("Another nick: " + c.isNickOnline(nick2)); + System.out.println("My ip: " + c.getIpForNick(nick1)); + System.out.println("Other ip: " + c.getIpForNick(nick2)); + + System.out.println("My port: " + c.getPortForNick(nick1)); + System.out.println("Other port: " + c.getPortForNick(nick2)); + }// main +}