refactored

This commit is contained in:
Hannes Dürr
2020-12-19 13:54:01 +01:00
parent 1585766b5a
commit 302d193651
9 changed files with 102 additions and 22 deletions
+69
View File
@@ -0,0 +1,69 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import chatProg.controller.ReceiveAdapter;
import chatProg.controller.CommandConnect;
import chatProg.controller.CommandSend;
import chatProg.model.ChatModel;
import chatProg.view.ChatView;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import chatProg.logger.OhmLogger;
/**
* Builder Class
* @author chris, hd
*/
public class Start
{
private static Logger lg = OhmLogger.getLogger();
public Start()
{
JFrame frm = new JFrame();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ChatView view = new ChatView();
ChatModel model = new ChatModel();
CommandConnect cmdConnect = new CommandConnect(view, model);
cmdConnect.registerEvents();
CommandSend cmdSend = new CommandSend(view, model);
cmdSend.registerEvents();
ReceiveAdapter recAdapter = new ReceiveAdapter(view, model);
recAdapter.subscribe();
view.setVisible(true);
view.setTitle("Chat");
view.setSize(800, 600);
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
new Start();
new Start();
}
}
@@ -0,0 +1,73 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Logger;
import chatProg.logger.OhmLogger;
import chatProg.model.ChatModel;
import chatProg.view.ChatView;
/**
*
* @author hd, chris
*/
public class CommandConnect implements ActionListener
{
private static Logger lg = OhmLogger.getLogger();
ChatView view;
ChatModel model;
private static final int PORT = 35000;
private static final String IP_ADRESSE = "127.0.0.1";
public CommandConnect(ChatView view, ChatModel transmitter)
{
this.view = view;
this.model = transmitter;
}
public void registerEvents(){
view.getBtnSetServer().addActionListener(this);
view.getBtnSetClient().addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
// connect to server
if(src == view.getBtnSetServer()){
synchronized (this){
try {
view.getLblType().setText("Server");
model.setServer(PORT);
} catch (IOException ex) {
lg.severe(ex.toString());
}
}
}
// connect to vlient
if(src == view.getBtnSetClient()){
synchronized (this){
try {
view.getLblType().setText("Client");
model.setClient(PORT, IP_ADRESSE);
} catch (IOException ex) {
lg.severe(ex.toString());
}
}
}
}
}
+52
View File
@@ -0,0 +1,52 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Logger;
import chatProg.logger.OhmLogger;
import chatProg.model.ChatModel;
import chatProg.view.ChatView;
/**
*
* @author hd, christ
*/
public class CommandSend implements ActionListener
{
private static Logger lg = OhmLogger.getLogger();
ChatView view;
ChatModel model;
public CommandSend(ChatView view, ChatModel model)
{
this.view = view;
this.model = model;
}
public void registerEvents(){
view.getBtnSend().addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if(src == view.getBtnSend()){
String msg = view.getTxtField().getText();
if(msg != ""){
model.sendMessage(msg);
view.getLblStatusDialog().setText("Nachricht gesendet");
view.getjTextArea().append("Ich: " + msg +"\n");
}
view.getTxtField().setText("");
}
}
}
@@ -0,0 +1,64 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.controller;
import java.util.concurrent.Flow;
import java.util.logging.Logger;
import chatProg.logger.OhmLogger;
import chatProg.model.ChatModel;
import chatProg.view.ChatView;
/**
*
* @author hd, chris
*/
public class ReceiveAdapter implements Flow.Subscriber<String>
{
private static Logger lg = OhmLogger.getLogger();
private ChatView view;
private ChatModel model;
private Flow.Subscription subscription;
public ReceiveAdapter(ChatView view, ChatModel model)
{
this.view = view;
this.model = model;
}
public void subscribe()
{
model.addSubscription(this);
}
@Override
public void onSubscribe(Flow.Subscription subscription)
{
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(String item)
{
view.getLblStatusDialog().setText("Nachricht empfangen");
view.getjTextArea().append("Partner: " + item + "\n");
subscription.request(1);
//System.out.println(item);
}
@Override
public void onError(Throwable throwable)
{
}
@Override
public void onComplete()
{
}
}
+26
View File
@@ -0,0 +1,26 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.logger;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
/**
*
* @author chris
*/
public class MyFormatter extends Formatter {
@Override
public String format(LogRecord lr) {
String date = String.format("%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp", new Date(lr.getMillis()));
String s = ("| ")+lr.getMillis()+(" | ")+date+(" | ")+lr.getLevel().toString()+(" | ")+lr.getSourceClassName()+(" | ")+lr.getMessage()+(" | ")+"\n";
return s;
}
}
+54
View File
@@ -0,0 +1,54 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.logger;
import chatProg.logger.MyFormatter;
import java.io.File;
import java.io.IOException;
import java.util.logging.*;
/**
*
* @author chris, hd
*/
public class OhmLogger
{
public OhmLogger()
{
}
private static Logger lg = null;
public static Logger getLogger()
{
if (lg == null)
{
lg = Logger.getLogger("OhmLogger");
initLogger();
}
return lg;
}
private static void initLogger()
{
try{
String datei = System.getProperty("java.io.tmpdir") + File.separator + "log.txt";
FileHandler fh = new FileHandler(datei);
ConsoleHandler ch = new ConsoleHandler();
lg.addHandler(fh);
ch.setFormatter(new MyFormatter());
lg.setUseParentHandlers(false);
lg.addHandler(ch);
lg.setLevel(Level.ALL);
}
catch(IOException ioex)
{
System.err.println(ioex);
}
}
}
+141
View File
@@ -0,0 +1,141 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.model;
import chatProg.logger.OhmLogger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author hd, chris
*/
public class ChatModel implements Runnable
{
private static Logger lg = OhmLogger.getLogger();
private ExecutorService eService;
private SubmissionPublisher<String> iPublisher;
private volatile boolean laufend;
String nachricht;
BufferedReader in;
PrintWriter out;
private Socket socket;
public ChatModel()
{
laufend = false;
iPublisher = new SubmissionPublisher<>();
eService = Executors.newSingleThreadExecutor();
}
public void addSubscription(Flow.Subscriber<String> subscriber)
{
iPublisher.subscribe(subscriber);
}
public synchronized void start(){
laufend = true;
eService.submit(this);
this.notifyAll();//muss sync
lg.info("startet");
}
@Override
public void run()
{
while(true){
try {
nachricht = in.readLine();
lg.info("Nachricht empfangen: " + nachricht);
iPublisher.submit(nachricht);//wenn neue Nachricht
} catch (IOException ex) {
lg.log(Level.SEVERE, ex.toString());
}
}
}
public void setSocket(Socket s) throws IOException {
InputStream iStream = s.getInputStream();
OutputStream oStream = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(iStream, "UTF-8");
OutputStreamWriter osr = new OutputStreamWriter(oStream, "UTF-8");
in = new BufferedReader(isr);
//BufferedWriter out = new BufferedWriter(osr);
out = new PrintWriter(osr);
start();
}
public void setClient(int PORT, String IP_ADRESSE) throws IOException
{
Thread connectThread = new Thread(new Runnable() {
@Override
public void run() {
try {
lg.info("Client: verbinde ...");
Socket s = new Socket(IP_ADRESSE, PORT); // Achtung: blockiert!
lg.info("Client: Verbindung hergestellt");
setSocket(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
connectThread.start();
}
public void setServer(int PORT) throws IOException
{
Thread connectThread = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket sSocket = new ServerSocket(PORT);
lg.info("Server: Warte auf Verbindung ...");
Socket s = sSocket.accept(); // Achtung: blockiert!
lg.info("Server: Verbindung akzeptiert");
setSocket(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
connectThread.start();
}
public void sendMessage(String msg)
{
if(laufend){
lg.log(Level.INFO, "Sende Nachricht: " + msg);
out.println(msg);
out.flush();
}
else{
lg.log(Level.INFO, "Keine Verbindung!");
}
}
}
+112
View File
@@ -0,0 +1,112 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
<Property name="title" type="java.lang.String" value="ChatTool"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="First"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridLayout">
<Property name="columns" type="int" value="0"/>
<Property name="rows" type="int" value="1"/>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="lblType">
</Component>
<Component class="javax.swing.JButton" name="btnSetClient">
<Properties>
<Property name="text" type="java.lang.String" value="Client"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnSetServer">
<Properties>
<Property name="text" type="java.lang.String" value="Server"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JButton" name="btnSend">
<Properties>
<Property name="text" type="java.lang.String" value="Send"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="After"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="lblStatusDialog">
<Properties>
<Property name="text" type="java.lang.String" value="&quot;&quot;"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Last"/>
</Constraint>
</Constraints>
</Component>
<Container class="javax.swing.JPanel" name="jPanel2">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridLayout">
<Property name="columns" type="int" value="1"/>
<Property name="rows" type="int" value="2"/>
</Layout>
<SubComponents>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTextArea" name="jTextArea">
<Properties>
<Property name="editable" type="boolean" value="false"/>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="cc" green="cc" red="cc" type="rgb"/>
</Property>
<Property name="columns" type="int" value="20"/>
<Property name="rows" type="int" value="5"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JTextField" name="txtField">
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="txtFieldActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>
+237
View File
@@ -0,0 +1,237 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatProg.view;
/**
*
* @author hd
*/
public class ChatView extends javax.swing.JFrame
{
/**
* @return the jTextArea
*/
public javax.swing.JTextArea getjTextArea()
{
return jTextArea;
}
/**
* @return the btnSend
*/
public javax.swing.JButton getBtnSend()
{
return btnSend;
}
/**
* @return the btnSetClient
*/
public javax.swing.JButton getBtnSetClient()
{
return btnSetClient;
}
/**
* @return the btnSetServer
*/
public javax.swing.JButton getBtnSetServer()
{
return btnSetServer;
}
/**
* @return the lblStatusDialog
*/
public javax.swing.JLabel getLblStatusDialog()
{
return lblStatusDialog;
}
/**
* @param lblStatusDialog the lblStatusDialog to set
*/
public void setLblStatusDialog(javax.swing.JLabel lblStatusDialog)
{
this.lblStatusDialog = lblStatusDialog;
}
/**
* @return the lblType
*/
public javax.swing.JLabel getLblType()
{
return lblType;
}
/**
* @param lblType the lblType to set
*/
public void setLblType(javax.swing.JLabel lblType)
{
this.lblType = lblType;
}
/**
* @return the txtField
*/
public javax.swing.JTextField getTxtField()
{
return txtField;
}
/**
* @param txtField the txtField to set
*/
public void setTxtField(javax.swing.JTextField txtField)
{
this.txtField = txtField;
}
/**
* Creates new form chatView
*/
public ChatView()
{
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
jPanel1 = new javax.swing.JPanel();
lblType = new javax.swing.JLabel();
btnSetClient = new javax.swing.JButton();
btnSetServer = new javax.swing.JButton();
btnSend = new javax.swing.JButton();
lblStatusDialog = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea = new javax.swing.JTextArea();
txtField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("ChatTool");
jPanel1.setLayout(new java.awt.GridLayout(1, 0));
jPanel1.add(lblType);
btnSetClient.setText("Client");
jPanel1.add(btnSetClient);
btnSetServer.setText("Server");
jPanel1.add(btnSetServer);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);
btnSend.setText("Send");
getContentPane().add(btnSend, java.awt.BorderLayout.LINE_END);
lblStatusDialog.setText("\"\"");
getContentPane().add(lblStatusDialog, java.awt.BorderLayout.PAGE_END);
jPanel2.setLayout(new java.awt.GridLayout(2, 1));
jTextArea.setEditable(false);
jTextArea.setBackground(new java.awt.Color(204, 204, 204));
jTextArea.setColumns(20);
jTextArea.setRows(5);
jScrollPane1.setViewportView(jTextArea);
jPanel2.add(jScrollPane1);
txtField.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
txtFieldActionPerformed(evt);
}
});
jPanel2.add(txtField);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtFieldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_txtFieldActionPerformed
{//GEN-HEADEREND:event_txtFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFieldActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new ChatView().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnSend;
private javax.swing.JButton btnSetClient;
private javax.swing.JButton btnSetServer;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea;
private javax.swing.JLabel lblStatusDialog;
private javax.swing.JLabel lblType;
private javax.swing.JTextField txtField;
// End of variables declaration//GEN-END:variables
}