Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f7652201c | ||
|
|
cb8e9c9bd1 | ||
|
|
c2bf3f5a9d | ||
|
|
350a2ad301 | ||
|
|
1d9faa93f8 | ||
|
|
e5eb4f3f9c | ||
|
|
581a924afc | ||
|
|
7a699cd280 | ||
|
|
88b75ad75f | ||
|
|
d551324e8b | ||
|
|
9b45d515ba | ||
|
|
2e50dacee7 | ||
|
|
a628490fcb | ||
|
|
395363e4bd | ||
|
|
12497594e4 | ||
|
|
6a597092fe | ||
|
|
ffd474e7ff | ||
|
|
4d39648ee7 | ||
|
|
095af14463 | ||
|
|
d0083e8069 | ||
|
|
dda324228f | ||
|
|
840183ee9f | ||
|
|
eb3ce132cd | ||
|
|
d1dc427185 | ||
|
|
7c9e61ce0f | ||
|
|
6538dac8af | ||
|
|
67813e4881 | ||
|
|
4cc07a3754 | ||
|
|
fa696194aa | ||
|
|
9fb4952f32 | ||
|
|
96b8faca5b | ||
|
|
cac549f1ee | ||
|
|
a86f4dbf82 | ||
|
|
23559dcc06 | ||
|
|
fa4ee046b1 | ||
|
|
0c71a85cba | ||
|
|
e7c8983775 | ||
|
|
0ec3129a22 | ||
|
|
ba2f41daf7 | ||
|
|
57059c3ef0 | ||
|
|
7168431bcd | ||
|
|
0b7c67fef6 | ||
|
|
15ea8ac207 | ||
|
|
b5bbd1df2d | ||
|
|
93ac292f72 | ||
|
|
b610ec20e1 | ||
|
|
4461772ebf | ||
|
|
0d5a4dbe75 | ||
|
|
bbb1ceea23 | ||
|
|
7d9ca4ca71 | ||
|
|
1fcc03d9be |
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
#Mon, 17 Aug 2026 14:26:26 -0300
|
#Fri, 02 Oct 2026 20:11:21 -0300
|
||||||
|
|
||||||
|
|
||||||
C\:\\Users\\extre\\OneDrive\\Documentos\\Faculdade\\2026_02\\Monitoria\\Pitiupi\\pitiupi.chat=
|
C\:\\Users\\extre\\OneDrive\\Documentos\\Faculdade\\2026_02\\Monitoria\\Pitiupi\\pitiupi.chat=
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File renamed without changes.
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="module-library">
|
||||||
|
<library>
|
||||||
|
<CLASSES>
|
||||||
|
<root url="jar://$MODULE_DIR$/../../pitiupi/dist/pitiupi.jar!/" />
|
||||||
|
</CLASSES>
|
||||||
|
<JAVADOC />
|
||||||
|
<SOURCES />
|
||||||
|
</library>
|
||||||
|
</orderEntry>
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
@@ -4,28 +4,29 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.chat.GUI;
|
package pitiupi.chat.GUI;
|
||||||
|
|
||||||
import java.awt.event.ActionEvent;
|
import pitiupi.models.Menus.MulticastMenus.MulticastMenu;
|
||||||
import javax.swing.JMenu;
|
import pitiupi.models.Menus.MulticastMenus.MulticastSubMenu;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author flavio
|
* @author flavio
|
||||||
*/
|
*/
|
||||||
public class ChatMenu extends JMenu {
|
public class ChatMenu extends MulticastSubMenu {
|
||||||
|
ChatMulticastMenu chatMulticastMenu;
|
||||||
private final ChatWindow chatWindow;
|
|
||||||
private javax.swing.JMenuItem menuItem;
|
|
||||||
|
|
||||||
public ChatMenu(ChatWindow chatWindow) {
|
public ChatMenu(ChatWindow chatWindow) {
|
||||||
this.chatWindow = chatWindow;
|
this.chatMulticastMenu = new ChatMulticastMenu(chatWindow);
|
||||||
this.setText("Chat");
|
|
||||||
menuItem = new javax.swing.JMenuItem();
|
|
||||||
menuItem.setText("Show Chat Window");
|
|
||||||
menuItem.addActionListener(this::chatMenuActionPerformed);
|
|
||||||
this.add(menuItem);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void chatMenuActionPerformed(ActionEvent ae) {
|
@Override
|
||||||
this.chatWindow.setVisible(true);
|
public String getText() {
|
||||||
|
return "Chat";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<MulticastMenu> getMenus() {
|
||||||
|
return List.of(chatMulticastMenu);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package pitiupi.chat.GUI;
|
||||||
|
|
||||||
|
import pitiupi.models.Menus.MulticastMenus.MulticastActionMenu;;
|
||||||
|
|
||||||
|
public class ChatMulticastMenu extends MulticastActionMenu {
|
||||||
|
ChatWindow chatWindow;
|
||||||
|
|
||||||
|
public ChatMulticastMenu(ChatWindow chatWindow) {
|
||||||
|
this.chatWindow = chatWindow;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return "Show Chat Window";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onClick() {
|
||||||
|
chatWindow.setVisible(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,34 +5,33 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.chat.GUI;
|
package pitiupi.chat.GUI;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.logging.Level;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
import pitiupi.chat.net.ChatMessage;
|
import pitiupi.chat.net.ChatMessage;
|
||||||
import pitiupi.GUI.MainWindow;
|
import pitiupi.control.ConnectionManager;
|
||||||
import pitiupi.net.Message;
|
import pitiupi.models.Messages.Message;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author flavio
|
* @author flavio
|
||||||
*/
|
*/
|
||||||
public class ChatWindow extends javax.swing.JDialog {
|
public class ChatWindow extends JDialog {
|
||||||
|
|
||||||
private javax.swing.JButton jButton1;
|
private JButton jButton1;
|
||||||
private javax.swing.JEditorPane jEditorPane1;
|
private JEditorPane jEditorPane1;
|
||||||
private javax.swing.JPanel jPanel1;
|
private JPanel jPanel1;
|
||||||
private javax.swing.JPanel jPanel2;
|
private JPanel jPanel2;
|
||||||
private javax.swing.JScrollPane jScrollPane1;
|
private JScrollPane jScrollPane1;
|
||||||
private javax.swing.JScrollPane jScrollPane2;
|
private JScrollPane jScrollPane2;
|
||||||
private javax.swing.JSplitPane jSplitPane1;
|
private JSplitPane jSplitPane1;
|
||||||
private javax.swing.JTextArea jTextArea1;
|
private JTextArea jTextArea1;
|
||||||
|
|
||||||
private final MainWindow mainWindow;
|
private final ConnectionManager connectionManager;
|
||||||
|
|
||||||
public ChatWindow(MainWindow mainWindow) {
|
public ChatWindow(ConnectionManager connectionManager) {
|
||||||
this.mainWindow = mainWindow;
|
this.connectionManager = connectionManager;
|
||||||
initComponents();
|
initComponents();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,23 +42,23 @@ public class ChatWindow extends javax.swing.JDialog {
|
|||||||
*/
|
*/
|
||||||
private void initComponents() {
|
private void initComponents() {
|
||||||
|
|
||||||
this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
|
this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
|
||||||
this.setTitle("Chat Window");
|
this.setTitle("Chat Window");
|
||||||
this.setBounds(new java.awt.Rectangle(0, 0, 800, 600));
|
this.setBounds(new java.awt.Rectangle(0, 0, 800, 600));
|
||||||
this.getContentPane().setLayout(new java.awt.BorderLayout(5, 5));
|
this.getContentPane().setLayout(new java.awt.BorderLayout(5, 5));
|
||||||
this.setPreferredSize(new java.awt.Dimension(800, 600));
|
this.setPreferredSize(new java.awt.Dimension(800, 600));
|
||||||
|
|
||||||
jSplitPane1 = new javax.swing.JSplitPane();
|
jSplitPane1 = new JSplitPane();
|
||||||
jScrollPane1 = new javax.swing.JScrollPane();
|
jScrollPane1 = new JScrollPane();
|
||||||
jEditorPane1 = new javax.swing.JEditorPane();
|
jEditorPane1 = new JEditorPane();
|
||||||
jPanel1 = new javax.swing.JPanel();
|
jPanel1 = new JPanel();
|
||||||
jScrollPane2 = new javax.swing.JScrollPane();
|
jScrollPane2 = new JScrollPane();
|
||||||
jTextArea1 = new javax.swing.JTextArea();
|
jTextArea1 = new JTextArea();
|
||||||
jPanel2 = new javax.swing.JPanel();
|
jPanel2 = new JPanel();
|
||||||
jButton1 = new javax.swing.JButton();
|
jButton1 = new JButton();
|
||||||
|
|
||||||
jSplitPane1.setDividerLocation(500);
|
jSplitPane1.setDividerLocation(500);
|
||||||
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
|
jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT);
|
||||||
jEditorPane1.setContentType("text/html");
|
jEditorPane1.setContentType("text/html");
|
||||||
jPanel1.setLayout(new java.awt.BorderLayout());
|
jPanel1.setLayout(new java.awt.BorderLayout());
|
||||||
jTextArea1.setColumns(20);
|
jTextArea1.setColumns(20);
|
||||||
@@ -94,17 +93,13 @@ public class ChatWindow extends javax.swing.JDialog {
|
|||||||
if (jTextArea1.getText().trim().isEmpty()) {
|
if (jTextArea1.getText().trim().isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ChatMessage message = new ChatMessage(mainWindow.getUserName(), jTextArea1.getText());
|
ChatMessage message = new ChatMessage(connectionManager.getUserName(), jTextArea1.getText());
|
||||||
this.sendChatMessage(message);
|
this.sendChatMessage(message);
|
||||||
jTextArea1.setText("");
|
jTextArea1.setText("");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendChatMessage(Message message) {
|
public void sendChatMessage(Message message) {
|
||||||
try {
|
connectionManager.sendUdpMulticast(message);
|
||||||
mainWindow.getSocketUDP().sendMulticast(message.toByteArray());
|
|
||||||
} catch (IOException ex) {
|
|
||||||
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void receiveChatMessage(ChatMessage message) {
|
public void receiveChatMessage(ChatMessage message) {
|
||||||
|
|||||||
@@ -5,14 +5,14 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.chat.net;
|
package pitiupi.chat.net;
|
||||||
|
|
||||||
import pitiupi.net.Message;
|
|
||||||
import pitiupi.net.Message;
|
import pitiupi.models.Messages.Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author flavio
|
* @author flavio
|
||||||
*/
|
*/
|
||||||
public class ChatMessage extends Message{
|
public class ChatMessage extends Message {
|
||||||
|
|
||||||
private String text;
|
private String text;
|
||||||
private String name;
|
private String name;
|
||||||
|
|||||||
@@ -4,48 +4,43 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.chat.plugin;
|
package pitiupi.chat.plugin;
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
import java.util.ArrayList;
|
||||||
import java.io.IOException;
|
import java.util.Collection;
|
||||||
import java.io.ObjectInputStream;
|
import java.util.List;
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.chat.GUI.ChatMenu;
|
import pitiupi.chat.GUI.ChatMenu;
|
||||||
import pitiupi.chat.GUI.ChatWindow;
|
import pitiupi.chat.GUI.ChatWindow;
|
||||||
import pitiupi.chat.net.ChatMessage;
|
import pitiupi.chat.net.ChatMessage;
|
||||||
import pitiupi.net.Message;
|
import pitiupi.control.ConnectionManager;
|
||||||
import pitiupi.plugin.Plugin;
|
import pitiupi.control.GuiManager;
|
||||||
|
import pitiupi.models.Menus.MenuCategory;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.models.Plugin;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author flavio
|
* @author flavio
|
||||||
*/
|
*/
|
||||||
public class ChatPlugin implements Plugin {
|
public class ChatPlugin extends Plugin {
|
||||||
|
|
||||||
private ChatWindow chatWindow;
|
private ChatWindow chatWindow;
|
||||||
private MainWindow mainWindow;
|
|
||||||
|
|
||||||
public ChatPlugin() {
|
@Override
|
||||||
|
public void createPlugin(ConnectionManager connectionManager, GuiManager guiManager) {
|
||||||
|
this.chatWindow = new ChatWindow(connectionManager);
|
||||||
|
guiManager.createMenu(MenuCategory.Social, new ChatMenu(chatWindow));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void createPlugin(MainWindow mainWindow) {
|
public List<Class<? extends Message>> getMessages() {
|
||||||
this.mainWindow = mainWindow;
|
return List.of(ChatMessage.class);
|
||||||
this.chatWindow = new ChatWindow(mainWindow);
|
|
||||||
this.mainWindow.addMenu(new ChatMenu(chatWindow));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void receiveMessage(byte[] message) {
|
public void receiveMessage(Message message) {
|
||||||
ByteArrayInputStream bis = new ByteArrayInputStream(message);
|
if (message instanceof ChatMessage msg) {
|
||||||
ObjectInputStream ois;
|
this.chatWindow.receiveChatMessage(msg);
|
||||||
try {
|
|
||||||
ois = new ObjectInputStream(bis);
|
|
||||||
if (ois.readObject() instanceof ChatMessage msg) {
|
|
||||||
this.chatWindow.receiveChatMessage(msg);
|
|
||||||
}
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println(ex.toString());
|
|
||||||
} catch (ClassNotFoundException ex) {
|
|
||||||
System.out.println(ex.toString());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +60,9 @@ public class ChatPlugin implements Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Message getMessage() {
|
public String getIdentifier() {
|
||||||
return new ChatMessage();
|
return "Pitiupi.Chat.Example";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
Generated
+5
@@ -0,0 +1,5 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
Generated
+5
@@ -0,0 +1,5 @@
|
|||||||
|
<project version="4">
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/pitiupi.mpChat.iml" filepath="$PROJECT_DIR$/pitiupi.mpChat.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
JAR = ../pitiupi/dist/pitiupi.jar
|
||||||
|
OUT_DIR = out
|
||||||
|
META-INF_DIR = src/META-INF
|
||||||
|
DIST = dist/mpChat.jar
|
||||||
|
|
||||||
|
SOURCES = $(shell find -name "*.java")
|
||||||
|
|
||||||
|
all:
|
||||||
|
mkdir -p "$(OUT_DIR)"
|
||||||
|
mkdir -p "$(dir $(DIST))"
|
||||||
|
javac -cp "$(JAR)" -d "$(OUT_DIR)" $(SOURCES)
|
||||||
|
cp -r "$(META-INF_DIR)" "$(OUT_DIR)"
|
||||||
|
jar cf "$(DIST)" -C "$(OUT_DIR)" .
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf "$(OUT_DIR)"/*
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
plugin.MultiProtocolChat
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
<orderEntry type="module-library">
|
||||||
|
<library>
|
||||||
|
<CLASSES>
|
||||||
|
<root url="jar://$MODULE_DIR$/../pitiupi/dist/pitiupi.jar!/" />
|
||||||
|
</CLASSES>
|
||||||
|
<JAVADOC />
|
||||||
|
<SOURCES />
|
||||||
|
</library>
|
||||||
|
</orderEntry>
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package GUI;
|
||||||
|
|
||||||
|
import pitiupi.models.Menus.MulticastMenus.MulticastActionMenu;
|
||||||
|
|
||||||
|
public class MulticastMpChatMenu extends MulticastActionMenu {
|
||||||
|
PublicChatWindow publicChatWindow;
|
||||||
|
|
||||||
|
public MulticastMpChatMenu(PublicChatWindow publicChatWindow) {
|
||||||
|
this.publicChatWindow = publicChatWindow;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onClick() {
|
||||||
|
publicChatWindow.setVisible(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return "MP-Chat";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package GUI;
|
||||||
|
|
||||||
|
import net.MpChatMessage;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
import pitiupi.plugin.Pitiupi;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.awt.*;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class PrivateChatWindow extends JFrame {
|
||||||
|
|
||||||
|
private final Pitiupi pitiupi;
|
||||||
|
private final TcpConnection connection;
|
||||||
|
|
||||||
|
private final JTextArea receivedMessagesArea;
|
||||||
|
private final JTextField messageField;
|
||||||
|
|
||||||
|
public PrivateChatWindow(
|
||||||
|
Pitiupi pitiupi,
|
||||||
|
TcpConnection connection
|
||||||
|
) {
|
||||||
|
this.pitiupi = pitiupi;
|
||||||
|
this.connection = connection;
|
||||||
|
|
||||||
|
setTitle("Chat privado");
|
||||||
|
setSize(700, 500);
|
||||||
|
setLocationRelativeTo(null);
|
||||||
|
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
|
||||||
|
|
||||||
|
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
|
||||||
|
mainPanel.setBorder(
|
||||||
|
BorderFactory.createEmptyBorder(10, 10, 10, 10)
|
||||||
|
);
|
||||||
|
|
||||||
|
receivedMessagesArea = new JTextArea();
|
||||||
|
receivedMessagesArea.setEditable(false);
|
||||||
|
receivedMessagesArea.setLineWrap(true);
|
||||||
|
receivedMessagesArea.setWrapStyleWord(true);
|
||||||
|
|
||||||
|
JScrollPane messagesScrollPane =
|
||||||
|
new JScrollPane(receivedMessagesArea);
|
||||||
|
|
||||||
|
messagesScrollPane.setBorder(
|
||||||
|
BorderFactory.createTitledBorder("Mensagens")
|
||||||
|
);
|
||||||
|
|
||||||
|
mainPanel.add(
|
||||||
|
messagesScrollPane,
|
||||||
|
BorderLayout.CENTER
|
||||||
|
);
|
||||||
|
|
||||||
|
JPanel bottomPanel = new JPanel(
|
||||||
|
new BorderLayout(10, 10)
|
||||||
|
);
|
||||||
|
|
||||||
|
messageField = new JTextField();
|
||||||
|
|
||||||
|
JButton tcpButton = new JButton("TCP");
|
||||||
|
tcpButton.addActionListener(e -> sendTCP());
|
||||||
|
|
||||||
|
bottomPanel.add(
|
||||||
|
messageField,
|
||||||
|
BorderLayout.CENTER
|
||||||
|
);
|
||||||
|
|
||||||
|
bottomPanel.add(
|
||||||
|
tcpButton,
|
||||||
|
BorderLayout.EAST
|
||||||
|
);
|
||||||
|
|
||||||
|
mainPanel.add(
|
||||||
|
bottomPanel,
|
||||||
|
BorderLayout.SOUTH
|
||||||
|
);
|
||||||
|
|
||||||
|
setContentPane(mainPanel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendTCP() {
|
||||||
|
try {
|
||||||
|
String nome = pitiupi.getUserName();
|
||||||
|
|
||||||
|
MpChatMessage message = new MpChatMessage(
|
||||||
|
nome,
|
||||||
|
InetAddress.getLocalHost().getHostAddress(),
|
||||||
|
"TCP Private",
|
||||||
|
messageField.getText()
|
||||||
|
);
|
||||||
|
|
||||||
|
connection.send(message.toByteArray());
|
||||||
|
receiveMessage(message);
|
||||||
|
|
||||||
|
messageField.setText("");
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.getLogger(
|
||||||
|
PrivateChatWindow.class.getName()
|
||||||
|
).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receiveMessage(MpChatMessage message) {
|
||||||
|
SwingUtilities.invokeLater(() -> {
|
||||||
|
String texto = String.format(
|
||||||
|
"[%s] %s (%s): %s%n",
|
||||||
|
message.getTipoMensagem(),
|
||||||
|
message.getNome(),
|
||||||
|
message.getIp(),
|
||||||
|
message.getMessage()
|
||||||
|
);
|
||||||
|
|
||||||
|
receivedMessagesArea.append(texto);
|
||||||
|
|
||||||
|
receivedMessagesArea.setCaretPosition(
|
||||||
|
receivedMessagesArea.getDocument().getLength()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
package GUI;
|
||||||
|
|
||||||
|
import net.MpChatMessage;
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.plugin.Pitiupi;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import javax.swing.text.BadLocationException;
|
||||||
|
import javax.swing.text.SimpleAttributeSet;
|
||||||
|
import javax.swing.text.StyleConstants;
|
||||||
|
import javax.swing.text.StyledDocument;
|
||||||
|
import java.awt.*;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class PublicChatWindow extends JFrame {
|
||||||
|
private final Pitiupi pitiupi;
|
||||||
|
|
||||||
|
private JTextPane receivedMessagesArea;
|
||||||
|
private JTextField messageField;
|
||||||
|
private JTextField ipField;
|
||||||
|
|
||||||
|
public PublicChatWindow(Pitiupi pitiupi) {
|
||||||
|
this.pitiupi = pitiupi;
|
||||||
|
|
||||||
|
initComponents();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initComponents() {
|
||||||
|
setTitle("Public Chat");
|
||||||
|
setSize(700, 500);
|
||||||
|
setLocationRelativeTo(null);
|
||||||
|
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
|
||||||
|
|
||||||
|
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
|
||||||
|
|
||||||
|
mainPanel.setBorder(
|
||||||
|
BorderFactory.createEmptyBorder(10, 10, 10, 10)
|
||||||
|
);
|
||||||
|
|
||||||
|
initReceivedMessagesPanel(mainPanel);
|
||||||
|
initBottomPanel(mainPanel);
|
||||||
|
|
||||||
|
setContentPane(mainPanel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initReceivedMessagesPanel(JPanel mainPanel) {
|
||||||
|
receivedMessagesArea = new JTextPane();
|
||||||
|
|
||||||
|
receivedMessagesArea.setEditable(false);
|
||||||
|
|
||||||
|
JScrollPane messagesScrollPane = new JScrollPane(receivedMessagesArea);
|
||||||
|
|
||||||
|
messagesScrollPane.setBorder(
|
||||||
|
BorderFactory.createTitledBorder("Mensagens recebidas")
|
||||||
|
);
|
||||||
|
|
||||||
|
mainPanel.add(messagesScrollPane, BorderLayout.CENTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initBottomPanel(JPanel mainPanel) {
|
||||||
|
messageField = new JTextField();
|
||||||
|
|
||||||
|
JPanel bottomPanel = new JPanel(
|
||||||
|
new BorderLayout(10, 10)
|
||||||
|
);
|
||||||
|
|
||||||
|
bottomPanel.add(messageField, BorderLayout.CENTER);
|
||||||
|
|
||||||
|
initIpField(bottomPanel);
|
||||||
|
initCommunicationButtons(bottomPanel);
|
||||||
|
|
||||||
|
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initIpField(JPanel bottomPanel) {
|
||||||
|
ipField = new JTextField();
|
||||||
|
ipField.setPreferredSize(new Dimension(130, 30));
|
||||||
|
|
||||||
|
JPanel ipPanel = new JPanel(
|
||||||
|
new BorderLayout(5, 5)
|
||||||
|
);
|
||||||
|
|
||||||
|
ipPanel.add(
|
||||||
|
new JLabel("IP destino:"),
|
||||||
|
BorderLayout.WEST
|
||||||
|
);
|
||||||
|
|
||||||
|
ipPanel.add(
|
||||||
|
ipField,
|
||||||
|
BorderLayout.CENTER
|
||||||
|
);
|
||||||
|
|
||||||
|
bottomPanel.add(ipPanel, BorderLayout.WEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initCommunicationButtons(JPanel bottomPanel) {
|
||||||
|
JButton tcpButton = new JButton("TCP");
|
||||||
|
JButton udpButton = new JButton("UDP");
|
||||||
|
JButton multicastButton = new JButton("Multicast");
|
||||||
|
|
||||||
|
tcpButton.addActionListener(e -> sendTCP());
|
||||||
|
udpButton.addActionListener(e -> sendUDP());
|
||||||
|
multicastButton.addActionListener(e -> sendMulticast());
|
||||||
|
|
||||||
|
JPanel buttonsPanel = new JPanel(
|
||||||
|
new FlowLayout(FlowLayout.RIGHT, 5, 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
buttonsPanel.add(tcpButton);
|
||||||
|
buttonsPanel.add(udpButton);
|
||||||
|
buttonsPanel.add(multicastButton);
|
||||||
|
|
||||||
|
bottomPanel.add(
|
||||||
|
buttonsPanel,
|
||||||
|
BorderLayout.EAST
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private MpChatMessage createMessage(String tipoMensagem) {
|
||||||
|
try {
|
||||||
|
String nome = pitiupi.getUserName();
|
||||||
|
String ip = InetAddress.getLocalHost().getHostAddress();
|
||||||
|
String message = messageField.getText();
|
||||||
|
|
||||||
|
return new MpChatMessage(
|
||||||
|
nome,
|
||||||
|
ip,
|
||||||
|
tipoMensagem,
|
||||||
|
message
|
||||||
|
);
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receiveMessage(MpChatMessage msg) {
|
||||||
|
SwingUtilities.invokeLater(() -> {
|
||||||
|
String mensagem = String.format(
|
||||||
|
"[%s] %s (%s): %s%n",
|
||||||
|
msg.getTipoMensagem(),
|
||||||
|
msg.getNome(),
|
||||||
|
msg.getIp(),
|
||||||
|
msg.getMessage()
|
||||||
|
);
|
||||||
|
|
||||||
|
StyledDocument document = receivedMessagesArea.getStyledDocument();
|
||||||
|
|
||||||
|
SimpleAttributeSet attributes = new SimpleAttributeSet();
|
||||||
|
|
||||||
|
if (msg.getTipoMensagem().equals("TCP Unicast") || msg.getTipoMensagem().equals("UDP Unicast")) {
|
||||||
|
StyleConstants.setForeground(attributes, new Color(128, 0, 128));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
document.insertString(
|
||||||
|
document.getLength(),
|
||||||
|
mensagem,
|
||||||
|
attributes
|
||||||
|
);
|
||||||
|
|
||||||
|
receivedMessagesArea.setCaretPosition(
|
||||||
|
document.getLength()
|
||||||
|
);
|
||||||
|
|
||||||
|
} catch (BadLocationException ex) {
|
||||||
|
Logger.getLogger(PublicChatWindow.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendTCP() {
|
||||||
|
try {
|
||||||
|
MpChatMessage msg = createMessage("TCP Unicast");
|
||||||
|
|
||||||
|
InetAddress ip = InetAddress.getByName(ipField.getText());
|
||||||
|
|
||||||
|
pitiupi.sendTcp(msg, ip);
|
||||||
|
receiveMessage(msg);
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.getLogger(
|
||||||
|
PublicChatWindow.class.getName()
|
||||||
|
).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendUDP() {
|
||||||
|
try {
|
||||||
|
MpChatMessage msg = createMessage("UDP Unicast");
|
||||||
|
|
||||||
|
InetAddress ip = InetAddress.getByName(ipField.getText());
|
||||||
|
|
||||||
|
pitiupi.sendUdpUnicast(msg, ip);
|
||||||
|
receiveMessage(msg);
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.getLogger(
|
||||||
|
PublicChatWindow.class.getName()
|
||||||
|
).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendMulticast() {
|
||||||
|
try {
|
||||||
|
MpChatMessage msg = createMessage("UDP Multicast");
|
||||||
|
|
||||||
|
pitiupi.sendUdpMulticast(msg);
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.getLogger(
|
||||||
|
PublicChatWindow.class.getName()
|
||||||
|
).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package GUI;
|
||||||
|
|
||||||
|
import control.PrivateChatController;
|
||||||
|
import pitiupi.models.Menus.UnicastMenus.UnicastActionMenu;
|
||||||
|
import pitiupi.models.User;
|
||||||
|
|
||||||
|
public class UnicastMpChatMenu extends UnicastActionMenu {
|
||||||
|
|
||||||
|
private final PrivateChatController controller;
|
||||||
|
|
||||||
|
public UnicastMpChatMenu(
|
||||||
|
PrivateChatController controller
|
||||||
|
) {
|
||||||
|
this.controller = controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onClick(User user) {
|
||||||
|
controller.openChat(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return "Start Private Chat";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
plugin.MultiProtocolChat
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package control;
|
||||||
|
|
||||||
|
import GUI.ChatMenu;
|
||||||
|
import GUI.ChatWindow;
|
||||||
|
import GUI.PrivateChatWindow;
|
||||||
|
import GUI.PublicChatWindow;
|
||||||
|
import net.MpChatMessage;
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.PeerListener;
|
||||||
|
import pitiupi.models.User;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class ChatController implements PeerListener {
|
||||||
|
ConnectionManager connectionManager;
|
||||||
|
ChatMenu chatMenu;
|
||||||
|
|
||||||
|
PublicChatWindow publicChatWindow;
|
||||||
|
|
||||||
|
private final HashMap<TcpConnection, ChatWindow> chatWindows;
|
||||||
|
|
||||||
|
public ChatController(ConnectionManager connectionManager, ChatMenu chatMenu) {
|
||||||
|
this.connectionManager = connectionManager;
|
||||||
|
publicChatWindow = new PublicChatWindow(connectionManager);
|
||||||
|
|
||||||
|
chatMenus = new HashMap<>();
|
||||||
|
chatWindows = new HashMap<>();
|
||||||
|
|
||||||
|
this.chatMenu = chatMenu;
|
||||||
|
|
||||||
|
this.chatMenu.newMenuItem(new JMenuItem("Show global chat"), publicChatWindow);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addChatWindow(TcpConnection tcpConnection) {
|
||||||
|
if (chatWindows.containsKey(tcpConnection)) return;
|
||||||
|
|
||||||
|
PrivateChatWindow newChat = new PrivateChatWindow(connectionManager, tcpConnection);
|
||||||
|
chatWindows.put(tcpConnection, newChat);
|
||||||
|
JMenuItem newMenuItem = new JMenuItem();
|
||||||
|
chatMenus.put(tcpConnection, newMenuItem);
|
||||||
|
newMenuItem.setText(tcpConnection.getAddress().toString());
|
||||||
|
chatMenu.newMenuItem(newMenuItem, newChat);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeChatWindow(TcpConnection tcpConnection) {
|
||||||
|
ChatWindow removedWindow = chatWindows.remove(tcpConnection);
|
||||||
|
JMenuItem removedMenu = chatMenus.remove(tcpConnection);
|
||||||
|
|
||||||
|
chatMenu.removeMenuItem(removedMenu);
|
||||||
|
removedWindow.setVisible(false);
|
||||||
|
removedWindow.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receivePublic(MpChatMessage message) {
|
||||||
|
publicChatWindow.receiveMessage(message);
|
||||||
|
}
|
||||||
|
public void receivePrivate(TcpConnection tcpConnection, MpChatMessage message) {
|
||||||
|
chatWindows.get(tcpConnection).receiveMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void openChatWindow(InetAddress address) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onPeersChanged(List<User> list) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package control;
|
||||||
|
|
||||||
|
import GUI.PrivateChatWindow;
|
||||||
|
import net.MpChatMessage;
|
||||||
|
import pitiupi.models.User;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
import pitiupi.plugin.Pitiupi;
|
||||||
|
import plugin.MultiProtocolChat;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class PrivateChatController {
|
||||||
|
|
||||||
|
private final Pitiupi pitiupi;
|
||||||
|
private final MultiProtocolChat multiProtocolChat;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Relaciona o endereço do usuário à janela de chat.
|
||||||
|
*/
|
||||||
|
private final Map<String, PrivateChatWindow> windows;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Endereços para os quais uma conexão já foi solicitada,
|
||||||
|
* mas ainda não chegou.
|
||||||
|
*/
|
||||||
|
private final Set<String> pendingConnections;
|
||||||
|
|
||||||
|
public PrivateChatController(
|
||||||
|
Pitiupi pitiupi,
|
||||||
|
MultiProtocolChat multiProtocolChat
|
||||||
|
) {
|
||||||
|
this.pitiupi = pitiupi;
|
||||||
|
this.multiProtocolChat = multiProtocolChat;
|
||||||
|
|
||||||
|
this.windows = new HashMap<>();
|
||||||
|
this.pendingConnections = new HashSet<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void openChat(User user) {
|
||||||
|
String address = user.getAddress().getHostAddress();
|
||||||
|
|
||||||
|
PrivateChatWindow window = windows.get(address);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Já existe uma janela para esse usuário.
|
||||||
|
*/
|
||||||
|
if (window != null) {
|
||||||
|
window.setVisible(true);
|
||||||
|
window.toFront();
|
||||||
|
window.requestFocus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Já estamos esperando uma conexão para esse usuário.
|
||||||
|
*/
|
||||||
|
if (pendingConnections.contains(address)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ainda não existe conexão.
|
||||||
|
*/
|
||||||
|
pendingConnections.add(address);
|
||||||
|
|
||||||
|
multiProtocolChat.openConnection(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receiveMessage(TcpConnection connection, MpChatMessage message) {
|
||||||
|
String address = connection.getAddress().toString();
|
||||||
|
|
||||||
|
PrivateChatWindow window = windows.get(address);
|
||||||
|
|
||||||
|
if (window == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.receiveMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deve ser chamado quando uma nova conexão privada chegar.
|
||||||
|
*/
|
||||||
|
public void connectionReceived(TcpConnection connection) {
|
||||||
|
String address = connection.getAddress().toString();
|
||||||
|
|
||||||
|
pendingConnections.remove(address);
|
||||||
|
|
||||||
|
PrivateChatWindow window = new PrivateChatWindow(
|
||||||
|
pitiupi,
|
||||||
|
connection
|
||||||
|
);
|
||||||
|
|
||||||
|
windows.put(address, window);
|
||||||
|
|
||||||
|
window.setVisible(true);
|
||||||
|
window.toFront();
|
||||||
|
window.requestFocus();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha a janela e remove o relacionamento.
|
||||||
|
*/
|
||||||
|
public void closeChat(TcpConnection connection) {
|
||||||
|
String address = connection.getAddress().toString();
|
||||||
|
|
||||||
|
PrivateChatWindow window = windows.remove(address);
|
||||||
|
|
||||||
|
if (window != null) {
|
||||||
|
window.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-4
@@ -1,21 +1,21 @@
|
|||||||
package net;
|
package net;
|
||||||
|
|
||||||
import pitiupi.net.Message;
|
import pitiupi.models.Messages.Message;
|
||||||
|
|
||||||
public class TestMessage extends Message {
|
public class MpChatMessage extends Message {
|
||||||
private String nome;
|
private String nome;
|
||||||
private String ip;
|
private String ip;
|
||||||
private String tipoMensagem;
|
private String tipoMensagem;
|
||||||
private String message;
|
private String message;
|
||||||
|
|
||||||
public TestMessage(String nome, String ip, String tipoMensagem, String message) {
|
public MpChatMessage(String nome, String ip, String tipoMensagem, String message) {
|
||||||
this.nome = nome;
|
this.nome = nome;
|
||||||
this.ip = ip;
|
this.ip = ip;
|
||||||
this.tipoMensagem = tipoMensagem;
|
this.tipoMensagem = tipoMensagem;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TestMessage(){}
|
public MpChatMessage(){}
|
||||||
|
|
||||||
public String getNome() {
|
public String getNome() {
|
||||||
return nome;
|
return nome;
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package plugin;
|
||||||
|
|
||||||
|
import GUI.MulticastMpChatMenu;
|
||||||
|
import GUI.PrivateChatWindow;
|
||||||
|
import GUI.PublicChatWindow;
|
||||||
|
import GUI.UnicastMpChatMenu;
|
||||||
|
import control.PrivateChatController;
|
||||||
|
import net.MpChatMessage;
|
||||||
|
import pitiupi.models.Menus.MenuCategory;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
import pitiupi.models.Plugin;
|
||||||
|
import pitiupi.plugin.Pitiupi;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class MultiProtocolChat extends Plugin {
|
||||||
|
Pitiupi pitiupi;
|
||||||
|
|
||||||
|
PrivateChatController privateChatController;
|
||||||
|
PublicChatWindow publicChatWindow;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() {
|
||||||
|
return "MultiProtocol chat";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAuthor() {
|
||||||
|
return "Gustavo Henrique";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getVersion() {
|
||||||
|
return "0";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getIdentifier() {
|
||||||
|
return "Multi.Protocol.Chat.Pitiupi";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void createPlugin(Pitiupi pitiupi) {
|
||||||
|
this.pitiupi = pitiupi;
|
||||||
|
|
||||||
|
privateChatController = new PrivateChatController(pitiupi, this);
|
||||||
|
|
||||||
|
publicChatWindow = new PublicChatWindow(pitiupi);
|
||||||
|
|
||||||
|
MulticastMpChatMenu multicastMpChatMenu = new MulticastMpChatMenu(publicChatWindow);
|
||||||
|
UnicastMpChatMenu unicastMpChatMenu = new UnicastMpChatMenu(privateChatController);
|
||||||
|
|
||||||
|
pitiupi.createMenu(MenuCategory.Social, multicastMpChatMenu);
|
||||||
|
pitiupi.createMenu(MenuCategory.Social, unicastMpChatMenu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Class<? extends Message>> getMessages() {
|
||||||
|
return List.of(MpChatMessage.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void receiveMessage(Message message) {
|
||||||
|
if (message instanceof MpChatMessage mpChatMessage) {
|
||||||
|
publicChatWindow.receiveMessage(mpChatMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean receivePrivateConnection(TcpConnection connection) {
|
||||||
|
SwingUtilities.invokeLater(() -> {
|
||||||
|
privateChatController.connectionReceived(connection);
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean receiveBytes(TcpConnection connection, byte[] bytes) {
|
||||||
|
MpChatMessage mpChatMessage = parseMessage(bytes);
|
||||||
|
if (mpChatMessage == null) {
|
||||||
|
System.out.println("Invalid message received");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else System.out.println(mpChatMessage.getMessage());
|
||||||
|
|
||||||
|
privateChatController.receiveMessage(connection, mpChatMessage);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onSocketClosed(TcpConnection connection) {
|
||||||
|
privateChatController.closeChat(connection);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void openConnection(String ip) {
|
||||||
|
try {
|
||||||
|
pitiupi.connectTcp(InetAddress.getByName(ip), getIdentifier(), getIdentifier());
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
System.out.println("Error opening connection: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private MpChatMessage parseMessage(byte[] bytes) {
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois;
|
||||||
|
try {
|
||||||
|
ois = new ObjectInputStream(bis);
|
||||||
|
if (ois.readObject() instanceof MpChatMessage msg) {
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
} catch (IOException | ClassNotFoundException ex) {
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$" />
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
Generated
+23
-31
@@ -5,24 +5,10 @@
|
|||||||
</component>
|
</component>
|
||||||
<component name="ChangeListManager">
|
<component name="ChangeListManager">
|
||||||
<list default="true" id="083e72ce-fa9b-4ddf-a0ef-24105aa3eabb" name="Changes" comment="">
|
<list default="true" id="083e72ce-fa9b-4ddf-a0ef-24105aa3eabb" name="Changes" comment="">
|
||||||
<change beforePath="$PROJECT_DIR$/../.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../.idea/misc.xml" afterDir="false" />
|
<change afterPath="$PROJECT_DIR$/../pitiupi.testSocket/Makefile" afterDir="false" />
|
||||||
<change beforePath="$PROJECT_DIR$/../.idea/vcs.xml" beforeDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../.idea/workspace.xml" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi.chat/.idea/misc.xml" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/build/built-jar.properties" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi.chat/build/built-jar.properties" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/build/classes/pitiupi/chat/GUI/ChatWindow.class" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi.chat/build/classes/pitiupi/chat/GUI/ChatWindow.class" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/dist/pitiupi.chat.jar" beforeDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/pitiupi.chat.iml" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi.chat/pitiupi.chat.iml" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi.chat/src/pitiupi/chat/GUI/ChatWindow.java" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi.chat/src/pitiupi/chat/GUI/ChatWindow.java" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||||
<change beforePath="$PROJECT_DIR$/build/built-jar.properties" beforeDir="false" afterPath="$PROJECT_DIR$/build/built-jar.properties" afterDir="false" />
|
<change beforePath="$PROJECT_DIR$/../pitiupi/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/.idea/misc.xml" afterDir="false" />
|
||||||
<change beforePath="$PROJECT_DIR$/build/classes/pitiupi/screenCast/GUI/ScreenCastWindow.class" beforeDir="false" afterPath="$PROJECT_DIR$/build/classes/pitiupi/screenCast/GUI/ScreenCastWindow.class" afterDir="false" />
|
<change beforePath="$PROJECT_DIR$/../pitiupi/src/pitiupi/net/tcp/ConnectionFactory.java" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/src/pitiupi/net/tcp/ConnectionFactory.java" afterDir="false" />
|
||||||
<change beforePath="$PROJECT_DIR$/dist/pitiupi.screenCast.jar" beforeDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/src/pitiupi/screenCast/GUI/ScreenCastWindow.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/pitiupi/screenCast/GUI/ScreenCastWindow.java" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi/plugins/pitiupi.chat.jar" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/plugins/pitiupi.chat.jar" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi/plugins/pitiupi.screenCast.jar" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/plugins/pitiupi.screenCast.jar" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi/src/pitiupi/GUI/MainWindow.java" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/src/pitiupi/GUI/MainWindow.java" afterDir="false" />
|
|
||||||
<change beforePath="$PROJECT_DIR$/../pitiupi/src/pitiupi/control/HeartbeatManager.java" beforeDir="false" afterPath="$PROJECT_DIR$/../pitiupi/src/pitiupi/control/HeartbeatManager.java" afterDir="false" />
|
|
||||||
</list>
|
</list>
|
||||||
<option name="SHOW_DIALOG" value="false" />
|
<option name="SHOW_DIALOG" value="false" />
|
||||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||||
@@ -46,10 +32,12 @@
|
|||||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||||
"RunOnceActivity.git.unshallow": "true",
|
"RunOnceActivity.git.unshallow": "true",
|
||||||
"git-widget-placeholder": "feature/unicast",
|
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
|
||||||
|
"codeWithMe.voiceChat.enabledByDefault": "false",
|
||||||
|
"git-widget-placeholder": "feature/separacao-gerenciadores",
|
||||||
"ignore.virus.scanning.warn.message": "true",
|
"ignore.virus.scanning.warn.message": "true",
|
||||||
"kotlin-language-version-configured": "true",
|
"kotlin-language-version-configured": "true",
|
||||||
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi/pitiupi.screenCast",
|
"last_opened_file_path": "C:/Users/Gustavo/OneDrive/Documentos/Faculdade/2026_2/Monitoria/pitiupi/pitiupi.screenCast",
|
||||||
"project.structure.last.edited": "Modules",
|
"project.structure.last.edited": "Modules",
|
||||||
"project.structure.proportion": "0.15",
|
"project.structure.proportion": "0.15",
|
||||||
"project.structure.side.proportion": "0.2",
|
"project.structure.side.proportion": "0.2",
|
||||||
@@ -57,17 +45,6 @@
|
|||||||
}
|
}
|
||||||
}]]></component>
|
}]]></component>
|
||||||
<component name="RunManager">
|
<component name="RunManager">
|
||||||
<configuration default="true" type="JetRunConfigurationType">
|
|
||||||
<module name="pitiupi.screenCast" />
|
|
||||||
<method v="2">
|
|
||||||
<option name="Make" enabled="true" />
|
|
||||||
</method>
|
|
||||||
</configuration>
|
|
||||||
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType">
|
|
||||||
<module name="pitiupi.screenCast" />
|
|
||||||
<option name="filePath" />
|
|
||||||
<method v="2" />
|
|
||||||
</configuration>
|
|
||||||
<configuration default="true" type="PythonConfigurationType" factoryName="Python">
|
<configuration default="true" type="PythonConfigurationType" factoryName="Python">
|
||||||
<module name="pitiupi.screenCast" />
|
<module name="pitiupi.screenCast" />
|
||||||
<option name="ENV_FILES" value="" />
|
<option name="ENV_FILES" value="" />
|
||||||
@@ -102,11 +79,23 @@
|
|||||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||||
<method v="2" />
|
<method v="2" />
|
||||||
</configuration>
|
</configuration>
|
||||||
|
<configuration default="true" type="JetRunConfigurationType">
|
||||||
|
<module name="pitiupi.screenCast" />
|
||||||
|
<method v="2">
|
||||||
|
<option name="Make" enabled="true" />
|
||||||
|
</method>
|
||||||
|
</configuration>
|
||||||
|
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType">
|
||||||
|
<module name="pitiupi.screenCast" />
|
||||||
|
<option name="filePath" />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
</component>
|
</component>
|
||||||
<component name="SharedIndexes">
|
<component name="SharedIndexes">
|
||||||
<attachedChunks>
|
<attachedChunks>
|
||||||
<set>
|
<set>
|
||||||
<option value="bundled-jdk-9823dce3aa75-bf35d07a577b-intellij.indexing.shared.core-IU-252.28539.54" />
|
<option value="bundled-jdk-30f59d01ecdd-37e91769500f-intellij.indexing.shared.core-IU-261.26222.65" />
|
||||||
|
<option value="bundled-js-predefined-d6986cc7102b-31caf2ab9e3c-JavaScript-IU-261.26222.65" />
|
||||||
</set>
|
</set>
|
||||||
</attachedChunks>
|
</attachedChunks>
|
||||||
</component>
|
</component>
|
||||||
@@ -120,4 +109,7 @@
|
|||||||
</task>
|
</task>
|
||||||
<servers />
|
<servers />
|
||||||
</component>
|
</component>
|
||||||
|
<component name="TypeScriptGeneratedFilesManager">
|
||||||
|
<option name="version" value="3" />
|
||||||
|
</component>
|
||||||
</project>
|
</project>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#Mon, 17 Aug 2026 14:35:40 -0300
|
#Tue, 29 Sep 2026 11:04:58 -0300
|
||||||
|
|
||||||
|
|
||||||
C\:\\Users\\extre\\OneDrive\\Documentos\\Faculdade\\2026_02\\Monitoria\\Pitiupi\\pitiupi.screenCast=
|
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\pitiupi\\pitiupi.screenCast=
|
||||||
|
|
||||||
C\:\\Users\\extre\\OneDrive\\Documentos\\Faculdade\\2026_02\\Monitoria\\Pitiupi\\pitiupi=
|
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\pitiupi\\pitiupi=
|
||||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
File renamed without changes.
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="module-library">
|
||||||
|
<library>
|
||||||
|
<CLASSES>
|
||||||
|
<root url="jar://$MODULE_DIR$/../../pitiupi/dist/pitiupi.jar!/" />
|
||||||
|
</CLASSES>
|
||||||
|
<JAVADOC />
|
||||||
|
<SOURCES />
|
||||||
|
</library>
|
||||||
|
</orderEntry>
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
@@ -5,6 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.screenCast.GUI;
|
package pitiupi.screenCast.GUI;
|
||||||
|
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.GuiManager;
|
||||||
import pitiupi.screenCast.control.AlarmClock;
|
import pitiupi.screenCast.control.AlarmClock;
|
||||||
import pitiupi.screenCast.control.ImageTransformation;
|
import pitiupi.screenCast.control.ImageTransformation;
|
||||||
import pitiupi.screenCast.control.ScreenShot;
|
import pitiupi.screenCast.control.ScreenShot;
|
||||||
@@ -38,10 +40,13 @@ public class ScreenCastWindow extends javax.swing.JFrame {
|
|||||||
public final static int TIME = 1000;
|
public final static int TIME = 1000;
|
||||||
|
|
||||||
private float compressRatio;
|
private float compressRatio;
|
||||||
private final MainWindow mainWindow;
|
private final ConnectionManager connectionManager;
|
||||||
|
private final GuiManager guiManager;
|
||||||
|
|
||||||
|
public ScreenCastWindow(ConnectionManager connectionManager, GuiManager guiManager) {
|
||||||
|
this.connectionManager = connectionManager;
|
||||||
|
this.guiManager = guiManager;
|
||||||
|
|
||||||
public ScreenCastWindow(MainWindow mainWindow) {
|
|
||||||
this.mainWindow = mainWindow;
|
|
||||||
this.compressRatio = 0.5f;
|
this.compressRatio = 0.5f;
|
||||||
this.initComponents();
|
this.initComponents();
|
||||||
}
|
}
|
||||||
@@ -91,19 +96,12 @@ public class ScreenCastWindow extends javax.swing.JFrame {
|
|||||||
BufferedImage image = ScreenShot.takeAShot();
|
BufferedImage image = ScreenShot.takeAShot();
|
||||||
BufferedImage rescaled = ImageTransformation.resize(image, 1024, 768);
|
BufferedImage rescaled = ImageTransformation.resize(image, 1024, 768);
|
||||||
byte[] byteImage = ImageTransformation.compress(rescaled, compressRatio);
|
byte[] byteImage = ImageTransformation.compress(rescaled, compressRatio);
|
||||||
ScreenCastMessage message = new ScreenCastMessage(this.mainWindow.getUserName(), byteImage);
|
ScreenCastMessage message = new ScreenCastMessage(this.connectionManager.getUserName(), byteImage);
|
||||||
msg = message.toByteArray();
|
|
||||||
|
if (!connectionManager.sendUdpMulticast(message)) this.compressRatio -= 0.1f;
|
||||||
} catch (AWTException | IOException ex) {
|
} catch (AWTException | IOException ex) {
|
||||||
Logger.getLogger(AlarmClock.class.getName()).log(Level.SEVERE, null, ex);
|
Logger.getLogger(AlarmClock.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
}
|
}
|
||||||
if (msg != null) {
|
|
||||||
try {
|
|
||||||
this.mainWindow.getSocketUDP().sendMulticast(msg);
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println(ex.toString());
|
|
||||||
this.compressRatio -= 0.1f;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void receiveScreenCastMessage(ScreenCastMessage message) {
|
public void receiveScreenCastMessage(ScreenCastMessage message) {
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import java.io.ByteArrayInputStream;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.ObjectInputStream;
|
import java.io.ObjectInputStream;
|
||||||
import pitiupi.GUI.MainWindow;
|
import pitiupi.GUI.MainWindow;
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.GuiManager;
|
||||||
import pitiupi.net.Message;
|
import pitiupi.net.Message;
|
||||||
import pitiupi.plugin.Plugin;
|
import pitiupi.plugin.Plugin;
|
||||||
import pitiupi.screenCast.GUI.ScreenCastMenu;
|
import pitiupi.screenCast.GUI.ScreenCastMenu;
|
||||||
@@ -21,7 +23,6 @@ import pitiupi.screenCast.net.ScreenCastMessage;
|
|||||||
public class ScreenCastPlugin implements Plugin {
|
public class ScreenCastPlugin implements Plugin {
|
||||||
|
|
||||||
private ScreenCastWindow screenCastWindow;
|
private ScreenCastWindow screenCastWindow;
|
||||||
private MainWindow mainWindow;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
@@ -39,10 +40,14 @@ public class ScreenCastPlugin implements Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void createPlugin(MainWindow mainWindow) {
|
public String getIdentifier() {
|
||||||
this.mainWindow = mainWindow;
|
return "Pitiupi.ScreenCast.Example";
|
||||||
this.screenCastWindow = new ScreenCastWindow(mainWindow);
|
}
|
||||||
this.mainWindow.addMenu(new ScreenCastMenu(screenCastWindow));
|
|
||||||
|
@Override
|
||||||
|
public void createPlugin(ConnectionManager connectionManager, GuiManager guiManager) {
|
||||||
|
this.screenCastWindow = new ScreenCastWindow(connectionManager, guiManager);
|
||||||
|
guiManager.addMenu(new ScreenCastMenu(screenCastWindow));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -54,9 +59,7 @@ public class ScreenCastPlugin implements Plugin {
|
|||||||
if (ois.readObject() instanceof ScreenCastMessage msg) {
|
if (ois.readObject() instanceof ScreenCastMessage msg) {
|
||||||
this.screenCastWindow.receiveScreenCastMessage(msg);
|
this.screenCastWindow.receiveScreenCastMessage(msg);
|
||||||
}
|
}
|
||||||
} catch (IOException ex) {
|
} catch (IOException | ClassNotFoundException ex) {
|
||||||
System.out.println(ex.toString());
|
|
||||||
} catch (ClassNotFoundException ex) {
|
|
||||||
System.out.println(ex.toString());
|
System.out.println(ex.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -1 +0,0 @@
|
|||||||
plugin.SocketTest
|
|
||||||
Binary file not shown.
Binary file not shown.
@@ -1,21 +0,0 @@
|
|||||||
package GUI;
|
|
||||||
|
|
||||||
import javax.swing.*;
|
|
||||||
import java.awt.event.ActionEvent;
|
|
||||||
|
|
||||||
public class SocketTestMenu extends JMenu {
|
|
||||||
private final SocketTestWindow socketTestWindow;
|
|
||||||
|
|
||||||
public SocketTestMenu(SocketTestWindow socketTestWindow) {
|
|
||||||
this.socketTestWindow = socketTestWindow;
|
|
||||||
this.setText("Chat");
|
|
||||||
JMenuItem menuItem = new JMenuItem();
|
|
||||||
menuItem.setText("Show Chat Window");
|
|
||||||
menuItem.addActionListener(this::showTestWindow);
|
|
||||||
this.add(menuItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void showTestWindow(ActionEvent ae) {
|
|
||||||
this.socketTestWindow.setVisible(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
package GUI;
|
|
||||||
|
|
||||||
import net.TestMessage;
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
|
|
||||||
import javax.swing.*;
|
|
||||||
import java.awt.*;
|
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.logging.Level;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
public class SocketTestWindow extends JFrame {
|
|
||||||
private MainWindow mainWindow;
|
|
||||||
private JTextArea receivedMessagesArea;
|
|
||||||
|
|
||||||
private JTextField ipField;
|
|
||||||
private JTextField messageField;
|
|
||||||
|
|
||||||
private JButton tcpButton;
|
|
||||||
private JButton udpButton;
|
|
||||||
private JButton multicastButton;
|
|
||||||
|
|
||||||
public SocketTestWindow(MainWindow mainWindow) {
|
|
||||||
this.mainWindow = mainWindow;
|
|
||||||
initComponents();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void initComponents() {
|
|
||||||
setTitle("Socket Test");
|
|
||||||
setSize(700, 500);
|
|
||||||
setLocationRelativeTo(null);
|
|
||||||
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
|
|
||||||
|
|
||||||
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
|
|
||||||
|
|
||||||
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
|
|
||||||
|
|
||||||
initReceivedMessagesPanel(mainPanel);
|
|
||||||
initBottomPanel(mainPanel);
|
|
||||||
|
|
||||||
setContentPane(mainPanel);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initReceivedMessagesPanel(JPanel mainPanel) {
|
|
||||||
receivedMessagesArea = new JTextArea();
|
|
||||||
receivedMessagesArea.setEditable(false);
|
|
||||||
receivedMessagesArea.setLineWrap(true);
|
|
||||||
receivedMessagesArea.setWrapStyleWord(true);
|
|
||||||
|
|
||||||
JScrollPane messagesScrollPane = new JScrollPane(receivedMessagesArea);
|
|
||||||
|
|
||||||
messagesScrollPane.setBorder(BorderFactory.createTitledBorder("Mensagens recebidas"));
|
|
||||||
|
|
||||||
mainPanel.add(messagesScrollPane, BorderLayout.CENTER);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initBottomPanel(JPanel mainPanel) {
|
|
||||||
ipField = new JTextField();
|
|
||||||
ipField.setPreferredSize(new Dimension(130, 30));
|
|
||||||
|
|
||||||
JPanel ipPanel = new JPanel(new BorderLayout(5, 5));
|
|
||||||
ipPanel.add(new JLabel("IP destino:"), BorderLayout.WEST);
|
|
||||||
ipPanel.add(ipField, BorderLayout.CENTER);
|
|
||||||
|
|
||||||
messageField = new JTextField();
|
|
||||||
|
|
||||||
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
|
|
||||||
|
|
||||||
bottomPanel.add(ipPanel, BorderLayout.WEST);
|
|
||||||
bottomPanel.add(messageField, BorderLayout.CENTER);
|
|
||||||
initButtons(bottomPanel);
|
|
||||||
|
|
||||||
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initButtons(JPanel bottomPanel) {
|
|
||||||
tcpButton = new JButton("TCP");
|
|
||||||
udpButton = new JButton("UDP");
|
|
||||||
multicastButton = new JButton("Multicast");
|
|
||||||
|
|
||||||
tcpButton.addActionListener(e -> sendTCP());
|
|
||||||
udpButton.addActionListener(e -> sendUDP());
|
|
||||||
multicastButton.addActionListener(e -> sendMulticast());
|
|
||||||
|
|
||||||
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
|
|
||||||
|
|
||||||
buttonsPanel.add(tcpButton);
|
|
||||||
buttonsPanel.add(udpButton);
|
|
||||||
buttonsPanel.add(multicastButton);
|
|
||||||
|
|
||||||
bottomPanel.add(buttonsPanel, BorderLayout.EAST);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void sendTCP() {
|
|
||||||
try {
|
|
||||||
TestMessage msg = createMessage("TCP Unicast");
|
|
||||||
InetAddress ip = InetAddress.getByName(ipField.getText());
|
|
||||||
mainWindow.getSocketTCP().send(msg.toByteArray(), ip);
|
|
||||||
} catch (Exception ex) {
|
|
||||||
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
public void sendUDP() {
|
|
||||||
try {
|
|
||||||
TestMessage msg = createMessage("UDP Unicast");
|
|
||||||
InetAddress ip = InetAddress.getByName(ipField.getText());
|
|
||||||
mainWindow.getSocketUDP().sendUnicast(msg.toByteArray(), ip);
|
|
||||||
} catch (Exception ex) {
|
|
||||||
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public void sendMulticast() {
|
|
||||||
try {
|
|
||||||
TestMessage msg = createMessage("UDP Multicast");
|
|
||||||
mainWindow.getSocketUDP().sendMulticast(msg.toByteArray());
|
|
||||||
} catch (Exception ex) {
|
|
||||||
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private TestMessage createMessage(String tipoMensagem) {
|
|
||||||
try {
|
|
||||||
String nome = mainWindow.getUserName();
|
|
||||||
String ip = InetAddress.getLocalHost().getHostAddress();
|
|
||||||
String message = messageField.getText();
|
|
||||||
return new TestMessage(nome, ip, tipoMensagem, message);
|
|
||||||
} catch (UnknownHostException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void receiveMessage(TestMessage msg) {
|
|
||||||
SwingUtilities.invokeLater(() -> {
|
|
||||||
String mensagem = String.format(
|
|
||||||
"[%s] %s (%s): %s%n",
|
|
||||||
msg.getTipoMensagem(),
|
|
||||||
msg.getNome(),
|
|
||||||
msg.getIp(),
|
|
||||||
msg.getMessage()
|
|
||||||
);
|
|
||||||
|
|
||||||
receivedMessagesArea.append(mensagem);
|
|
||||||
|
|
||||||
receivedMessagesArea.setCaretPosition(
|
|
||||||
receivedMessagesArea.getDocument().getLength()
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
plugin.SocketTest
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package plugin;
|
|
||||||
|
|
||||||
import GUI.SocketTestMenu;
|
|
||||||
import GUI.SocketTestWindow;
|
|
||||||
import net.TestMessage;
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.net.Message;
|
|
||||||
import pitiupi.plugin.Plugin;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.ObjectInputStream;
|
|
||||||
|
|
||||||
public class SocketTest implements Plugin{
|
|
||||||
SocketTestWindow socketTestWindow;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "Test Socket";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getAuthor() {
|
|
||||||
return "Gustavo Henrique";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getVersion() {
|
|
||||||
return "0";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void createPlugin(MainWindow mainWindow) {
|
|
||||||
this.socketTestWindow = new SocketTestWindow(mainWindow);
|
|
||||||
mainWindow.addMenu(new SocketTestMenu(socketTestWindow));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Message getMessage() {
|
|
||||||
return new TestMessage();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void receiveMessage(byte[] bytes) {
|
|
||||||
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
|
||||||
ObjectInputStream ois;
|
|
||||||
try {
|
|
||||||
ois = new ObjectInputStream(bis);
|
|
||||||
if (ois.readObject() instanceof TestMessage msg) {
|
|
||||||
this.socketTestWindow.receiveMessage(msg);
|
|
||||||
}
|
|
||||||
} catch (IOException | ClassNotFoundException ex) {
|
|
||||||
System.out.println(ex.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Generated
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_26_PREVIEW" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
||||||
@@ -468,10 +468,10 @@ MeusPlugins
|
|||||||
|
|
|
|
||||||
+---services
|
+---services
|
||||||
|
|
|
|
||||||
+---pitiupi.plugin.Plugin
|
+---pitiupi.models.Plugin
|
||||||
```
|
```
|
||||||
|
|
||||||
O arquivo `pitiupi.plugin.Plugin` deve conter o nome completo das classes que
|
O arquivo `pitiupi.models.Plugin` deve conter o nome completo das classes que
|
||||||
implementam a interface Plugin:
|
implementam a interface Plugin:
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -46,8 +46,8 @@ javac.modulepath=
|
|||||||
javac.processormodulepath=
|
javac.processormodulepath=
|
||||||
javac.processorpath=\
|
javac.processorpath=\
|
||||||
${javac.classpath}
|
${javac.classpath}
|
||||||
javac.source=25
|
javac.source=17
|
||||||
javac.target=25
|
javac.target=17
|
||||||
javac.test.classpath=\
|
javac.test.classpath=\
|
||||||
${javac.classpath}:\
|
${javac.classpath}:\
|
||||||
${build.classes.dir}
|
${build.classes.dir}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -48,7 +48,6 @@ public final class Login extends JDialog {
|
|||||||
public void initComponents() {
|
public void initComponents() {
|
||||||
this.setTitle("Login");
|
this.setTitle("Login");
|
||||||
|
|
||||||
|
|
||||||
String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name"));
|
String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name"));
|
||||||
int portaSalva = prefs.getInt(PREF_PORTA, 8000);
|
int portaSalva = prefs.getInt(PREF_PORTA, 8000);
|
||||||
|
|
||||||
|
|||||||
@@ -5,14 +5,13 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.GUI;
|
package pitiupi.GUI;
|
||||||
|
|
||||||
import pitiupi.net.SocketTCP;
|
import pitiupi.control.ConnectionManager;
|
||||||
import pitiupi.net.SocketUDP;
|
import pitiupi.control.GuiManager;
|
||||||
import java.util.ArrayList;
|
import pitiupi.control.plugins.PluginManager;
|
||||||
import java.util.List;
|
|
||||||
import javax.swing.JMenu;
|
import javax.swing.*;
|
||||||
import pitiupi.control.PluginLoader;
|
|
||||||
import pitiupi.plugin.Plugin;
|
import java.awt.*;
|
||||||
import pitiupi.control.HeartbeatManager;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Janela principal da aplicação.
|
* Janela principal da aplicação.
|
||||||
@@ -28,26 +27,15 @@ import pitiupi.control.HeartbeatManager;
|
|||||||
* @author tony
|
* @author tony
|
||||||
* @author Gustavo
|
* @author Gustavo
|
||||||
*/
|
*/
|
||||||
public class MainWindow extends javax.swing.JFrame {
|
public class MainWindow extends JFrame {
|
||||||
|
|
||||||
private final MenuBar menuBar;
|
private MenuBar menuBar;
|
||||||
private javax.swing.JScrollPane jScrollPane1;
|
private JLabel status;
|
||||||
private javax.swing.JLabel status;
|
OnlineUsersPanel onlineUsersPanel;
|
||||||
private javax.swing.JPanel statusPanel;
|
|
||||||
private javax.swing.JTabbedPane tabbedPane;
|
|
||||||
|
|
||||||
private HeartbeatManager heartbeatManager;
|
private final ConnectionManager connectionManager;
|
||||||
private OnlineUsersPanel onlineUsersPanel;
|
private final PluginManager pluginManager;
|
||||||
|
private final GuiManager guiManager;
|
||||||
|
|
||||||
private SocketUDP socketUDP;
|
|
||||||
private SocketTCP socketTCP;
|
|
||||||
|
|
||||||
private String userName;
|
|
||||||
private int port;
|
|
||||||
|
|
||||||
private PluginLoader pluginManager;
|
|
||||||
private final List<Plugin> plugins;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria a janela principal da aplicação.
|
* Cria a janela principal da aplicação.
|
||||||
@@ -56,61 +44,53 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
* @param port porta utilizada na comunicação multicast.
|
* @param port porta utilizada na comunicação multicast.
|
||||||
*/
|
*/
|
||||||
public MainWindow(String userName, int port) {
|
public MainWindow(String userName, int port) {
|
||||||
this.userName = userName;
|
initMenu();
|
||||||
this.port = port;
|
|
||||||
this.menuBar = new MenuBar(this);
|
pluginManager = new PluginManager();
|
||||||
this.plugins = new ArrayList<>();
|
connectionManager = new ConnectionManager(this, userName, pluginManager, port);
|
||||||
this.initComponents();
|
|
||||||
}
|
initUserPanel();
|
||||||
|
initStatusPanel();
|
||||||
|
|
||||||
|
guiManager = new GuiManager(this, menuBar, onlineUsersPanel);
|
||||||
|
|
||||||
|
loadPlugins();
|
||||||
|
|
||||||
|
this.pack();
|
||||||
|
|
||||||
private void initComponents() {
|
|
||||||
initGUI();
|
|
||||||
initSocket();
|
|
||||||
initHeartbeat();
|
|
||||||
initPlugins();
|
|
||||||
this.setSize(new java.awt.Dimension(1024, 768));
|
this.setSize(new java.awt.Dimension(1024, 768));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initGUI() {
|
private void initMenu() {
|
||||||
|
menuBar = new MenuBar(this);
|
||||||
|
|
||||||
this.setJMenuBar(menuBar);
|
this.setJMenuBar(menuBar);
|
||||||
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
|
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
|
||||||
this.setTitle("Share My Sheet");
|
this.setTitle("Pitiupi");
|
||||||
|
|
||||||
jScrollPane1 = new javax.swing.JScrollPane();
|
javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
|
||||||
tabbedPane = new javax.swing.JTabbedPane();
|
javax.swing.JTabbedPane tabbedPane = new javax.swing.JTabbedPane();
|
||||||
statusPanel = new javax.swing.JPanel();
|
|
||||||
status = new javax.swing.JLabel();
|
|
||||||
|
|
||||||
jScrollPane1.setViewportView(tabbedPane);
|
jScrollPane1.setViewportView(tabbedPane);
|
||||||
statusPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
|
|
||||||
status.setText("Connected on port " + this.port + " name " + this.userName);
|
|
||||||
statusPanel.add(status);
|
|
||||||
|
|
||||||
this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
|
this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
|
||||||
this.getContentPane().add(statusPanel, java.awt.BorderLayout.PAGE_END);
|
|
||||||
|
|
||||||
this.pack();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initSocket() {
|
private void initUserPanel() {
|
||||||
this.socketUDP = new SocketUDP(this);
|
onlineUsersPanel = new OnlineUsersPanel();
|
||||||
this.socketTCP = new SocketTCP(this);
|
this.connectionManager.addPeerListener(onlineUsersPanel);
|
||||||
|
this.getContentPane().add(onlineUsersPanel, java.awt.BorderLayout.LINE_END);
|
||||||
this.socketUDP.start();
|
|
||||||
this.socketTCP.start();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initHeartbeat() {
|
private void initStatusPanel() {
|
||||||
this.heartbeatManager = new HeartbeatManager(this);
|
JPanel statusPanel = new JPanel();
|
||||||
this.onlineUsersPanel = new OnlineUsersPanel();
|
status = new JLabel();
|
||||||
this.heartbeatManager.addPeerListener(this.onlineUsersPanel);
|
|
||||||
this.getContentPane().add(this.onlineUsersPanel, java.awt.BorderLayout.LINE_END);
|
|
||||||
this.heartbeatManager.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initPlugins() {
|
statusPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
|
||||||
this.pluginManager = new PluginLoader(this);
|
updateStatus();
|
||||||
this.pluginManager.loadPlugins();
|
statusPanel.add(status);
|
||||||
|
|
||||||
|
this.getContentPane().add(statusPanel, BorderLayout.PAGE_END);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
@@ -119,61 +99,21 @@ public class MainWindow extends javax.swing.JFrame {
|
|||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HeartbeatManager getHeartbeatManager() {
|
public ConnectionManager getConnectionManager() {
|
||||||
return heartbeatManager;
|
return connectionManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUserName(){
|
public void loadPlugins() {
|
||||||
return this.userName;
|
pluginManager.loadPlugins(connectionManager, guiManager);
|
||||||
}
|
|
||||||
|
|
||||||
public void addMenu(JMenu menu) {
|
|
||||||
this.menuBar.addPlugin(menu);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPort() {
|
|
||||||
return this.port;
|
|
||||||
}
|
|
||||||
|
|
||||||
public SocketUDP getSocketUDP() {
|
|
||||||
return this.socketUDP;
|
|
||||||
}
|
|
||||||
|
|
||||||
public SocketTCP getSocketTCP() {
|
|
||||||
return this.socketTCP;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Plugin> getPlugins() {
|
|
||||||
return plugins;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUserName(String userName) {
|
public void setUserName(String userName) {
|
||||||
this.userName = userName;
|
connectionManager.setUserName(userName);
|
||||||
updateStatus();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPort(int port) {
|
|
||||||
this.port = port;
|
|
||||||
reconnect();
|
|
||||||
updateStatus();
|
updateStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateStatus() {
|
private void updateStatus() {
|
||||||
this.status.setText("Connected on port " + this.port + " name " + this.userName);
|
this.status.setText("Connected on port " + connectionManager.getPort() + " name " + connectionManager.getUserName());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void reconnect() {
|
|
||||||
if (this.socketUDP != null) {
|
|
||||||
this.socketUDP.close();
|
|
||||||
}
|
|
||||||
if (this.socketTCP != null) {
|
|
||||||
this.socketTCP.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.socketUDP = new SocketUDP(this);
|
|
||||||
this.socketTCP = new SocketTCP(this);
|
|
||||||
|
|
||||||
this.socketUDP.start();
|
|
||||||
this.socketTCP.start();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -5,8 +5,14 @@
|
|||||||
*/
|
*/
|
||||||
package pitiupi.GUI;
|
package pitiupi.GUI;
|
||||||
|
|
||||||
import javax.swing.JMenu;
|
import pitiupi.models.Menus.MenuCategory;
|
||||||
import javax.swing.JMenuBar;
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.awt.event.ActionEvent;
|
||||||
|
import java.awt.event.InputEvent;
|
||||||
|
import java.awt.event.KeyEvent;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Barra de menus principal da aplicação.
|
* Barra de menus principal da aplicação.
|
||||||
@@ -21,12 +27,14 @@ import javax.swing.JMenuBar;
|
|||||||
*/
|
*/
|
||||||
public class MenuBar extends JMenuBar {
|
public class MenuBar extends JMenuBar {
|
||||||
|
|
||||||
private javax.swing.JMenuItem setupMenu;
|
private JMenuItem preferencesMenu;
|
||||||
private javax.swing.JMenuItem aboutMenu;
|
private JMenuItem aboutMenu;
|
||||||
private javax.swing.JMenu fileMenu;
|
private JMenu fileMenu;
|
||||||
private javax.swing.JMenu helpMenu;
|
private JMenu helpMenu;
|
||||||
private javax.swing.JMenu pluginMenu;
|
private JMenu pluginMenu;
|
||||||
private javax.swing.JMenuItem exitMenu;
|
private Map<MenuCategory, JMenu> categories;
|
||||||
|
|
||||||
|
private JMenuItem exitMenu;
|
||||||
private final MainWindow mainWindow;
|
private final MainWindow mainWindow;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,63 +48,69 @@ public class MenuBar extends JMenuBar {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void initComponents() {
|
private void initComponents() {
|
||||||
fileMenu = new javax.swing.JMenu();
|
initFileMenu();
|
||||||
exitMenu = new javax.swing.JMenuItem();
|
initPluginMenu();
|
||||||
helpMenu = new javax.swing.JMenu();
|
initHelpMenu();
|
||||||
pluginMenu = new javax.swing.JMenu();
|
}
|
||||||
setupMenu = new javax.swing.JMenuItem();
|
|
||||||
aboutMenu = new javax.swing.JMenuItem();
|
|
||||||
|
|
||||||
fileMenu.setText("File");
|
private void initFileMenu() {
|
||||||
exitMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
|
fileMenu = new JMenu("File");
|
||||||
exitMenu.setText("Exit");
|
exitMenu = new JMenuItem("Exit");
|
||||||
|
|
||||||
|
exitMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK));
|
||||||
exitMenu.addActionListener(this::exitMenuActionPerformed);
|
exitMenu.addActionListener(this::exitMenuActionPerformed);
|
||||||
fileMenu.add(exitMenu);
|
fileMenu.add(exitMenu);
|
||||||
this.add(fileMenu);
|
this.add(fileMenu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initPluginMenu() {
|
||||||
|
pluginMenu = new JMenu("Plugin");
|
||||||
|
categories = new HashMap<>();
|
||||||
|
|
||||||
|
for (MenuCategory category : MenuCategory.values()) {
|
||||||
|
JMenu newCategoryMenu = new JMenu(category.toString());
|
||||||
|
|
||||||
|
pluginMenu.add(newCategoryMenu);
|
||||||
|
categories.put(category, newCategoryMenu);
|
||||||
|
}
|
||||||
|
|
||||||
pluginMenu.setText("Plugin");
|
|
||||||
this.add(pluginMenu);
|
this.add(pluginMenu);
|
||||||
|
}
|
||||||
|
|
||||||
helpMenu.setText("Help");
|
private void initHelpMenu() {
|
||||||
|
helpMenu = new JMenu("Help");
|
||||||
|
preferencesMenu = new JMenuItem("Preferences");
|
||||||
|
aboutMenu = new JMenuItem("About");
|
||||||
|
|
||||||
setupMenu.setText("Preferences");
|
preferencesMenu.addActionListener(this::setupMenuActionPerformed);
|
||||||
setupMenu.addActionListener(this::setupMenuActionPerformed);
|
helpMenu.add(preferencesMenu);
|
||||||
helpMenu.add(setupMenu);
|
|
||||||
|
|
||||||
aboutMenu.setText("About");
|
|
||||||
aboutMenu.addActionListener(this::aboutMenuActionPerformed);
|
aboutMenu.addActionListener(this::aboutMenuActionPerformed);
|
||||||
helpMenu.add(aboutMenu);
|
helpMenu.add(aboutMenu);
|
||||||
|
|
||||||
this.add(helpMenu);
|
this.add(helpMenu);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {
|
private void exitMenuActionPerformed(ActionEvent evt) {
|
||||||
mainWindow.exit();
|
mainWindow.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void setupMenuActionPerformed(ActionEvent evt) {
|
||||||
private void setupMenuActionPerformed(java.awt.event.ActionEvent evt) {
|
|
||||||
Login login = new Login();
|
Login login = new Login();
|
||||||
login.setVisible(true);
|
login.setVisible(true);
|
||||||
|
|
||||||
mainWindow.setUserName(login.getName());
|
mainWindow.setUserName(login.getName());
|
||||||
mainWindow.setPort(login.getPort());
|
mainWindow.getConnectionManager().setPort(login.getPort());
|
||||||
|
|
||||||
login.dispose();
|
login.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void aboutMenuActionPerformed(java.awt.event.ActionEvent evt) {
|
private void aboutMenuActionPerformed(ActionEvent evt) {
|
||||||
About about = new About();
|
About about = new About();
|
||||||
about.setVisible(true);
|
about.setVisible(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public void addPluginMenu(MenuCategory category, JMenuItem menu){
|
||||||
* Adiciona um menu fornecido por um plugin à seção de plugins da barra
|
categories.get(category).add(menu);
|
||||||
* de menus.
|
|
||||||
*
|
|
||||||
* @param menu menu criado pelo plugin.
|
|
||||||
*/
|
|
||||||
public void addPlugin(JMenu menu){
|
|
||||||
this.pluginMenu.add(menu);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,14 +2,16 @@ package pitiupi.GUI;
|
|||||||
|
|
||||||
import java.awt.BorderLayout;
|
import java.awt.BorderLayout;
|
||||||
import java.awt.Dimension;
|
import java.awt.Dimension;
|
||||||
|
import java.awt.event.MouseAdapter;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import javax.swing.BorderFactory;
|
import java.util.Map;
|
||||||
import javax.swing.DefaultListModel;
|
import java.util.function.Consumer;
|
||||||
import javax.swing.JList;
|
import javax.swing.*;
|
||||||
import javax.swing.JPanel;
|
|
||||||
import javax.swing.JScrollPane;
|
import pitiupi.models.Menus.MenuCategory;
|
||||||
import javax.swing.SwingUtilities;
|
import pitiupi.models.User;
|
||||||
import pitiupi.control.PeerInfo;
|
|
||||||
import pitiupi.control.PeerListener;
|
import pitiupi.control.PeerListener;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,10 +22,16 @@ import pitiupi.control.PeerListener;
|
|||||||
*/
|
*/
|
||||||
public class OnlineUsersPanel extends JPanel implements PeerListener {
|
public class OnlineUsersPanel extends JPanel implements PeerListener {
|
||||||
|
|
||||||
private final DefaultListModel<String> listModel;
|
private final DefaultListModel<User> listModel;
|
||||||
private final JList<String> userList;
|
private final JList<User> userList;
|
||||||
|
JPopupMenu menu;
|
||||||
|
private Map<MenuCategory, JMenu> categories;
|
||||||
|
|
||||||
public OnlineUsersPanel() {
|
public OnlineUsersPanel() {
|
||||||
|
menu = new JPopupMenu();
|
||||||
|
categories = new HashMap<>();
|
||||||
|
initMenu();
|
||||||
|
|
||||||
setLayout(new BorderLayout());
|
setLayout(new BorderLayout());
|
||||||
setBorder(BorderFactory.createTitledBorder("Online"));
|
setBorder(BorderFactory.createTitledBorder("Online"));
|
||||||
setPreferredSize(new Dimension(160, 0));
|
setPreferredSize(new Dimension(160, 0));
|
||||||
@@ -31,6 +39,48 @@ public class OnlineUsersPanel extends JPanel implements PeerListener {
|
|||||||
listModel = new DefaultListModel<>();
|
listModel = new DefaultListModel<>();
|
||||||
userList = new JList<>(listModel);
|
userList = new JList<>(listModel);
|
||||||
add(new JScrollPane(userList), BorderLayout.CENTER);
|
add(new JScrollPane(userList), BorderLayout.CENTER);
|
||||||
|
|
||||||
|
setupUserListActions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initMenu() {
|
||||||
|
for (MenuCategory category : MenuCategory.values()) {
|
||||||
|
JMenu newCategory = new JMenu(category.toString());
|
||||||
|
|
||||||
|
menu.add(newCategory);
|
||||||
|
categories.put(category, newCategory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setupUserListActions() {
|
||||||
|
userList.addMouseListener(new MouseAdapter() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseClicked(MouseEvent e) {
|
||||||
|
int index = userList.locationToIndex(e.getPoint());
|
||||||
|
|
||||||
|
if (index == -1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
userList.setSelectedIndex(index);
|
||||||
|
menu.show(userList, e.getX(), e.getY());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void initUnicastMenu(JMenuItem menuItem, Consumer<User> action) {
|
||||||
|
menuItem.addActionListener(e -> {
|
||||||
|
User user = userList.getSelectedValue();
|
||||||
|
|
||||||
|
if (user != null) {
|
||||||
|
action.accept(user);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addUnicastMenu(MenuCategory category, JMenuItem menuItem) {
|
||||||
|
categories.get(category).add(menuItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,11 +89,11 @@ public class OnlineUsersPanel extends JPanel implements PeerListener {
|
|||||||
* @param peers lista atualizada de usuários ativos na rede.
|
* @param peers lista atualizada de usuários ativos na rede.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onPeersChanged(List<PeerInfo> peers) {
|
public void onPeersChanged(List<User> peers) {
|
||||||
SwingUtilities.invokeLater(() -> {
|
SwingUtilities.invokeLater(() -> {
|
||||||
listModel.clear();
|
listModel.clear();
|
||||||
for (PeerInfo peer : peers) {
|
for (User peer : peers) {
|
||||||
listModel.addElement(peer.toString());
|
listModel.addElement(peer);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package pitiupi.control;
|
||||||
|
|
||||||
|
import pitiupi.GUI.MainWindow;
|
||||||
|
import pitiupi.control.plugins.PluginManager;
|
||||||
|
import pitiupi.models.Messages.HeartbeatMessage;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.net.tcp.SocketTCP;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
import pitiupi.net.udp.SocketUDP;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
|
||||||
|
public class ConnectionManager {
|
||||||
|
private final String pitiupiIdentifier;
|
||||||
|
|
||||||
|
private final PluginManager pluginManager;
|
||||||
|
|
||||||
|
private final HeartbeatManager heartbeatManager;
|
||||||
|
|
||||||
|
private SocketTCP socketTCP;
|
||||||
|
private SocketUDP socketUDP;
|
||||||
|
private String username;
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
public ConnectionManager(MainWindow main, String username, PluginManager pluginManager, int port) {
|
||||||
|
this.pluginManager = pluginManager;
|
||||||
|
|
||||||
|
this.username = username;
|
||||||
|
this.port = port;
|
||||||
|
|
||||||
|
pitiupiIdentifier = "Pitiupi.Alice.2026";
|
||||||
|
|
||||||
|
reconnect();
|
||||||
|
|
||||||
|
heartbeatManager = new HeartbeatManager(this);
|
||||||
|
heartbeatManager.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public TcpConnection connectPluginTcp(InetAddress destinationAdress, String senderId, String receiverId) {
|
||||||
|
return socketTCP.createPrivateConnection(destinationAdress, senderId, receiverId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean sendTcp(Message message, InetAddress destinationAddress) {
|
||||||
|
return socketTCP.send(message, destinationAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean sendUdpUnicast(Message message, InetAddress destinationAddress) {
|
||||||
|
try {
|
||||||
|
socketUDP.sendUnicast(message, destinationAddress);
|
||||||
|
return true;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean sendUdpMulticast(Message message) {
|
||||||
|
try {
|
||||||
|
socketUDP.sendMulticast(message);
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Error sending UDP Multicast");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void broadcastLocal(byte[] message) {
|
||||||
|
pluginManager.handleMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addPeerListener(PeerListener peerListener) {
|
||||||
|
heartbeatManager.addPeerListener(peerListener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receiveHeartbeat(HeartbeatMessage message, InetAddress destinationAddress) {
|
||||||
|
heartbeatManager.receiveHeartbeat(message, destinationAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPort(int port) {
|
||||||
|
this.port = port;
|
||||||
|
reconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPort() {
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIdentifier(){
|
||||||
|
return this.pitiupiIdentifier;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reconnect() {
|
||||||
|
if (this.socketUDP != null) {
|
||||||
|
this.socketUDP.close();
|
||||||
|
}
|
||||||
|
if (this.socketTCP != null) {
|
||||||
|
this.socketTCP.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.socketUDP = new SocketUDP(this, pluginManager);
|
||||||
|
this.socketTCP = new SocketTCP(this, pluginManager);
|
||||||
|
|
||||||
|
this.socketUDP.start();
|
||||||
|
this.socketTCP.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUserName() {
|
||||||
|
return this.username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUserName(String userName) {
|
||||||
|
this.username = userName;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package pitiupi.control;
|
||||||
|
|
||||||
|
import pitiupi.GUI.MainWindow;
|
||||||
|
import pitiupi.GUI.MenuBar;
|
||||||
|
import pitiupi.GUI.OnlineUsersPanel;
|
||||||
|
import pitiupi.models.Menus.*;
|
||||||
|
import pitiupi.models.Menus.MulticastMenus.MulticastActionMenu;
|
||||||
|
import pitiupi.models.Menus.MulticastMenus.MulticastMenu;
|
||||||
|
import pitiupi.models.Menus.MulticastMenus.MulticastSubMenu;
|
||||||
|
import pitiupi.models.Menus.UnicastMenus.UnicastActionMenu;
|
||||||
|
import pitiupi.models.Menus.UnicastMenus.UnicastMenu;
|
||||||
|
import pitiupi.models.Menus.UnicastMenus.UnicastSubMenu;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class GuiManager {
|
||||||
|
private MainWindow mainWindow;
|
||||||
|
private MenuBar menuBar;
|
||||||
|
private OnlineUsersPanel onlineUsersPanel;
|
||||||
|
|
||||||
|
private Logger logger;
|
||||||
|
|
||||||
|
public GuiManager(MainWindow mainWindow, MenuBar menuBar, OnlineUsersPanel onlineUsersPanel) {
|
||||||
|
this.mainWindow = mainWindow;
|
||||||
|
this.menuBar = menuBar;
|
||||||
|
this.onlineUsersPanel = onlineUsersPanel;
|
||||||
|
this.logger = Logger.getLogger(GuiManager.class.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createMenu(MenuCategory category, Menu menu) {
|
||||||
|
System.out.println(
|
||||||
|
menu.getClass().getSuperclass().getSuperclass()
|
||||||
|
);
|
||||||
|
|
||||||
|
System.out.println(
|
||||||
|
MulticastMenu.class
|
||||||
|
);
|
||||||
|
|
||||||
|
System.out.println(
|
||||||
|
menu.getClass().getSuperclass().getSuperclass()
|
||||||
|
== MulticastMenu.class
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
JMenuItem newMenu = buildMenu(menu);
|
||||||
|
if (menu instanceof MulticastMenu) {
|
||||||
|
menuBar.addPluginMenu(category, newMenu);
|
||||||
|
}
|
||||||
|
if (menu instanceof UnicastMenu) {
|
||||||
|
onlineUsersPanel.addUnicastMenu(category, newMenu);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e) {
|
||||||
|
logger.log(Level.WARNING, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JMenuItem buildMenu(Menu menu) {
|
||||||
|
if (menu instanceof MulticastSubMenu multicastSubMenu) {
|
||||||
|
JMenu newMenu = new JMenu(menu.getText());
|
||||||
|
|
||||||
|
for (Menu child : multicastSubMenu.getMenus()) {
|
||||||
|
newMenu.add(buildMenu(child));
|
||||||
|
}
|
||||||
|
|
||||||
|
return newMenu;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (menu instanceof UnicastSubMenu unicastSubMenu) {
|
||||||
|
JMenu newMenu = new JMenu(menu.getText());
|
||||||
|
|
||||||
|
for (Menu child : unicastSubMenu.getMenus()) {
|
||||||
|
newMenu.add(buildMenu(child));
|
||||||
|
}
|
||||||
|
|
||||||
|
return newMenu;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (menu instanceof MulticastActionMenu multicastActionMenu) {
|
||||||
|
JMenuItem newMenu = new JMenuItem(menu.getText());
|
||||||
|
newMenu.addActionListener(e -> multicastActionMenu.onClick());
|
||||||
|
return newMenu;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (menu instanceof UnicastActionMenu unicastActionMenu) {
|
||||||
|
JMenuItem newMenu = new JMenuItem(menu.getText());
|
||||||
|
|
||||||
|
onlineUsersPanel.initUnicastMenu(newMenu, unicastActionMenu::onClick);
|
||||||
|
return newMenu;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("Invalid menu type");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package pitiupi.control;
|
package pitiupi.control;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -10,10 +9,9 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.logging.Level;
|
|
||||||
import java.util.logging.Logger;
|
import pitiupi.models.User;
|
||||||
import pitiupi.GUI.MainWindow;
|
import pitiupi.models.Messages.HeartbeatMessage;
|
||||||
import pitiupi.net.HeartbeatMessage;
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
/**
|
/**
|
||||||
* Gerencia o mecanismo de heartbeat da aplicação.
|
* Gerencia o mecanismo de heartbeat da aplicação.
|
||||||
@@ -28,9 +26,8 @@ public class HeartbeatManager {
|
|||||||
|
|
||||||
private static final long HEARTBEAT_INTERVAL_MS = 5000;
|
private static final long HEARTBEAT_INTERVAL_MS = 5000;
|
||||||
private static final long PEER_TIMEOUT_MS = 15000; // ~3 batimentos perdidos
|
private static final long PEER_TIMEOUT_MS = 15000; // ~3 batimentos perdidos
|
||||||
|
private final ConnectionManager connectionManager;
|
||||||
private final MainWindow mainWindow;
|
private final Map<String, User> peers = new ConcurrentHashMap<>();
|
||||||
private final Map<String, PeerInfo> peers = new ConcurrentHashMap<>();
|
|
||||||
private final List<PeerListener> listeners = new CopyOnWriteArrayList<>();
|
private final List<PeerListener> listeners = new CopyOnWriteArrayList<>();
|
||||||
private ScheduledExecutorService scheduler;
|
private ScheduledExecutorService scheduler;
|
||||||
private final String instanceId = UUID.randomUUID().toString();
|
private final String instanceId = UUID.randomUUID().toString();
|
||||||
@@ -38,11 +35,9 @@ public class HeartbeatManager {
|
|||||||
/**
|
/**
|
||||||
* Cria um gerenciador de heartbeat associado à janela principal da aplicação.
|
* Cria um gerenciador de heartbeat associado à janela principal da aplicação.
|
||||||
*
|
*
|
||||||
* @param mainWindow janela principal utilizada para obter o nome do usuário
|
|
||||||
* e o socket de comunicação.
|
|
||||||
*/
|
*/
|
||||||
public HeartbeatManager(MainWindow mainWindow) {
|
public HeartbeatManager(ConnectionManager connectionManager) {
|
||||||
this.mainWindow = mainWindow;
|
this.connectionManager = connectionManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -64,12 +59,8 @@ public class HeartbeatManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void announce() {
|
private void announce() {
|
||||||
try {
|
HeartbeatMessage msg = new HeartbeatMessage(connectionManager.getUserName(), instanceId);
|
||||||
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
|
connectionManager.sendUdpMulticast(msg);
|
||||||
mainWindow.getSocketUDP().sendMulticast(msg.toByteArray());
|
|
||||||
} catch (IOException ex) {
|
|
||||||
Logger.getLogger(HeartbeatManager.class.getName()).log(Level.WARNING, "Falha ao enviar heartbeat", ex);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chamado pelo Socket quando um pacote é identificado como heartbeat
|
// Chamado pelo Socket quando um pacote é identificado como heartbeat
|
||||||
@@ -94,7 +85,7 @@ public class HeartbeatManager {
|
|||||||
String key = msg.getInstanceId();
|
String key = msg.getInstanceId();
|
||||||
boolean isNew = !peers.containsKey(key);
|
boolean isNew = !peers.containsKey(key);
|
||||||
|
|
||||||
PeerInfo peer = peers.computeIfAbsent(key, k -> new PeerInfo(msg.getUserName(), from, msg.getTimestamp()));
|
User peer = peers.computeIfAbsent(key, k -> new User(msg.getUserName(), from, msg.getTimestamp()));
|
||||||
peer.touch(System.currentTimeMillis());
|
peer.touch(System.currentTimeMillis());
|
||||||
|
|
||||||
if (isNew) {
|
if (isNew) {
|
||||||
@@ -111,7 +102,7 @@ public class HeartbeatManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void notifyListeners() {
|
private void notifyListeners() {
|
||||||
List<PeerInfo> snapshot = new ArrayList<>(peers.values());
|
List<User> snapshot = new ArrayList<>(peers.values());
|
||||||
for (PeerListener l : listeners) {
|
for (PeerListener l : listeners) {
|
||||||
l.onPeersChanged(snapshot);
|
l.onPeersChanged(snapshot);
|
||||||
}
|
}
|
||||||
@@ -144,7 +135,7 @@ public class HeartbeatManager {
|
|||||||
*
|
*
|
||||||
* @return lista contendo os peers atualmente conhecidos.
|
* @return lista contendo os peers atualmente conhecidos.
|
||||||
*/
|
*/
|
||||||
public List<PeerInfo> getPeers() {
|
public List<User> getPeers() {
|
||||||
return new ArrayList<>(peers.values());
|
return new ArrayList<>(peers.values());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package pitiupi.control;
|
package pitiupi.control;
|
||||||
|
|
||||||
|
import pitiupi.models.User;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,5 +19,5 @@ public interface PeerListener {
|
|||||||
*
|
*
|
||||||
* @param peers lista atualizada de usuários ativos.
|
* @param peers lista atualizada de usuários ativos.
|
||||||
*/
|
*/
|
||||||
void onPeersChanged(List<PeerInfo> peers);
|
void onPeersChanged(List<User> peers);
|
||||||
}
|
}
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
/*
|
|
||||||
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
|
||||||
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
|
|
||||||
*/
|
|
||||||
package pitiupi.control;
|
|
||||||
|
|
||||||
import java.awt.List;
|
|
||||||
import java.io.File;
|
|
||||||
import java.net.MalformedURLException;
|
|
||||||
import java.net.URL;
|
|
||||||
import java.net.URLClassLoader;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.ServiceLoader;
|
|
||||||
import java.util.Vector;
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.Main;
|
|
||||||
import pitiupi.plugin.Plugin;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Responsável por localizar, carregar e registrar os plugins
|
|
||||||
* presentes no diretório {@code plugins}.
|
|
||||||
*
|
|
||||||
* <p>Os plugins são descobertos utilizando {@link java.util.ServiceLoader}
|
|
||||||
* e devem estar empacotados como arquivos JAR contendo a configuração
|
|
||||||
* {@code META-INF/services} correspondente.</p>
|
|
||||||
* @author flavio
|
|
||||||
*/
|
|
||||||
public class PluginLoader {
|
|
||||||
|
|
||||||
private final pitiupi.GUI.MainWindow mainWindow;
|
|
||||||
|
|
||||||
public PluginLoader(MainWindow main) {
|
|
||||||
this.mainWindow = main;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void loadPlugins() {
|
|
||||||
File pluginDir = new File("plugins");
|
|
||||||
File[] jarFiles = pluginDir.listFiles((dir, name) -> name.endsWith(".jar"));
|
|
||||||
|
|
||||||
if (jarFiles == null || jarFiles.length == 0) {
|
|
||||||
System.out.println("No plugins found in the " + pluginDir.getAbsolutePath() + " directory.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 2. Convert jar file paths into URLs
|
|
||||||
ArrayList urls = new ArrayList();
|
|
||||||
for (File file : jarFiles) {
|
|
||||||
urls.add(file.toURI().toURL());
|
|
||||||
System.out.println("Discovered plugin package: " + file.getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Create a class loader isolated from the application's default loader
|
|
||||||
URLClassLoader pluginClassLoader = new URLClassLoader(
|
|
||||||
(URL[])urls.toArray(new URL[0]),
|
|
||||||
Main.class.getClassLoader()
|
|
||||||
);
|
|
||||||
System.out.println(pluginClassLoader);
|
|
||||||
|
|
||||||
// 4. Locate and instantiate all classes implementing the Plugin interface
|
|
||||||
ServiceLoader<Plugin> serviceLoader = ServiceLoader.load(Plugin.class, pluginClassLoader);
|
|
||||||
|
|
||||||
System.out.println("\n--- Executing Discovered Plugins ---" + serviceLoader.findFirst());
|
|
||||||
for (Plugin plugin : serviceLoader) {
|
|
||||||
System.out.println("Loading: " + plugin.getName());
|
|
||||||
plugin.createPlugin(this.mainWindow);
|
|
||||||
this.mainWindow.getPlugins().add(plugin);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (MalformedURLException e) {
|
|
||||||
System.out.println(e.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package pitiupi.control.plugins;
|
||||||
|
|
||||||
|
import pitiupi.models.Plugin;
|
||||||
|
|
||||||
|
class LoadedPlugin {
|
||||||
|
|
||||||
|
private final Plugin plugin;
|
||||||
|
private final ClassLoader classLoader;
|
||||||
|
|
||||||
|
public LoadedPlugin(Plugin plugin, ClassLoader classLoader) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
this.classLoader = classLoader;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Plugin getPlugin() {
|
||||||
|
return plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClassLoader getClassLoader() {
|
||||||
|
return classLoader;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package pitiupi.control.plugins;
|
||||||
|
|
||||||
|
import pitiupi.Main;
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.GuiManager;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
import pitiupi.models.Plugin;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLClassLoader;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ServiceLoader;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class PluginManager {
|
||||||
|
private final List<LoadedPlugin> loadedPlugins;
|
||||||
|
private final HashSet<String> loadedJars;
|
||||||
|
|
||||||
|
private final Logger logger;
|
||||||
|
|
||||||
|
public PluginManager() {
|
||||||
|
this.loadedPlugins = new ArrayList<>();
|
||||||
|
this.loadedJars = new HashSet<>();
|
||||||
|
|
||||||
|
logger = Logger.getLogger(getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void handleMessage(byte[] msg) {
|
||||||
|
Message message = null;
|
||||||
|
|
||||||
|
for (LoadedPlugin loadedPlugin : loadedPlugins) {
|
||||||
|
message = deserialize(msg, loadedPlugin.getClassLoader());
|
||||||
|
if (message != null) break;
|
||||||
|
}
|
||||||
|
if (message == null) return;
|
||||||
|
|
||||||
|
for (LoadedPlugin loadedPlugin : loadedPlugins) {
|
||||||
|
Plugin plugin = loadedPlugin.getPlugin();
|
||||||
|
|
||||||
|
if (plugin.receiveAllTypes() && message.isPublic()) {
|
||||||
|
plugin.receiveMessage(message);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Class<? extends Message> messageType : plugin.getMessages()) {
|
||||||
|
if (messageType.isInstance(message)) {
|
||||||
|
plugin.receiveMessage(message);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Plugin getPlugin(String pluginId) {
|
||||||
|
for (LoadedPlugin loadedPlugin : loadedPlugins) {
|
||||||
|
if (loadedPlugin.getPlugin().getIdentifier().equals(pluginId)) {
|
||||||
|
return loadedPlugin.getPlugin();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void handleMessageFromConnection(TcpConnection connection, byte[] msg) {
|
||||||
|
Plugin plugin = getPlugin(connection.getReceiver());
|
||||||
|
if (plugin == null) return;
|
||||||
|
|
||||||
|
plugin.receiveBytes(connection, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean handleConnection(TcpConnection connection, String receiverId) {
|
||||||
|
Plugin plugin = getPlugin(receiverId);
|
||||||
|
if (plugin == null) return false;
|
||||||
|
|
||||||
|
plugin.receivePrivateConnection(connection);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void handleDisconnection(TcpConnection connection, String receiverId) {
|
||||||
|
Plugin plugin = getPlugin(receiverId);
|
||||||
|
if (plugin == null) return;
|
||||||
|
|
||||||
|
plugin.onSocketClosed(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void loadPlugins(ConnectionManager connectionManager, GuiManager guiManager) {
|
||||||
|
File pluginDir = new File("plugins");
|
||||||
|
File[] jarFiles = pluginDir.listFiles((dir, name) -> name.endsWith(".jar"));
|
||||||
|
|
||||||
|
if (jarFiles == null || jarFiles.length == 0) {
|
||||||
|
System.out.println("No plugins found in the " + pluginDir.getAbsolutePath() + " directory.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (File file : jarFiles) {
|
||||||
|
|
||||||
|
if (loadedJars.contains(file.getName())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Discovered plugin package: " + file.getName());
|
||||||
|
|
||||||
|
try {
|
||||||
|
URLClassLoader classLoader = new URLClassLoader(
|
||||||
|
new URL[]{file.toURI().toURL()},
|
||||||
|
Main.class.getClassLoader()
|
||||||
|
);
|
||||||
|
|
||||||
|
ServiceLoader<Plugin> serviceLoader = ServiceLoader.load(Plugin.class, classLoader);
|
||||||
|
|
||||||
|
for (Plugin plugin : serviceLoader) {
|
||||||
|
LoadedPlugin loadedPlugin = new LoadedPlugin(plugin, classLoader);
|
||||||
|
|
||||||
|
plugin.createPlugin(connectionManager, guiManager);
|
||||||
|
loadedPlugins.add(loadedPlugin);
|
||||||
|
loadedJars.add(file.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.log(Level.WARNING, "Failed to load plugin " + file.getName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Message deserialize(byte[] data, ClassLoader classLoader) {
|
||||||
|
try {
|
||||||
|
ByteArrayInputStream input = new ByteArrayInputStream(data);
|
||||||
|
|
||||||
|
PluginObjectInputStream objectInput = new PluginObjectInputStream(input, classLoader);
|
||||||
|
|
||||||
|
Object object = objectInput.readObject();
|
||||||
|
|
||||||
|
if (!(object instanceof Message)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (Message) object;
|
||||||
|
}
|
||||||
|
catch (ClassNotFoundException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
logger.log(Level.SEVERE, "Failed to load plugin package", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package pitiupi.control.plugins;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectStreamClass;
|
||||||
|
|
||||||
|
public class PluginObjectInputStream extends ObjectInputStream {
|
||||||
|
private final ClassLoader classLoader;
|
||||||
|
|
||||||
|
public PluginObjectInputStream(InputStream input, ClassLoader classLoader) throws IOException {
|
||||||
|
super(input);
|
||||||
|
this.classLoader = classLoader;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Class<?> resolveClass(ObjectStreamClass description) throws ClassNotFoundException {
|
||||||
|
return Class.forName(description.getName(), false, classLoader);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package pitiupi.models.Menus;
|
||||||
|
|
||||||
|
public abstract class Menu {
|
||||||
|
public abstract String getText();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package pitiupi.models.Menus;
|
||||||
|
|
||||||
|
public enum MenuCategory {
|
||||||
|
Jogos,
|
||||||
|
Social,
|
||||||
|
Streaming
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package pitiupi.models.Menus.MulticastMenus;
|
||||||
|
|
||||||
|
public abstract class MulticastActionMenu extends MulticastMenu{
|
||||||
|
public abstract void onClick();
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package pitiupi.models.Menus.MulticastMenus;
|
||||||
|
|
||||||
|
import pitiupi.models.Menus.Menu;
|
||||||
|
|
||||||
|
public abstract class MulticastMenu extends Menu {
|
||||||
|
MulticastMenu() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package pitiupi.models.Menus.MulticastMenus;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public abstract class MulticastSubMenu extends MulticastMenu{
|
||||||
|
public abstract List<MulticastMenu> getMenus();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package pitiupi.models.Menus.UnicastMenus;
|
||||||
|
|
||||||
|
import pitiupi.models.User;
|
||||||
|
|
||||||
|
public abstract class UnicastActionMenu extends UnicastMenu{
|
||||||
|
public abstract void onClick(User user);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package pitiupi.models.Menus.UnicastMenus;
|
||||||
|
|
||||||
|
import pitiupi.models.Menus.Menu;
|
||||||
|
import pitiupi.models.User;
|
||||||
|
|
||||||
|
public abstract class UnicastMenu extends Menu {
|
||||||
|
UnicastMenu() {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package pitiupi.models.Menus.UnicastMenus;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public abstract class UnicastSubMenu extends UnicastMenu{
|
||||||
|
public abstract List<UnicastMenu> getMenus();
|
||||||
|
}
|
||||||
+2
-1
@@ -1,4 +1,5 @@
|
|||||||
package pitiupi.net;
|
package pitiupi.models.Messages;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mensagem utilizada para sinalizar a presença de um usuário na rede.
|
* Mensagem utilizada para sinalizar a presença de um usuário na rede.
|
||||||
*
|
*
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package pitiupi.models.Messages;
|
||||||
|
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class InfoMessage extends Message {
|
||||||
|
private final InfoType type;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public InfoMessage(String message, InfoType type) {
|
||||||
|
this.message = message;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public InfoType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void sendSystemInfo(TcpConnection connection, InfoType type, String description) {
|
||||||
|
try {
|
||||||
|
InfoMessage error = new InfoMessage(description, type);
|
||||||
|
connection.send(error.toByteArray());
|
||||||
|
} catch (IOException ex) {
|
||||||
|
Logger.getLogger(InfoMessage.class.getName()).log(Level.WARNING, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static InfoMessage parseSystemInfo(byte[] bytes) {
|
||||||
|
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||||
|
|
||||||
|
Object object = ois.readObject();
|
||||||
|
if (object instanceof InfoMessage) {
|
||||||
|
return (InfoMessage) object;
|
||||||
|
}
|
||||||
|
} catch (IOException | ClassNotFoundException ex) {
|
||||||
|
Logger.getLogger(InfoMessage.class.getName()).log(Level.WARNING, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package pitiupi.models.Messages;
|
||||||
|
|
||||||
|
public enum InfoType {
|
||||||
|
CONNECTION_REJECTED,
|
||||||
|
RECEIVER_NOT_FOUND,
|
||||||
|
MESSAGE_REJECTED,
|
||||||
|
INTERNAL_ERROR,
|
||||||
|
CONNECTION_CLOSED,
|
||||||
|
}
|
||||||
+14
-1
@@ -3,7 +3,7 @@
|
|||||||
* To change this template file, choose Tools | Templates
|
* To change this template file, choose Tools | Templates
|
||||||
* and open the template in the editor.
|
* and open the template in the editor.
|
||||||
*/
|
*/
|
||||||
package pitiupi.net;
|
package pitiupi.models.Messages;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -24,6 +24,19 @@ import java.io.Serializable;
|
|||||||
* @author flavio
|
* @author flavio
|
||||||
*/
|
*/
|
||||||
public abstract class Message implements Serializable{
|
public abstract class Message implements Serializable{
|
||||||
|
private boolean isPublic;
|
||||||
|
|
||||||
|
protected Message(){
|
||||||
|
isPublic = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Message(boolean isPublic){
|
||||||
|
this.isPublic = isPublic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPublic(){
|
||||||
|
return isPublic;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serializa a mensagem para um vetor de bytes.
|
* Serializa a mensagem para um vetor de bytes.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
/*
|
||||||
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
||||||
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
|
||||||
|
*/
|
||||||
|
package pitiupi.models;
|
||||||
|
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.GuiManager;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.net.tcp.TcpConnection;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface base para plugins da aplicação.
|
||||||
|
*
|
||||||
|
* <p>Cada plugin deve implementar esta interface para ser carregado
|
||||||
|
* pela aplicação e participar do sistema de comunicação por mensagens.</p>
|
||||||
|
*
|
||||||
|
* @author flavio
|
||||||
|
*/
|
||||||
|
public abstract class Plugin {
|
||||||
|
public abstract String getName();
|
||||||
|
public abstract String getAuthor();
|
||||||
|
public abstract String getVersion();
|
||||||
|
public abstract String getIdentifier();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicializa o plugin.
|
||||||
|
*
|
||||||
|
* <p>Este método é chamado pela aplicação após o carregamento do plugin.</p>
|
||||||
|
*
|
||||||
|
* @param connectionManager interface com o sistema de conexões da aplicação.
|
||||||
|
* @param guiManager interface com a janela principal da aplicação
|
||||||
|
*/
|
||||||
|
public abstract void createPlugin(ConnectionManager connectionManager, GuiManager guiManager);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retorna uma mensagem utilizada pelo plugin.
|
||||||
|
*
|
||||||
|
* @return mensagem criada pelo plugin.
|
||||||
|
*/
|
||||||
|
public abstract List<Class<? extends Message>> getMessages();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recebe uma mensagem enviada pela aplicação.
|
||||||
|
*
|
||||||
|
* <p>A mensagem é recebida em formato serializado. O plugin deve verificar
|
||||||
|
* se a mensagem pertence ao seu tipo e realizar o processamento necessário.</p>
|
||||||
|
*
|
||||||
|
* @param message mensagem serializada recebida.
|
||||||
|
*/
|
||||||
|
public abstract void receiveMessage(Message message);
|
||||||
|
|
||||||
|
public boolean receiveAllTypes() {return false;}
|
||||||
|
public boolean receivePrivateConnection(TcpConnection connection) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
public boolean receiveBytes(TcpConnection connection, byte[] bytes) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
public boolean onSocketClosed(TcpConnection connection) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package pitiupi.control;
|
package pitiupi.models;
|
||||||
|
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
/**
|
/**
|
||||||
@@ -10,13 +10,13 @@ import java.net.InetAddress;
|
|||||||
*
|
*
|
||||||
* @author tony
|
* @author tony
|
||||||
*/
|
*/
|
||||||
public class PeerInfo {
|
public class User {
|
||||||
|
|
||||||
private final String userName;
|
private final String userName;
|
||||||
private final InetAddress address;
|
private final InetAddress address;
|
||||||
private volatile long lastSeen;
|
private volatile long lastSeen;
|
||||||
|
|
||||||
public PeerInfo(String userName, InetAddress address, long lastSeen) {
|
public User(String userName, InetAddress address, long lastSeen) {
|
||||||
this.userName = userName;
|
this.userName = userName;
|
||||||
this.address = address;
|
this.address = address;
|
||||||
this.lastSeen = lastSeen;
|
this.lastSeen = lastSeen;
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
package pitiupi.net;
|
|
||||||
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.control.PeerInfo;
|
|
||||||
import pitiupi.control.PeerListener;
|
|
||||||
import pitiupi.plugin.Plugin;
|
|
||||||
|
|
||||||
import java.io.*;
|
|
||||||
import java.net.*;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gerencia a comunicação TCP da aplicação.
|
|
||||||
*
|
|
||||||
* <p>Mantém conexões persistentes com os peers e reutiliza essas conexões
|
|
||||||
* para o envio de mensagens. As mensagens recebidas são encaminhadas aos
|
|
||||||
* plugins, que são responsáveis por interpretá-las.</p>
|
|
||||||
*
|
|
||||||
* <p>Novas conexões são aceitas pelo servidor e cada conexão possui uma
|
|
||||||
* tarefa própria para receber mensagens, permitindo que múltiplas conexões
|
|
||||||
* sejam mantidas simultaneamente.</p>
|
|
||||||
*
|
|
||||||
* <p>As conexões são associadas aos endereços dos peers e podem ser
|
|
||||||
* encerradas quando um peer deixa de estar ativo.</p>
|
|
||||||
*
|
|
||||||
* @author Gustavo
|
|
||||||
*/
|
|
||||||
public class SocketTCP extends Thread implements PeerListener {
|
|
||||||
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
|
|
||||||
private final Map<InetAddress, TcpConnection> connections;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
private InetAddress address;
|
|
||||||
|
|
||||||
private final MainWindow main;
|
|
||||||
|
|
||||||
private volatile boolean running = true;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria o servidor TCP da aplicação.
|
|
||||||
*
|
|
||||||
* <p>O servidor utiliza a porta definida pela aplicação e inicia sem
|
|
||||||
* estabelecer conexões com os peers. As conexões são criadas conforme
|
|
||||||
* necessário durante o envio ou recebidas de outros peers.</p>
|
|
||||||
*
|
|
||||||
* @param main janela principal da aplicação.
|
|
||||||
*/
|
|
||||||
public SocketTCP(MainWindow main) {
|
|
||||||
this.main = main;
|
|
||||||
connections = new ConcurrentHashMap<>();
|
|
||||||
try {
|
|
||||||
serverSocket = new ServerSocket(main.getPort());
|
|
||||||
address = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println("There is no socket connection. Sorry.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envia uma mensagem TCP para um peer.
|
|
||||||
*
|
|
||||||
* <p>Uma conexão existente com o peer é reutilizada. Caso não exista uma
|
|
||||||
* conexão válida, uma nova conexão é criada e adicionada ao conjunto de
|
|
||||||
* conexões ativas.</p>
|
|
||||||
*
|
|
||||||
* @param msg mensagem serializada a ser enviada.
|
|
||||||
* @param destinationAddress endereço IP do peer destinatário.
|
|
||||||
*/
|
|
||||||
public void send(byte[] msg, InetAddress destinationAddress) {
|
|
||||||
try {
|
|
||||||
if (destinationAddress.equals(address)) {
|
|
||||||
throw new IllegalArgumentException("Destination address cannot be the same as the original address.");
|
|
||||||
}
|
|
||||||
TcpConnection connec tion;
|
|
||||||
|
|
||||||
synchronized (connections) {
|
|
||||||
connection = connections.get(destinationAddress);
|
|
||||||
|
|
||||||
if (connection == null || connection.isClosed()) {
|
|
||||||
Socket socket = new Socket(destinationAddress, main.getPort());
|
|
||||||
|
|
||||||
connection = new TcpConnection(socket);
|
|
||||||
|
|
||||||
connections.put(destinationAddress, connection);
|
|
||||||
|
|
||||||
startReceiver(destinationAddress, connection);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connection.send(msg);
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println("Could not send TCP message.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aguarda e aceita novas conexões TCP.
|
|
||||||
*
|
|
||||||
* <p>Cada conexão aceita é associada ao endereço do peer e registrada para
|
|
||||||
* que possa ser utilizada tanto para recepção quanto para envio de
|
|
||||||
* mensagens.</p>
|
|
||||||
*/
|
|
||||||
private void receive() {
|
|
||||||
while (running) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Socket socket = serverSocket.accept();
|
|
||||||
|
|
||||||
InetAddress address = socket.getInetAddress();
|
|
||||||
|
|
||||||
TcpConnection connection = new TcpConnection(socket);
|
|
||||||
|
|
||||||
TcpConnection oldConnection = connections.put(address, connection);
|
|
||||||
|
|
||||||
if (oldConnection != null) {
|
|
||||||
oldConnection.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
startReceiver(address, connection);
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
|
|
||||||
if (!running) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("Error accepting TCP connection.");
|
|
||||||
System.out.println(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicia a recepção de mensagens de uma conexão TCP.
|
|
||||||
*
|
|
||||||
* <p>A recepção é executada de forma independente para que uma conexão
|
|
||||||
* não impeça a aceitação ou o processamento de outras conexões.</p>
|
|
||||||
*
|
|
||||||
* <p>Cada mensagem recebida é encaminhada aos plugins da aplicação.</p>
|
|
||||||
*
|
|
||||||
* @param address endereço do peer associado à conexão.
|
|
||||||
* @param connection conexão TCP utilizada para a comunicação.
|
|
||||||
*/
|
|
||||||
private void startReceiver(InetAddress address, TcpConnection connection) {
|
|
||||||
connectionExecutor.submit(() -> {
|
|
||||||
try {
|
|
||||||
while (running) {
|
|
||||||
byte[] message = connection.receive();
|
|
||||||
|
|
||||||
for (Plugin plugin : main.getPlugins()) {
|
|
||||||
plugin.receiveMessage(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException ex) {
|
|
||||||
System.out.println(
|
|
||||||
"Connection with " + address.getHostAddress() + " closed."
|
|
||||||
);
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
connections.remove(address, connection);
|
|
||||||
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicia o processo de recepção de conexões TCP.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
receive();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encerra o servidor TCP e as conexões associadas.
|
|
||||||
*
|
|
||||||
* <p>As conexões existentes são encerradas e o servidor deixa
|
|
||||||
* de aceitar novas conexões.</p>
|
|
||||||
*/
|
|
||||||
public void close() {
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
if (serverSocket != null) {
|
|
||||||
try {
|
|
||||||
serverSocket.close();
|
|
||||||
} catch (IOException _) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (TcpConnection connection : connections.values()) {
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException _) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connections.clear();
|
|
||||||
|
|
||||||
connectionExecutor.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Atualiza as conexões de acordo com os peers atualmente ativos.
|
|
||||||
*
|
|
||||||
* <p>Conexões associadas a peers que não estão mais ativos são encerradas
|
|
||||||
* e removidas.</p>
|
|
||||||
*
|
|
||||||
* @param peers lista atualizada de peers ativos.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onPeersChanged(List<PeerInfo> peers) {
|
|
||||||
Set<InetAddress> activePeers = peers.stream()
|
|
||||||
.map(PeerInfo::getAddress)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
for (InetAddress address : connections.keySet()) {
|
|
||||||
if (!activePeers.contains(address)) {
|
|
||||||
|
|
||||||
TcpConnection connection = connections.remove(address);
|
|
||||||
if (connection != null) {
|
|
||||||
try {
|
|
||||||
connection.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package pitiupi.net;
|
|
||||||
|
|
||||||
import java.io.DataInputStream;
|
|
||||||
import java.io.DataOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.Socket;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Representa uma conexão TCP persistente com um peer.
|
|
||||||
*
|
|
||||||
* <p>Encapsula o socket e os streams utilizados para enviar e receber
|
|
||||||
* mensagens. Também é responsável pelo framing das mensagens, permitindo
|
|
||||||
* que várias mensagens sejam transmitidas pela mesma conexão.</p>
|
|
||||||
*
|
|
||||||
* @author Gustavo
|
|
||||||
*/
|
|
||||||
class TcpConnection {
|
|
||||||
|
|
||||||
private final Socket socket;
|
|
||||||
private final DataInputStream input;
|
|
||||||
private final DataOutputStream output;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria uma conexão a partir de um socket existente.
|
|
||||||
*
|
|
||||||
* @param socket socket TCP utilizado pela conexão.
|
|
||||||
* @throws IOException caso não seja possível obter os streams do socket.
|
|
||||||
*/
|
|
||||||
public TcpConnection(Socket socket) throws IOException {
|
|
||||||
this.socket = socket;
|
|
||||||
this.input = new DataInputStream(socket.getInputStream());
|
|
||||||
this.output = new DataOutputStream(socket.getOutputStream());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envia uma mensagem pela conexão.
|
|
||||||
*
|
|
||||||
* <p>A mensagem é precedida por seu tamanho para permitir que o receptor
|
|
||||||
* identifique o limite entre mensagens transmitidas pela mesma conexão.</p>
|
|
||||||
*
|
|
||||||
* @param message mensagem serializada a ser enviada.
|
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
|
||||||
*/
|
|
||||||
public void send(byte[] message) throws IOException {
|
|
||||||
synchronized (output) {
|
|
||||||
output.writeInt(message.length);
|
|
||||||
output.write(message);
|
|
||||||
output.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recebe uma mensagem completa da conexão.
|
|
||||||
*
|
|
||||||
* <p>O tamanho da mensagem é lido primeiro e, em seguida, os dados
|
|
||||||
* correspondentes são recebidos.</p>
|
|
||||||
*
|
|
||||||
* @return mensagem recebida.
|
|
||||||
* @throws IOException caso ocorra um erro durante a recepção.
|
|
||||||
*/
|
|
||||||
public byte[] receive() throws IOException {
|
|
||||||
int length = input.readInt();
|
|
||||||
|
|
||||||
if (length < 0) {
|
|
||||||
throw new IOException("Invalid message length.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return input.readNBytes(length);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifica se o socket da conexão está fechado.
|
|
||||||
*
|
|
||||||
* @return {@code true} caso o socket esteja fechado.
|
|
||||||
*/
|
|
||||||
public boolean isClosed() {
|
|
||||||
return socket.isClosed();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encerra a conexão TCP.
|
|
||||||
*
|
|
||||||
* @throws IOException caso ocorra um erro ao fechar o socket.
|
|
||||||
*/
|
|
||||||
public void close() throws IOException {
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.models.Messages.InfoMessage;
|
||||||
|
import pitiupi.models.Messages.InfoType;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fábrica responsável pela criação e configuração de conexões TCP.
|
||||||
|
*
|
||||||
|
* <p>Esta classe centraliza o estabelecimento de conexões de saída e a
|
||||||
|
* configuração de conexões recebidas. Antes de uma conexão ser considerada
|
||||||
|
* válida, é realizado um handshake entre os peers para identificar o remetente,
|
||||||
|
* o destinatário e se a conexão é privada.</p>
|
||||||
|
*
|
||||||
|
* <p>Durante o handshake é utilizado um timeout menor, definido por
|
||||||
|
* {@link #HANDSHAKE_TIMEOUT}. Após a validação bem-sucedida, a conexão passa
|
||||||
|
* a utilizar o timeout padrão definido por {@link #STANDARD_TIMEOUT}.</p>
|
||||||
|
*/
|
||||||
|
public class ConnectionFactory {
|
||||||
|
private static final int HANDSHAKE_TIMEOUT = 1000;
|
||||||
|
private static final int STANDARD_TIMEOUT = 300_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria uma conexão TCP de saída com o peer de destino e realiza o handshake
|
||||||
|
* necessário para validá-la.
|
||||||
|
*
|
||||||
|
* <p>A conexão é configurada com os identificadores do remetente e do
|
||||||
|
* destinatário e com o tipo indicado pelo parâmetro {@code isPrivate}.
|
||||||
|
* Após o estabelecimento do socket, o método envia um
|
||||||
|
* {@link HandshakeMessage} e aguarda uma resposta válida.</p>
|
||||||
|
*
|
||||||
|
* <p>Se o handshake for validado com sucesso, o timeout da conexão é
|
||||||
|
* alterado de {@link #HANDSHAKE_TIMEOUT} para {@link #STANDARD_TIMEOUT}
|
||||||
|
* e a conexão é retornada. Caso contrário, {@code null} é retornado.</p>
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer de destino.
|
||||||
|
* @param port porta TCP na qual o peer de destino está aguardando conexões.
|
||||||
|
* @param sender identificador do remetente da conexão.
|
||||||
|
* @param receiver identificador do destinatário da conexão.
|
||||||
|
* @param isPrivate {@code true} se a conexão deve ser privada;
|
||||||
|
* {@code false} se deve ser pública.
|
||||||
|
* @return a conexão TCP estabelecida e validada ou {@code null} caso
|
||||||
|
* não seja possível estabelecer ou validar a conexão.
|
||||||
|
*/
|
||||||
|
public static TcpConnection createConnection(InetAddress address, int port, String sender, String receiver, boolean isPrivate) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
Socket socket = new Socket(address, port);
|
||||||
|
connection = new TcpConnection(socket);
|
||||||
|
connection.setSender(sender);
|
||||||
|
connection.setReceiver(receiver);
|
||||||
|
connection.setPrivate(isPrivate);
|
||||||
|
|
||||||
|
HandshakeMessage handshake = new HandshakeMessage(isPrivate, sender, receiver);
|
||||||
|
|
||||||
|
connection.send(handshake.toByteArray());
|
||||||
|
HandshakeMessage handshakeResponse = validateConnection(connection);
|
||||||
|
|
||||||
|
if (handshakeResponse == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
connection.setTimeout(STANDARD_TIMEOUT);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configura uma conexão TCP recebida e valida o handshake enviado pelo
|
||||||
|
* peer remoto.
|
||||||
|
*
|
||||||
|
* <p>O handshake recebido é utilizado para obter e configurar os
|
||||||
|
* identificadores do remetente e do destinatário, bem como o tipo da
|
||||||
|
* conexão. Após a validação bem-sucedida, o timeout da conexão é alterado
|
||||||
|
* para {@link #STANDARD_TIMEOUT}.</p>
|
||||||
|
*
|
||||||
|
* <p>O {@link Socket} recebido deve representar uma conexão TCP já aceita
|
||||||
|
* pelo servidor.</p>
|
||||||
|
*
|
||||||
|
* @param socket socket TCP correspondente à conexão recebida.
|
||||||
|
* @return a conexão TCP configurada e validada ou {@code null} caso
|
||||||
|
* o handshake seja inválido ou não possa ser processado.
|
||||||
|
*/
|
||||||
|
public static TcpConnection receiveConnection(Socket socket) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
connection = new TcpConnection(socket);
|
||||||
|
|
||||||
|
HandshakeMessage handshake = validateConnection(connection);
|
||||||
|
|
||||||
|
if (handshake == null) return null;
|
||||||
|
|
||||||
|
connection.send(handshake.createResponse().toByteArray());
|
||||||
|
|
||||||
|
connection.setSender(handshake.getSender());
|
||||||
|
connection.setReceiver(handshake.getReceiver());
|
||||||
|
connection.setPrivate(handshake.isPrivate());
|
||||||
|
|
||||||
|
connection.setTimeout(STANDARD_TIMEOUT);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aguarda e valida a mensagem de handshake de uma conexão TCP.
|
||||||
|
*
|
||||||
|
* <p>Durante a validação, a conexão utiliza {@link #HANDSHAKE_TIMEOUT}
|
||||||
|
* como limite para o recebimento do handshake. A mensagem recebida deve
|
||||||
|
* ser uma instância de {@link Message} e, especificamente, de
|
||||||
|
* {@link HandshakeMessage}. Mensagens de sistema ou mensagens de outros
|
||||||
|
* tipos são rejeitadas.</p>
|
||||||
|
*
|
||||||
|
* <p>Quando o handshake é recebido, seus campos de remetente e destinatário
|
||||||
|
* são validados por {@link #validateHandshake(HandshakeMessage, TcpConnection)}.
|
||||||
|
* Caso a validação seja bem-sucedida, o próprio handshake é retornado.</p>
|
||||||
|
*
|
||||||
|
* <p>Em caso de timeout, mensagem inválida ou erro durante o processamento,
|
||||||
|
* uma mensagem de sistema apropriada pode ser enviada ao peer e
|
||||||
|
* {@code null} é retornado.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP da qual o handshake será recebido.
|
||||||
|
* @return o {@link HandshakeMessage} validado ou {@code null} caso o
|
||||||
|
* handshake não seja recebido ou seja inválido.
|
||||||
|
*/
|
||||||
|
private static HandshakeMessage validateConnection(TcpConnection connection) {
|
||||||
|
try {
|
||||||
|
connection.setTimeout(HANDSHAKE_TIMEOUT);
|
||||||
|
byte[] bytes = connection.receive();
|
||||||
|
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis);
|
||||||
|
|
||||||
|
Object object = ois.readObject();
|
||||||
|
|
||||||
|
if (object instanceof Message message) {
|
||||||
|
InfoMessage sysInfo = InfoMessage.parseSystemInfo(bytes);
|
||||||
|
if (sysInfo != null) return null;
|
||||||
|
|
||||||
|
|
||||||
|
if (message instanceof HandshakeMessage handshake) {
|
||||||
|
return (validateHandshake(handshake, connection)) ? handshake : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.CONNECTION_REJECTED,
|
||||||
|
"The message was not from an allowed type."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.CONNECTION_REJECTED,
|
||||||
|
"No handshake was received within the allowed time."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (ClassNotFoundException | IOException ex) {
|
||||||
|
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
|
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.INTERNAL_ERROR,
|
||||||
|
"The server could not process the handshake."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valida os identificadores presentes em uma mensagem de handshake.
|
||||||
|
*
|
||||||
|
* <p>O remetente e o destinatário devem estar presentes e não podem ser
|
||||||
|
* vazios ou conter apenas espaços em branco. Quando um dos identificadores
|
||||||
|
* é inválido, uma mensagem de rejeição é enviada ao peer e a validação
|
||||||
|
* falha.</p>
|
||||||
|
*
|
||||||
|
* @param handshake mensagem de handshake a ser validada.
|
||||||
|
* @param connection conexão associada ao handshake, utilizada para enviar
|
||||||
|
* uma mensagem de rejeição quando necessário.
|
||||||
|
* @return {@code true} se os identificadores do remetente e do destinatário
|
||||||
|
* forem válidos; {@code false} caso contrário.
|
||||||
|
*/
|
||||||
|
private static boolean validateHandshake(HandshakeMessage handshake, TcpConnection connection) {
|
||||||
|
String sender = handshake.getSender();
|
||||||
|
String receiver = handshake.getReceiver();
|
||||||
|
|
||||||
|
if (sender == null || sender.isBlank()) {
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.CONNECTION_REJECTED,
|
||||||
|
"Invalid Sender: " + sender + "."
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (receiver == null || receiver.isBlank()) {
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.CONNECTION_REJECTED,
|
||||||
|
"Invalid Receiver: " + receiver + "."
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
|
||||||
|
class HandshakeMessage extends Message {
|
||||||
|
private final boolean isPrivate;
|
||||||
|
private final String sender;
|
||||||
|
private final String receiver;
|
||||||
|
|
||||||
|
|
||||||
|
public HandshakeMessage(boolean isPrivate, String sender, String receiver) {
|
||||||
|
this.isPrivate = isPrivate;
|
||||||
|
this.sender = sender;
|
||||||
|
this.receiver = receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPrivate() {
|
||||||
|
return isPrivate;
|
||||||
|
}
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
public String getReceiver() {
|
||||||
|
return receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HandshakeMessage createResponse() {
|
||||||
|
return new HandshakeMessage(isPrivate, receiver, sender);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.plugins.PluginManager;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
import pitiupi.models.Messages.InfoMessage;
|
||||||
|
import pitiupi.models.Messages.InfoType;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.net.*;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gerencia a comunicação TCP da aplicação.
|
||||||
|
*
|
||||||
|
* <p>Mantém conexões persistentes com os peers e reutiliza essas conexões
|
||||||
|
* para o envio de mensagens. As mensagens recebidas são encaminhadas aos
|
||||||
|
* plugins, que são responsáveis por interpretá-las.</p>
|
||||||
|
*
|
||||||
|
* <p>Novas conexões são aceitas pelo servidor e cada conexão possui uma
|
||||||
|
* tarefa própria para receber mensagens, permitindo que múltiplas conexões
|
||||||
|
* sejam mantidas simultaneamente.</p>
|
||||||
|
*
|
||||||
|
* <p>As conexões são associadas aos endereços dos peers e podem ser
|
||||||
|
* encerradas quando um peer deixa de estar ativo.</p>
|
||||||
|
*
|
||||||
|
* @author Gustavo
|
||||||
|
*/
|
||||||
|
public class SocketTCP extends Thread {
|
||||||
|
private final Logger logger;
|
||||||
|
|
||||||
|
private final ExecutorService connectionExecutor = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
|
private final ConnectionManager connectionManager;
|
||||||
|
|
||||||
|
private final PluginManager pluginManager;
|
||||||
|
|
||||||
|
private final TcpConnectionManager tcpConnectionManager;
|
||||||
|
|
||||||
|
private ServerSocket serverSocket;
|
||||||
|
private InetAddress address;
|
||||||
|
|
||||||
|
private volatile boolean running = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria o servidor TCP da aplicação.
|
||||||
|
*
|
||||||
|
* <p>O servidor é criado na porta definida pela aplicação. As conexões
|
||||||
|
* com os peers são estabelecidas sob demanda durante o envio ou aceitas
|
||||||
|
* quando iniciadas por outros peers.</p>
|
||||||
|
*
|
||||||
|
* @param connectionManager interface de conexão da aplicação, usada para obter a porta,
|
||||||
|
* o identificador local e os plugins disponíveis.
|
||||||
|
*/
|
||||||
|
public SocketTCP(ConnectionManager connectionManager, PluginManager pluginManager) {
|
||||||
|
this.connectionManager = connectionManager;
|
||||||
|
this.pluginManager = pluginManager;
|
||||||
|
|
||||||
|
logger = Logger.getLogger(getClass().getName());
|
||||||
|
tcpConnectionManager = new TcpConnectionManager();
|
||||||
|
|
||||||
|
try {
|
||||||
|
serverSocket = new ServerSocket(connectionManager.getPort());
|
||||||
|
address = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
|
||||||
|
} catch (IOException ex) {
|
||||||
|
System.out.println("There is no socket connection. Sorry.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem por meio de uma conexão TCP pública com o peer de destino.
|
||||||
|
*
|
||||||
|
* <p>A conexão pública existente para o endereço informado é reutilizada.
|
||||||
|
* Caso não exista uma conexão válida, uma nova conexão é estabelecida antes
|
||||||
|
* do envio. Falhas durante o estabelecimento ou envio são registradas na
|
||||||
|
* saída padrão e não são propagadas ao chamador.</p>
|
||||||
|
*
|
||||||
|
* @param msg mensagem que será enviada.
|
||||||
|
* @param destinationAddress endereço IP do peer que receberá a mensagem.
|
||||||
|
*/
|
||||||
|
public boolean send(Message msg, InetAddress destinationAddress) {
|
||||||
|
try {
|
||||||
|
TcpConnection connection = getPublicConnection(
|
||||||
|
destinationAddress,
|
||||||
|
connectionManager.getIdentifier(),
|
||||||
|
connectionManager.getIdentifier()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (connection == null) {
|
||||||
|
System.out.println("Could not establish TCP connection.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
connection.send(msg.toByteArray());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.out.println("Could not send TCP message.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estabelece uma conexão TCP privada com um plugin específico do peer de destino.
|
||||||
|
*
|
||||||
|
* <p>A conexão é criada como privada e passa a ser gerenciada pelo
|
||||||
|
* {@link TcpConnectionManager}. O método também inicia a tarefa responsável
|
||||||
|
* por receber os dados dessa conexão.</p>
|
||||||
|
*
|
||||||
|
* @param destinationAddress endereço IP do peer de destino.
|
||||||
|
* @param senderId identificador do remetente da conexão.
|
||||||
|
* @param receiverId identificador do plugin que receberá os dados.
|
||||||
|
* @return a conexão privada estabelecida ou {@code null} quando a criação
|
||||||
|
* da conexão falhar.
|
||||||
|
* @throws IllegalArgumentException se o endereço de destino for o endereço
|
||||||
|
* local desta instância.
|
||||||
|
*/
|
||||||
|
public TcpConnection createPrivateConnection(InetAddress destinationAddress, String senderId, String receiverId) {
|
||||||
|
return establishOutgoingConnection(destinationAddress, senderId, receiverId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém uma conexão TCP pública existente com o peer de destino ou estabelece
|
||||||
|
* uma nova caso não exista uma conexão válida.
|
||||||
|
*
|
||||||
|
* <p>As conexões públicas são gerenciadas pelo {@link TcpConnectionManager}.
|
||||||
|
* O método primeiro verifica se já existe uma conexão pública registrada
|
||||||
|
* para o endereço de destino e, caso ela exista e não esteja fechada,
|
||||||
|
* reutiliza-a. Caso contrário, uma nova conexão pública é estabelecida,
|
||||||
|
* registrada no {@link TcpConnectionManager} e disponibilizada para uso.</p>
|
||||||
|
*
|
||||||
|
* <p>O acesso ao método é sincronizado para evitar que múltiplas threads
|
||||||
|
* estabeleçam simultaneamente conexões públicas para o mesmo peer.</p>
|
||||||
|
*
|
||||||
|
* @param destinationAddress endereço IP do peer de destino.
|
||||||
|
* @param senderId identificador usado como remetente no estabelecimento da conexão.
|
||||||
|
* @param receiverId identificador usado como destinatário no estabelecimento da conexão.
|
||||||
|
* @return uma conexão pública válida ou {@code null} caso não seja possível
|
||||||
|
* estabelecê-la.
|
||||||
|
*/
|
||||||
|
private synchronized TcpConnection getPublicConnection(InetAddress destinationAddress, String senderId, String receiverId) {
|
||||||
|
TcpConnection connection;
|
||||||
|
|
||||||
|
connection = tcpConnectionManager.getPublicConnection(destinationAddress);
|
||||||
|
if (connection != null && !connection.isClosed()) return connection;
|
||||||
|
|
||||||
|
connection = establishOutgoingConnection(destinationAddress, senderId, receiverId, false);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aguarda e aceita novas conexões TCP.
|
||||||
|
*
|
||||||
|
* <p>Cada socket aceito é encaminhado para processamento assíncrono,
|
||||||
|
* interpretado como uma {@link TcpConnection}, registrado pelo
|
||||||
|
* {@link TcpConnectionManager} e associado ao receptor adequado.</p>
|
||||||
|
*/
|
||||||
|
private void receive() {
|
||||||
|
while (running) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Socket socket = serverSocket.accept();
|
||||||
|
acceptIncomingConnection(socket);
|
||||||
|
|
||||||
|
} catch (IOException ex) {
|
||||||
|
if (!running) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Error accepting TCP connection.");
|
||||||
|
System.out.println(ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estabelece uma conexão TCP de saída com outro peer.
|
||||||
|
*
|
||||||
|
* <p>O método impede conexões com o próprio endereço local, cria a conexão
|
||||||
|
* por meio da {@link ConnectionFactory}, registra-a no gerenciador de
|
||||||
|
* conexões e inicia uma tarefa para receber dados continuamente.</p>
|
||||||
|
*
|
||||||
|
* @param destinationAddress endereço IP do peer de destino.
|
||||||
|
* @param sender identificador do remetente.
|
||||||
|
* @param receiver identificador do destinatário.
|
||||||
|
* @param isPrivate {@code true} para uma conexão destinada a um plugin
|
||||||
|
* específico; {@code false} para uma conexão pública.
|
||||||
|
* @return a conexão estabelecida ou {@code null} se a
|
||||||
|
* {@link ConnectionFactory} não conseguir criá-la.
|
||||||
|
* @throws IllegalArgumentException se o destino for o endereço desta máquina.
|
||||||
|
*/
|
||||||
|
private TcpConnection establishOutgoingConnection(InetAddress destinationAddress, String sender, String receiver, boolean isPrivate) {
|
||||||
|
if (address.equals(destinationAddress)) {
|
||||||
|
System.out.println("Failed to get socket.");
|
||||||
|
throw new IllegalArgumentException("Connections to the local host are forbidden.");
|
||||||
|
}
|
||||||
|
|
||||||
|
TcpConnection connection = ConnectionFactory.createConnection(destinationAddress, connectionManager.getPort(), sender, receiver, isPrivate);
|
||||||
|
if (connection == null) return null;
|
||||||
|
|
||||||
|
saveConnection(connection);
|
||||||
|
|
||||||
|
connectionExecutor.submit(() -> {
|
||||||
|
startReceiver(connection);
|
||||||
|
});
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agenda o processamento de uma conexão TCP recebida.
|
||||||
|
*
|
||||||
|
* <p>A conexão é interpretada pela {@link ConnectionFactory}, registrada
|
||||||
|
* no gerenciador e associada a uma tarefa de recepção. O processamento é
|
||||||
|
* executado de forma assíncrona pelo executor compartilhado.</p>
|
||||||
|
*
|
||||||
|
* @param socket socket aceito pelo {@link ServerSocket}.
|
||||||
|
*/
|
||||||
|
private void acceptIncomingConnection(Socket socket) {
|
||||||
|
connectionExecutor.submit(() -> {
|
||||||
|
TcpConnection connection = ConnectionFactory.receiveConnection(socket);
|
||||||
|
if (connection == null) return;
|
||||||
|
|
||||||
|
saveConnection(connection);
|
||||||
|
startReceiver(connection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão no gerenciador de acordo com seu tipo.
|
||||||
|
*
|
||||||
|
* <p>Conexões privadas são armazenadas na coleção de conexões privadas;
|
||||||
|
* as demais são armazenadas na coleção de conexões públicas.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão que será registrada.
|
||||||
|
*/
|
||||||
|
private void saveConnection(TcpConnection connection) {
|
||||||
|
if (connection.isPrivate()) {
|
||||||
|
tcpConnectionManager.addPrivateConnection(connection);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
tcpConnectionManager.addPublicConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seleciona e inicia o receptor adequado para uma conexão.
|
||||||
|
*
|
||||||
|
* <p>Conexões públicas são tratadas pelo receptor de mensagens públicas.
|
||||||
|
* Conexões privadas destinadas ao próprio sistema são tratadas
|
||||||
|
* separadamente; as demais são encaminhadas ao plugin identificado como
|
||||||
|
* destinatário. Quando solicitado, o plugin também é notificado sobre o
|
||||||
|
* estabelecimento da conexão.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão cujo fluxo de entrada será processado.
|
||||||
|
*/
|
||||||
|
private void startReceiver(TcpConnection connection) {
|
||||||
|
|
||||||
|
if (!connection.isPrivate()) {
|
||||||
|
publicConnectionReceiver(connection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connection.getReceiver().equals(connectionManager.getIdentifier())) {
|
||||||
|
systemConnectionReceiver(connection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pluginManager.handleConnection(connection, connection.getReceiver())) {
|
||||||
|
privateConnectionReceiver(connection);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
InfoMessage.sendSystemInfo(
|
||||||
|
connection,
|
||||||
|
InfoType.RECEIVER_NOT_FOUND,
|
||||||
|
"This peer does not have the plugin: " + connection.getReceiver()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa continuamente as mensagens recebidas em uma conexão pública.
|
||||||
|
*
|
||||||
|
* <p>As mensagens são desserializadas e, quando são instâncias de
|
||||||
|
* {@link Message}, encaminhadas a todos os plugins da aplicação. Mensagens
|
||||||
|
* de controle do sistema podem encerrar a conexão ou registrar uma
|
||||||
|
* condição de erro.</p>
|
||||||
|
*
|
||||||
|
* <p>O método também trata timeouts e erros de I/O, removendo a conexão
|
||||||
|
* do {@link TcpConnectionManager} quando ela deixa de ser utilizável.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão pública da qual as mensagens serão recebidas.
|
||||||
|
*/
|
||||||
|
private void publicConnectionReceiver(TcpConnection connection) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] bytes = connection.receive();
|
||||||
|
|
||||||
|
InfoMessage sysMessage = InfoMessage.parseSystemInfo(bytes);
|
||||||
|
|
||||||
|
if (sysMessage == null) {
|
||||||
|
pluginManager.handleMessage(bytes);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (sysMessage.getType()) {
|
||||||
|
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
|
||||||
|
tcpConnectionManager.closeConnection(connection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case MESSAGE_REJECTED -> {
|
||||||
|
logger.log(Level.SEVERE, "Somehow sent something that was not an Message");
|
||||||
|
}
|
||||||
|
default -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
if (connection.hasTimedOut()) {
|
||||||
|
tcpConnectionManager.closeConnection(connection, "Connection timeout");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
tcpConnectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa os dados recebidos em uma conexão privada e os encaminha
|
||||||
|
* ao plugin destinatário.
|
||||||
|
*
|
||||||
|
* <p>Dados que não representam mensagens de controle são entregues
|
||||||
|
* diretamente ao {@link pitiupi.models.Plugin}. Mensagens de controle
|
||||||
|
* relacionadas ao encerramento ou a erros internos provocam a notificação
|
||||||
|
* do plugin e o fechamento da conexão.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão privada da qual os dados serão recebidos.
|
||||||
|
*/
|
||||||
|
private void privateConnectionReceiver(TcpConnection connection) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] message = connection.receive();
|
||||||
|
InfoMessage sysMessage = InfoMessage.parseSystemInfo(message);
|
||||||
|
|
||||||
|
if (sysMessage == null) {
|
||||||
|
pluginManager.handleMessageFromConnection(connection, message);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (sysMessage.getType()) {
|
||||||
|
case CONNECTION_CLOSED, INTERNAL_ERROR -> {
|
||||||
|
pluginManager.handleDisconnection(connection, connection.getReceiver());
|
||||||
|
tcpConnectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
if (connection.hasTimedOut()) {
|
||||||
|
tcpConnectionManager.closeConnection(connection, "Connection timeout");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
tcpConnectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa mensagens recebidas em uma conexão destinada ao próprio sistema.
|
||||||
|
*
|
||||||
|
* <p>Atualmente, mensagens destinadas ao sistema são apenas verificadas
|
||||||
|
* quanto ao seu formato de controle. Não há processamento adicional de
|
||||||
|
* mensagens de sistema neste método.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão destinada ao identificador da própria aplicação.
|
||||||
|
*/
|
||||||
|
private void systemConnectionReceiver(TcpConnection connection) {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
byte[] message = connection.receive();
|
||||||
|
try (ByteArrayInputStream bis = new ByteArrayInputStream(message);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||||
|
|
||||||
|
InfoMessage sysMessage = InfoMessage.parseSystemInfo(message);
|
||||||
|
if (sysMessage != null) continue;
|
||||||
|
|
||||||
|
//TODO: Ainda não existem mensagens trocadas entre o sistema.
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (SocketTimeoutException ex) {
|
||||||
|
if (connection.hasTimedOut()) return;
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
tcpConnectionManager.closeConnection(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encerra uma conexão TCP e registra o motivo informado.
|
||||||
|
*
|
||||||
|
* <p>Quando nenhuma descrição é fornecida, é utilizado um motivo padrão.
|
||||||
|
* O fechamento efetivo da conexão é delegado ao {@link TcpConnectionManager}.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão que será encerrada.
|
||||||
|
* @param description motivo do encerramento; pode ser {@code null}.
|
||||||
|
*/
|
||||||
|
public void disconnect(TcpConnection connection, String description) {
|
||||||
|
tcpConnectionManager.closeConnection(
|
||||||
|
connection,
|
||||||
|
Objects.requireNonNullElse(description, "No reason provided")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
receive();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encerra o servidor TCP e libera os recursos associados.
|
||||||
|
*
|
||||||
|
* <p>Interrompe o laço de aceitação de conexões, fecha o
|
||||||
|
* {@link ServerSocket}, encerra todas as conexões gerenciadas e interrompe
|
||||||
|
* as tarefas do executor.</p>
|
||||||
|
*
|
||||||
|
* <p>Após a chamada, esta instância não deve ser reutilizada para aceitar
|
||||||
|
* novas conexões.</p>
|
||||||
|
*/
|
||||||
|
public void close() {
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
if (serverSocket != null) {
|
||||||
|
try {
|
||||||
|
serverSocket.close();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, null, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpConnectionManager.closeAllConnections("The peer must have closed the application or changed ports");
|
||||||
|
|
||||||
|
connectionExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Representa uma conexão TCP ativa com um peer remoto.
|
||||||
|
*
|
||||||
|
* <p>A conexão permite o envio e recebimento de mensagens, além de manter
|
||||||
|
* informações sobre o endereço remoto e metadados da conexão, como remetente,
|
||||||
|
* destinatário e se a conexão é privada.</p>
|
||||||
|
*
|
||||||
|
* @author Gustavo
|
||||||
|
*/
|
||||||
|
public class TcpConnection {
|
||||||
|
|
||||||
|
private final Socket socket;
|
||||||
|
private final DataInputStream input;
|
||||||
|
private final DataOutputStream output;
|
||||||
|
private final InetAddress address;
|
||||||
|
private String sender;
|
||||||
|
private String receiver;
|
||||||
|
private boolean isPrivate;
|
||||||
|
private volatile long lastActivity;
|
||||||
|
private long timeout;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria uma conexão TCP a partir de um socket existente.
|
||||||
|
*
|
||||||
|
* @param socket socket utilizado para a comunicação
|
||||||
|
* @throws IOException se não for possível obter os fluxos de entrada ou saída
|
||||||
|
* do socket
|
||||||
|
*/
|
||||||
|
TcpConnection(Socket socket) throws IOException {
|
||||||
|
this.socket = socket;
|
||||||
|
this.input = new DataInputStream(socket.getInputStream());
|
||||||
|
this.output = new DataOutputStream(socket.getOutputStream());
|
||||||
|
this.address = socket.getInetAddress();
|
||||||
|
this.lastActivity = System.currentTimeMillis();
|
||||||
|
this.timeout = 300_000; // 5 minutos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem pela conexão.
|
||||||
|
*
|
||||||
|
* <p>A mensagem é enviada precedida pelo seu tamanho, permitindo que o
|
||||||
|
* receptor determine quantos bytes devem ser lidos.</p>
|
||||||
|
*
|
||||||
|
* @param message mensagem a ser enviada
|
||||||
|
* @throws IOException se ocorrer um erro durante o envio
|
||||||
|
*/
|
||||||
|
public synchronized void send(byte[] message) throws IOException {
|
||||||
|
output.writeInt(message.length);
|
||||||
|
output.write(message);
|
||||||
|
output.flush();
|
||||||
|
updateLastActivity();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recebe uma mensagem da conexão.
|
||||||
|
*
|
||||||
|
* <p>Primeiro lê o tamanho da mensagem e, em seguida, lê aquantidade
|
||||||
|
* correspondente de bytes.</p>
|
||||||
|
*
|
||||||
|
* @return mensagem recebida
|
||||||
|
* @throws IOException se o tamanho da mensagem for inválido ou se a conexão
|
||||||
|
* for encerrada antes que a mensagem seja completamente recebida
|
||||||
|
*/
|
||||||
|
byte[] receive() throws IOException {
|
||||||
|
int length = input.readInt();
|
||||||
|
|
||||||
|
if (length < 0) throw new IOException("Invalid message length.");
|
||||||
|
|
||||||
|
byte[] message = input.readNBytes(length);
|
||||||
|
|
||||||
|
|
||||||
|
if (message.length != length) {
|
||||||
|
throw new IOException("Connection closed before receiving the complete message.");
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLastActivity();
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se o socket da conexão está fechado.
|
||||||
|
*
|
||||||
|
* @return {@code true} se o socket estiver fechado;
|
||||||
|
* {@code false} caso contrário
|
||||||
|
*/
|
||||||
|
public boolean isClosed() {
|
||||||
|
return socket.isClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha o socket da conexão.
|
||||||
|
*
|
||||||
|
* @throws IOException se ocorrer um erro ao fechar o socket
|
||||||
|
*/
|
||||||
|
void close() throws IOException {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retorna o endereço do peer remoto conectado.
|
||||||
|
*
|
||||||
|
* @return endereço IP do peer remoto
|
||||||
|
*/
|
||||||
|
public InetAddress getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza o instante da última atividade da conexão.
|
||||||
|
*/
|
||||||
|
private void updateLastActivity() {
|
||||||
|
lastActivity = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define o tempo limite de leitura do socket.
|
||||||
|
*
|
||||||
|
* @param timeout tempo limite, em milissegundos
|
||||||
|
* @throws SocketException se ocorrer um erro ao definir o tempo limite
|
||||||
|
*/
|
||||||
|
void setTimeout(int timeout) throws SocketException {
|
||||||
|
socket.setSoTimeout(timeout);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se a conexão ficou inativa pelo tempo limite configurado.
|
||||||
|
*
|
||||||
|
* <p>A verificação é baseada no instante da última atividade registrada
|
||||||
|
* durante o envio ou recebimento de uma mensagem.</p>
|
||||||
|
*
|
||||||
|
* @return {@code true} se a conexão estiver inativa há pelo menos 5 minutos;
|
||||||
|
* {@code false} caso contrário
|
||||||
|
*/
|
||||||
|
boolean hasTimedOut() {
|
||||||
|
return System.currentTimeMillis() - lastActivity >= timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getReceiver() {
|
||||||
|
return receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPrivate() {
|
||||||
|
return isPrivate;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setSender(String sender) {
|
||||||
|
this.sender = sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setReceiver(String receiver) {
|
||||||
|
this.receiver = receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setPrivate(boolean aPrivate) {
|
||||||
|
isPrivate = aPrivate;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package pitiupi.net.tcp;
|
||||||
|
|
||||||
|
import pitiupi.models.Messages.InfoType;
|
||||||
|
import pitiupi.models.User;
|
||||||
|
import pitiupi.control.PeerListener;
|
||||||
|
import pitiupi.models.Messages.InfoMessage;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gerencia as conexões TCP estabelecidas com os peers da aplicação.
|
||||||
|
*
|
||||||
|
* <p>As conexões públicas são armazenadas individualmente por endereço IP,
|
||||||
|
* enquanto as conexões privadas são agrupadas por endereço, permitindo que
|
||||||
|
* um mesmo peer mantenha múltiplas conexões privadas simultaneamente.</p>
|
||||||
|
*
|
||||||
|
* <p>Além de manter o registro das conexões ativas, esta classe é responsável
|
||||||
|
* por encerrá-las quando necessário e por remover do gerenciamento as
|
||||||
|
* conexões que forem fechadas. Também acompanha as alterações na lista de
|
||||||
|
* peers ativos para encerrar conexões associadas a peers que deixaram de
|
||||||
|
* estar disponíveis.</p>
|
||||||
|
*/
|
||||||
|
class TcpConnectionManager implements PeerListener {
|
||||||
|
private final Logger logger;
|
||||||
|
private final Map<InetAddress, TcpConnection> publicConnections;
|
||||||
|
private final Map<InetAddress, List<TcpConnection>> privateConnections;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria um gerenciador de conexões TCP vazio.
|
||||||
|
*/
|
||||||
|
public TcpConnectionManager() {
|
||||||
|
publicConnections = new ConcurrentHashMap<>();
|
||||||
|
privateConnections = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
logger = Logger.getLogger(getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém a conexão pública registrada para um determinado peer.
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer.
|
||||||
|
* @return a conexão pública registrada para o endereço ou {@code null}
|
||||||
|
* caso não exista uma conexão pública registrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public TcpConnection getPublicConnection(InetAddress address) {
|
||||||
|
return publicConnections.get(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão privada associada a um peer.
|
||||||
|
*
|
||||||
|
* <p>Um mesmo peer pode possuir múltiplas conexões privadas. Por isso,
|
||||||
|
* as conexões são armazenadas em uma lista associada ao endereço do
|
||||||
|
* peer.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão privada a ser registrada.
|
||||||
|
*/
|
||||||
|
public void addPrivateConnection(TcpConnection connection) {
|
||||||
|
List<TcpConnection> connections =
|
||||||
|
privateConnections.computeIfAbsent(connection.getAddress(), e -> new ArrayList<>());
|
||||||
|
|
||||||
|
synchronized (connections) {
|
||||||
|
connections.add(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra uma conexão pública associada a um peer.
|
||||||
|
*
|
||||||
|
* <p>Cada peer pode possuir apenas uma conexão pública registrada.
|
||||||
|
* Quando já existe uma conexão pública para o endereço da nova conexão,
|
||||||
|
* a conexão anterior é encerrada e substituída pela nova.</p>
|
||||||
|
*
|
||||||
|
* @param connection nova conexão pública a ser registrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void addPublicConnection(TcpConnection connection) {
|
||||||
|
TcpConnection oldConnection = publicConnections.put(connection.getAddress(), connection);
|
||||||
|
if (oldConnection != null && oldConnection != connection) {
|
||||||
|
closeConnection(oldConnection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento ao peer e fecha a conexão.
|
||||||
|
*
|
||||||
|
* <p>A mensagem enviada informa o motivo do encerramento antes que a
|
||||||
|
* conexão seja removida do gerenciamento e fechada.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP a ser encerrada.
|
||||||
|
* @param reason motivo do encerramento que será informado ao peer.
|
||||||
|
*/
|
||||||
|
public void closeConnection(TcpConnection connection, String reason) {
|
||||||
|
InfoMessage.sendSystemInfo(connection, InfoType.CONNECTION_CLOSED, reason);
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove uma conexão do gerenciamento e encerra seu socket.
|
||||||
|
*
|
||||||
|
* <p>Para conexões privadas, a conexão é removida da lista associada ao
|
||||||
|
* endereço do peer. Caso essa seja a última conexão privada do endereço,
|
||||||
|
* a lista também é removida do mapa.</p>
|
||||||
|
*
|
||||||
|
* <p>Para conexões públicas, a conexão é removida do mapa somente se
|
||||||
|
* ainda for a conexão registrada para seu endereço.</p>
|
||||||
|
*
|
||||||
|
* <p>Se a conexão já estiver fechada ou for {@code null}, nenhuma ação
|
||||||
|
* adicional de fechamento é realizada.</p>
|
||||||
|
*
|
||||||
|
* @param connection conexão TCP a ser removida e encerrada.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void closeConnection(TcpConnection connection) {
|
||||||
|
if (connection == null) return;
|
||||||
|
if (connection.isPrivate()) {
|
||||||
|
List<TcpConnection> connections = privateConnections.get(connection.getAddress());
|
||||||
|
|
||||||
|
if (connections != null) {
|
||||||
|
synchronized (connections) {
|
||||||
|
connections.remove(connection);
|
||||||
|
|
||||||
|
if (connections.isEmpty()) privateConnections.remove(connection.getAddress(), connections);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else publicConnections.remove(connection.getAddress(), connection);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!connection.isClosed()) {
|
||||||
|
connection.close();
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento para todas as conexões de um peer
|
||||||
|
* e, em seguida, fecha essas conexões.
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer cujas conexões serão encerradas.
|
||||||
|
* @param reason motivo do encerramento informado ao peer.
|
||||||
|
*/
|
||||||
|
public void closeByAdress(InetAddress address, String reason) {
|
||||||
|
List<TcpConnection> connections = privateConnections.get(address);
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
InfoMessage.sendSystemInfo(connection, InfoType.CONNECTION_CLOSED, reason);
|
||||||
|
}
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha e remove todas as conexões associadas a um determinado endereço.
|
||||||
|
*
|
||||||
|
* <p>Tanto a conexão pública quanto todas as conexões privadas associadas
|
||||||
|
* ao endereço são encerradas e removidas do gerenciamento.</p>
|
||||||
|
*
|
||||||
|
* @param address endereço IP do peer cujas conexões serão encerradas.
|
||||||
|
*/
|
||||||
|
public void closeByAdress(InetAddress address) {
|
||||||
|
TcpConnection publicConnection = publicConnections.remove(address);
|
||||||
|
|
||||||
|
if (publicConnection != null) {
|
||||||
|
try {
|
||||||
|
publicConnection.close();
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
List<TcpConnection> connections = privateConnections.remove(address);
|
||||||
|
|
||||||
|
if (connections != null) {
|
||||||
|
synchronized (connections) {
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
try {
|
||||||
|
connection.close();
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
|
logger.log(Level.SEVERE, "Error closing TCP connection", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connections.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia uma mensagem de encerramento para todas as conexões privadas
|
||||||
|
* gerenciadas e, em seguida, fecha todas elas.
|
||||||
|
*
|
||||||
|
* @param reason motivo do encerramento informado aos peers.
|
||||||
|
*/
|
||||||
|
public void closeAllConnections(String reason) {
|
||||||
|
for (List<TcpConnection> connections : privateConnections.values()) {
|
||||||
|
for (TcpConnection connection : connections) {
|
||||||
|
InfoMessage.sendSystemInfo(connection, InfoType.CONNECTION_CLOSED, reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closeAllConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha e remove todas as conexões públicas e privadas gerenciadas.
|
||||||
|
*
|
||||||
|
* <p>Após a execução, não devem permanecer conexões registradas nos
|
||||||
|
* mapas de conexões deste gerenciador.</p>
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void closeAllConnections() {
|
||||||
|
for (TcpConnection connection : publicConnections.values()) {
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (privateConnections) {
|
||||||
|
for (List<TcpConnection> connectionsList : privateConnections.values()) {
|
||||||
|
for (TcpConnection connection : connectionsList) {
|
||||||
|
closeConnection(connection);
|
||||||
|
}
|
||||||
|
privateConnections.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza as conexões de acordo com os peers atualmente ativos.
|
||||||
|
*
|
||||||
|
* <p>Os endereços presentes na lista de peers são utilizados como
|
||||||
|
* referência para determinar quais conexões ainda devem permanecer
|
||||||
|
* ativas. Conexões públicas e privadas associadas a endereços que não
|
||||||
|
* estão mais presentes na lista de peers são encerradas e removidas.</p>
|
||||||
|
*
|
||||||
|
* @param peers lista atualizada de peers ativos.
|
||||||
|
*/
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onPeersChanged(List<User> peers) {
|
||||||
|
Set<InetAddress> activePeers = peers.stream().map(User::getAddress).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
for (InetAddress address : publicConnections.keySet()) {
|
||||||
|
if (!activePeers.contains(address)) {
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (InetAddress address : privateConnections.keySet()) {
|
||||||
|
if (!activePeers.contains(address)) {
|
||||||
|
closeByAdress(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
-25
@@ -3,9 +3,8 @@
|
|||||||
* To change this template file, choose Tools | Templates
|
* To change this template file, choose Tools | Templates
|
||||||
* and open the template in the editor.
|
* and open the template in the editor.
|
||||||
*/
|
*/
|
||||||
package pitiupi.net;
|
package pitiupi.net.udp;
|
||||||
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.ObjectInput;
|
import java.io.ObjectInput;
|
||||||
@@ -13,7 +12,11 @@ import java.io.ObjectInputStream;
|
|||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
import pitiupi.plugin.Plugin;
|
|
||||||
|
import pitiupi.control.ConnectionManager;
|
||||||
|
import pitiupi.control.plugins.PluginManager;
|
||||||
|
import pitiupi.models.Messages.HeartbeatMessage;
|
||||||
|
import pitiupi.models.Messages.Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gerencia a comunicação UDP multicast e unicast da aplicação.
|
* Gerencia a comunicação UDP multicast e unicast da aplicação.
|
||||||
@@ -34,7 +37,10 @@ public class SocketUDP extends Thread {
|
|||||||
private MulticastSocket multicastSocket;
|
private MulticastSocket multicastSocket;
|
||||||
|
|
||||||
private InetAddress address;
|
private InetAddress address;
|
||||||
private MainWindow main;
|
|
||||||
|
private final ConnectionManager connectionManager;
|
||||||
|
private final PluginManager pluginManager;
|
||||||
|
|
||||||
private volatile boolean running = true;
|
private volatile boolean running = true;
|
||||||
public final static String INET_ADDR = "224.0.0.3";
|
public final static String INET_ADDR = "224.0.0.3";
|
||||||
|
|
||||||
@@ -44,22 +50,26 @@ public class SocketUDP extends Thread {
|
|||||||
* <p>O socket é associado à porta da aplicação e ingressa no grupo
|
* <p>O socket é associado à porta da aplicação e ingressa no grupo
|
||||||
* multicast configurado.</p>
|
* multicast configurado.</p>
|
||||||
*
|
*
|
||||||
* @param main janela principal da aplicação.
|
* @param connectionManager interface que gerencia toda conexão da aplicação.
|
||||||
|
* @param pluginManager interface que gerencia os plugins da conexão.
|
||||||
*/
|
*/
|
||||||
public SocketUDP(MainWindow main) {
|
public SocketUDP(ConnectionManager connectionManager, PluginManager pluginManager) {
|
||||||
this.main = main;
|
this.connectionManager = connectionManager;
|
||||||
|
this.pluginManager = pluginManager;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.address = InetAddress.getByName(SocketUDP.INET_ADDR);
|
this.address = InetAddress.getByName(SocketUDP.INET_ADDR);
|
||||||
} catch (UnknownHostException ex) {
|
|
||||||
System.getLogger(SocketUDP.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
|
multicastSocket = new MulticastSocket(connectionManager.getPort());
|
||||||
}
|
|
||||||
try {
|
|
||||||
multicastSocket = new MulticastSocket(this.main.getPort());
|
|
||||||
multicastSocket.setSendBufferSize(256000);
|
multicastSocket.setSendBufferSize(256000);
|
||||||
multicastSocket.setReceiveBufferSize(256000);
|
multicastSocket.setReceiveBufferSize(256000);
|
||||||
multicastSocket.setReuseAddress(true);
|
multicastSocket.setReuseAddress(true);
|
||||||
multicastSocket.joinGroup(address);
|
multicastSocket.joinGroup(address);
|
||||||
} catch (IOException ex) {
|
}
|
||||||
|
catch (UnknownHostException ex) {
|
||||||
|
System.getLogger(SocketUDP.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
|
||||||
|
}
|
||||||
|
catch (IOException ex) {
|
||||||
System.out.println("There is no socket connection. Sorry.");
|
System.out.println("There is no socket connection. Sorry.");
|
||||||
System.out.println(ex);
|
System.out.println(ex);
|
||||||
}
|
}
|
||||||
@@ -68,22 +78,22 @@ public class SocketUDP extends Thread {
|
|||||||
/**
|
/**
|
||||||
* Envia uma mensagem para o grupo multicast da aplicação.
|
* Envia uma mensagem para o grupo multicast da aplicação.
|
||||||
*
|
*
|
||||||
* @param msg mensagem serializada a ser enviada.
|
* @param msg mensagem a ser enviada.
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
* @throws IOException caso ocorra um erro durante o envio.
|
||||||
*/
|
*/
|
||||||
public void sendMulticast(byte[] msg) throws IOException {
|
public void sendMulticast(Message msg) throws IOException {
|
||||||
send(msg, this.address);
|
send(msg.toByteArray(), this.address);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia uma mensagem diretamente para um peer utilizando UDP.
|
* Envia uma mensagem diretamente para um peer utilizando UDP.
|
||||||
*
|
*
|
||||||
* @param msg mensagem serializada a ser enviada.
|
* @param msg mensagem a ser enviada.
|
||||||
* @param destinationAddress endereço IP do peer destinatário.
|
* @param destinationAddress endereço IP do peer destinatário.
|
||||||
* @throws IOException caso ocorra um erro durante o envio.
|
* @throws IOException caso ocorra um erro durante o envio.
|
||||||
*/
|
*/
|
||||||
public void sendUnicast(byte[] msg, InetAddress destinationAddress) throws IOException {
|
public void sendUnicast(Message msg, InetAddress destinationAddress) throws IOException {
|
||||||
send(msg, destinationAddress);
|
send(msg.toByteArray(), destinationAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -95,7 +105,7 @@ public class SocketUDP extends Thread {
|
|||||||
*/
|
*/
|
||||||
private void send(byte[] msg, InetAddress destinationAddress) throws IOException {
|
private void send(byte[] msg, InetAddress destinationAddress) throws IOException {
|
||||||
DatagramPacket msgPacket;
|
DatagramPacket msgPacket;
|
||||||
msgPacket = new DatagramPacket(msg, msg.length, destinationAddress, this.main.getPort());
|
msgPacket = new DatagramPacket(msg, msg.length, destinationAddress, connectionManager.getPort());
|
||||||
multicastSocket.send(msgPacket);
|
multicastSocket.send(msgPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,15 +150,14 @@ public class SocketUDP extends Thread {
|
|||||||
}
|
}
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
|
|
||||||
HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData());
|
HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData());
|
||||||
if (heartbeat != null) {
|
if (heartbeat != null) {
|
||||||
main.getHeartbeatManager().receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (Plugin plugin : main.getPlugins()) {
|
|
||||||
System.out.println(msgPacket.getAddress().toString());
|
pluginManager.handleMessage(msgPacket.getData());
|
||||||
plugin.receiveMessage(msgPacket.getData());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
/*
|
|
||||||
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
|
||||||
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
|
|
||||||
*/
|
|
||||||
package pitiupi.plugin;
|
|
||||||
|
|
||||||
import javax.swing.JMenu;
|
|
||||||
import pitiupi.GUI.MainWindow;
|
|
||||||
import pitiupi.net.Message;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Interface base para plugins da aplicação.
|
|
||||||
*
|
|
||||||
* <p>Cada plugin deve implementar esta interface para ser carregado
|
|
||||||
* pela aplicação e participar do sistema de comunicação por mensagens.</p>
|
|
||||||
*
|
|
||||||
* @author flavio
|
|
||||||
*/
|
|
||||||
public interface Plugin {
|
|
||||||
|
|
||||||
public String getName();
|
|
||||||
public String getAuthor();
|
|
||||||
public String getVersion();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicializa o plugin.
|
|
||||||
*
|
|
||||||
* <p>Este método é chamado pela aplicação após o carregamento do plugin.</p>
|
|
||||||
*
|
|
||||||
* @param window janela principal da aplicação.
|
|
||||||
*/
|
|
||||||
public void createPlugin(MainWindow window);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retorna uma mensagem utilizada pelo plugin.
|
|
||||||
*
|
|
||||||
* @return mensagem criada pelo plugin.
|
|
||||||
*/
|
|
||||||
public Message getMessage();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recebe uma mensagem enviada pela aplicação.
|
|
||||||
*
|
|
||||||
* <p>A mensagem é recebida em formato serializado. O plugin deve verificar
|
|
||||||
* se a mensagem pertence ao seu tipo e realizar o processamento necessário.</p>
|
|
||||||
*
|
|
||||||
* @param message mensagem serializada recebida.
|
|
||||||
*/
|
|
||||||
public void receiveMessage(byte[] message);
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user