Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb3731232b | ||
|
|
fa85b6ee0c | ||
|
|
74153bcdf3 | ||
|
|
70db48e645 | ||
|
|
81c37225fa | ||
|
|
5c69189293 | ||
|
|
543073e84e | ||
|
|
7f21e89a0a | ||
|
|
239a10e79f | ||
|
|
a7ba307daf | ||
|
|
668b2d417b | ||
|
|
5e835f4d75 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
/pitiupi/build/
|
||||
/pitiupi/dist/
|
||||
/pitiupi.chat/build/
|
||||
/pitiupi.chat/dist/
|
||||
/pitiupi.chat/nbproject/private/
|
||||
/pitiupi.screenCast/build/
|
||||
/pitiupi.screenCast/dist/
|
||||
Generated
+14
-36
@@ -4,29 +4,7 @@
|
||||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="">
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/Documentation.md" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/PluginTutorial.md" 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/dist/pitiupi.chat.jar" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi.chat/dist/pitiupi.chat.jar" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi.screenCast/build/built-jar.properties" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi.screenCast/build/built-jar.properties" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi.screenCast/dist/pitiupi.screenCast.jar" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi.screenCast/dist/pitiupi.screenCast.jar" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/.netbeans_automatic_build" beforeDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/.netbeans_update_resources" beforeDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/Login.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/Login.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/MainWindow.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/MainWindow.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/MenuBar.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/GUI/MenuBar.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/Main$1.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/Main$1.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/Main.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/Main.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/control/PluginLoader.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/control/PluginLoader.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/net/Socket.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/net/Socket.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/plugin/Plugin.class" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/build/classes/pitiupi/plugin/Plugin.class" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/dist/README.TXT" beforeDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/dist/pitiupi.jar" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/dist/pitiupi.jar" 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/MenuBar.java" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/GUI/MenuBar.java" afterDir="false" />
|
||||
</list>
|
||||
<list default="true" id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="" />
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
@@ -43,20 +21,20 @@
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"Application.Main.executor": "Run",
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"git-widget-placeholder": "feature/help-and-documentation",
|
||||
"ignore.virus.scanning.warn.message": "true",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi",
|
||||
"settings.editor.selected.configurable": "preferences.keymap"
|
||||
<component name="PropertiesComponent">{
|
||||
"keyToString": {
|
||||
"Application.Main.executor": "Run",
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"git-widget-placeholder": "feature/help-and-documentation",
|
||||
"ignore.virus.scanning.warn.message": "true",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi",
|
||||
"settings.editor.selected.configurable": "preferences.keymap"
|
||||
}
|
||||
}]]></component>
|
||||
}</component>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi\plugins" />
|
||||
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
# Como criar um plugin para o pitiupi ?
|
||||
|
||||
O objetivo aqui, além de criar plugins para esse sistema, é entender **por que cada parte existe**. Isso é importante porque a ideia de **carregar código externo em tempo de execução** aparece em várias ferramentas nas áreas da computação.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 1. Visão rápida
|
||||
|
||||
O repositório contém projetos Java **independentes**:
|
||||
|
||||
| Projeto | O que é |
|
||||
|---|---|
|
||||
| `pitiupi` | A ferramenta principal : P2P, janela, rede, e o "motor" que carrega plugins |
|
||||
| `pitiupi.chat` | Um plugin que adiciona um chat |
|
||||
| `pitiupi.screenCast` | Outro plugin que adiciona compartilhamento de tela |
|
||||
|
||||
Cada plugin é compilado separadamente com `ant` e o `.jar` gerado é colocado (ou linkado) dentro da pasta `pitiupi/plugins`.
|
||||
|
||||
Quando o pitiupi principal inicia, ele varre essa pasta e **carrega dinamicamente** cada plugin encontrado, sem que o código principal precise conhecer o plugin em tempo de compilação.
|
||||
|
||||
|
||||
Isso é possível graças a três partes que trabalham juntas:
|
||||
|
||||
1. A **interface `Plugin`** : o contrato que todo plugin deve cumprir.
|
||||
2. O **`PluginLoader`** : a classe do pitiupi que varre a pasta `plugins/` e carrega os `.jar`.
|
||||
3. O **arquivo de registro do `ServiceLoader`** : um arquivo de texto dentro do `.jar` que diz "esta classe aqui implementa `Plugin`".
|
||||
|
||||
---
|
||||
|
||||
## 2. O contrato: a interface `Plugin`
|
||||
|
||||
Todo plugin **precisa** implementar esta interface (`pitiupi/src/pitiupi/plugin/Plugin.java`):
|
||||
|
||||
```java
|
||||
public interface Plugin {
|
||||
public String getName();
|
||||
public String getAuthor();
|
||||
public String getVersion();
|
||||
public void createPlugin(MainWindow window);
|
||||
public Message getMessage();
|
||||
public void receiveMessage(byte[] message);
|
||||
}
|
||||
```
|
||||
|
||||
O que cada método faz:
|
||||
|
||||
- **`getName()` / `getAuthor()` / `getVersion()`** : indentificação de dados básicos.
|
||||
- **`createPlugin(MainWindow window)`** : É aqui que o plugin cria sua interface gráfica, adiciona itens de menu na janela principal, etc.
|
||||
- **`getMessage()`** : Serve como modelo para a camada de rede saber que tipo de mensagem esse plugin envia.
|
||||
- **`receiveMessage(byte[] message)`** : recebe as mensagens que chegam pela rede e permite que o plugin interprete esses dados.
|
||||
|
||||
---
|
||||
|
||||
## 3. Como o pitiupi encontra e carrega os plugins
|
||||
|
||||
A classe `PluginLoader` (`pitiupi/src/pitiupi/control/PluginLoader.java`) faz o seguinte:
|
||||
|
||||
1. Olha dentro da pasta `plugins/` e lista todos os arquivos `.jar`.
|
||||
2. Cria um `URLClassLoader` : um "carregador de classes" isolado, que sabe ler código de dentro desses `.jar`.
|
||||
3. Usa `ServiceLoader.load(Plugin.class, pluginClassLoader)` para perguntar: *"dentre essas classes, quais implementam `Plugin`?"*
|
||||
4. Para cada plugin encontrado, chama `createPlugin(mainWindow)` e guarda o plugin numa lista.
|
||||
```java
|
||||
ServiceLoader<Plugin> serviceLoader = ServiceLoader.load(Plugin.class, pluginClassLoader);
|
||||
|
||||
for (Plugin plugin : serviceLoader) {
|
||||
plugin.createPlugin(this.mainWindow);
|
||||
this.mainWindow.getPlugins().add(plugin);
|
||||
}
|
||||
```
|
||||
|
||||
**Obs:** o `ServiceLoader` do Java **não escaneia o bytecode procurando quem implementa a interface**. Ele lê um arquivo de texto simples dentro do `.jar`. Se esse arquivo não existir ou estiver errado, o plugin é ignorado : mesmo que o código esteja perfeito.
|
||||
|
||||
---
|
||||
|
||||
## 4.`META-INF/services`
|
||||
|
||||
Dentro do projeto `pitiupi.chat` por exemplo, existe este arquivo:
|
||||
|
||||
```
|
||||
pitiupi.chat/src/META-INF/services/pitiupi.plugin.Plugin
|
||||
```
|
||||
|
||||
Repare em duas coisas:
|
||||
|
||||
- A **pasta** se chama `META-INF/services`.
|
||||
- O **nome do arquivo** é o nome completo da interface: `pitiupi.plugin.Plugin`.
|
||||
- O **conteúdo** do arquivo é uma linha com o nome completo da classe que implementa essa interface:
|
||||
```
|
||||
pitiupi.chat.plugin.ChatPlugin
|
||||
```
|
||||
|
||||
- O`Plugin` diz **"eu sei fazer o trabalho"**.
|
||||
- O arquivo em `META-INF/services` diz **"aqui está quem sabe fazer o trabalho"**.
|
||||
- Sem o segundo, o pitiupi nunca fica sabendo que a classe existe.
|
||||
---
|
||||
|
||||
## 5. Exemplo real: o `ChatPlugin`
|
||||
|
||||
Veja como o plugin de chat implementa o contrato : use isso como referência ao escrever o seu:
|
||||
|
||||
```java
|
||||
public class ChatPlugin implements Plugin {
|
||||
|
||||
private ChatWindow chatWindow;
|
||||
private MainWindow mainWindow;
|
||||
|
||||
@Override
|
||||
public void createPlugin(MainWindow mainWindow) {
|
||||
this.mainWindow = mainWindow;
|
||||
this.chatWindow = new ChatWindow(mainWindow);
|
||||
this.mainWindow.addMenu(new ChatMenu(chatWindow));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveMessage(byte[] message) {
|
||||
// desserializa os bytes recebidos de volta em um objeto ChatMessage
|
||||
ByteArrayInputStream bis = new ByteArrayInputStream(message);
|
||||
try {
|
||||
ObjectInputStream ois = new ObjectInputStream(bis);
|
||||
if (ois.readObject() instanceof ChatMessage msg) {
|
||||
this.chatWindow.receiveChatMessage(msg);
|
||||
}
|
||||
} catch (IOException | ClassNotFoundException ex) {
|
||||
System.out.println(ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() { return "Chat"; }
|
||||
|
||||
@Override
|
||||
public String getAuthor() { return "Flávio, Tony e Gustavo "; }
|
||||
|
||||
@Override
|
||||
public String getVersion() { return "0"; }
|
||||
|
||||
@Override
|
||||
public Message getMessage() { return new ChatMessage(); }
|
||||
}
|
||||
```
|
||||
|
||||
Em `createPlugin` é onde o bum de "aparecer na tela" acontece: ele cria a janela do plugin e adiciona um menu na janela principal do pitiupi.
|
||||
|
||||
---
|
||||
|
||||
## 6. Passo a passo: criando um plugin novo do zero
|
||||
|
||||
Vamos chamar o plugin de exemplo de `SeuPlugin`.
|
||||
|
||||
### Passo 1 : Criar a estrutura do projeto
|
||||
|
||||
Se você quiser um jeito mais facil sem se aprofundar, você pode criar o projeto de duas formas:
|
||||
|
||||
- **Mais simples:** copie um projeto Ant existente, como `pitiupi.chat` por exemplo, e remova o código específico do Chat.
|
||||
- **Outra opção:** crie um novo projeto no NetBeans usando **"Java Class Library"**, mantendo a mesma estrutura de pastas.
|
||||
|
||||
|
||||
```
|
||||
pitiupi.seuplugin/
|
||||
├── build.xml
|
||||
├── nbproject/
|
||||
└── src/
|
||||
├── META-INF/services/
|
||||
└── pitiupi/seuplugin/plugin/
|
||||
```
|
||||
|
||||
### Passo 2 : Adicionar o `pitiupi.jar` como dependência
|
||||
|
||||
O plugin precisa do arquivo **`pitiupi/dist/pitiupi.jar`** para acessar `Plugin` e `MainWindow`.
|
||||
|
||||
- **Se criou do zero:** configure o `pitiupi.jar` como dependência.
|
||||
- **Se copiou um projeto existente:** essa configuração já está pronta.
|
||||
- **Se criou pelo NetBeans:** **Properties → Libraries → Add JAR/Folder** → selecione `pitiupi/dist/pitiupi.jar`.
|
||||
|
||||
|
||||
### Passo 3 : Implementar a interface `Plugin`
|
||||
|
||||
Crie `src/pitiupi/seuplugin/plugin/SeuPlugin.java`:
|
||||
|
||||
```java
|
||||
package pitiupi.seuplugin.plugin;
|
||||
|
||||
import pitiupi.GUI.MainWindow;
|
||||
import pitiupi.net.Message;
|
||||
import pitiupi.plugin.Plugin;
|
||||
|
||||
public class SeuPlugin implements Plugin {
|
||||
|
||||
@Override
|
||||
public void createPlugin(MainWindow window) {
|
||||
System.out.println("SeuPlugin foi carregado!");
|
||||
// aqui você criaria sua janela/menu, como o ChatPlugin faz
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveMessage(byte[] message) {
|
||||
// trate as mensagens recebidas da rede aqui
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() { return "MeuPlugin"; }
|
||||
|
||||
@Override
|
||||
public String getAuthor() { return "Seu Nome"; }
|
||||
|
||||
@Override
|
||||
public String getVersion() { return "0.1"; }
|
||||
|
||||
@Override
|
||||
public Message getMessage() { return null; } // troque por uma Message real, se tiver
|
||||
}
|
||||
```
|
||||
|
||||
### Passo 4 : Registrar o plugin no `ServiceLoader`
|
||||
|
||||
Crie o arquivo (sem extensão):
|
||||
|
||||
```
|
||||
src/META-INF/services/pitiupi.plugin.Plugin
|
||||
```
|
||||
|
||||
Com **uma única linha** dentro, o nome completo da sua classe:
|
||||
|
||||
```
|
||||
pitiupi.seuplugin.plugin.MeuPlugin
|
||||
```
|
||||
|
||||
|
||||
### Passo 5 : Compilar com Ant
|
||||
|
||||
```bash
|
||||
cd pitiupi.seuplugin
|
||||
ant jar
|
||||
```
|
||||
|
||||
Isso gera o `.jar` em `pitiupi.seuplugin/dist/`.
|
||||
|
||||
### Passo 6 : Linkar o `.jar` na pasta de plugins
|
||||
|
||||
```bash
|
||||
cd pitiupi/plugins
|
||||
ln -s ../../pitiupi.meuplugin/dist/*.jar .
|
||||
```
|
||||
|
||||
Usar link simbólico (`ln -s`) é melhor durante o desenvolvimento: toda vez que você recompilar o plugin, não precisa copiar de novo.
|
||||
|
||||
|
||||
## 7. Geral
|
||||
|
||||
```
|
||||
Plugin.java → "o que todo plugin precisa saber fazer" (o contrato)
|
||||
MeuPlugin.java → "como EU faço esse trabalho" (a implementação)
|
||||
META-INF/services/pitiupi.plugin.Plugin → "aqui está quem faz o trabalho" (o registro)
|
||||
PluginLoader.java → "eu procuro registros e chamo quem se registrou" (o carregador, já pronto no pitiupi)
|
||||
```
|
||||
|
||||
Entendendo essas quatro peças, criar qualquer plugin novo : chat, screencast, ou algo totalmente diferente (arquivos, jogos, sensores) : é sempre o mesmo padrão: implementar a interface, registrar no `META-INF/services`, compilar e linkar.
|
||||
@@ -94,7 +94,7 @@ public class ChatWindow extends javax.swing.JDialog {
|
||||
if (jTextArea1.getText().trim().length() == 0) {
|
||||
return;
|
||||
}
|
||||
ChatMessage message = new ChatMessage(mainWindow.getName(), jTextArea1.getText());
|
||||
ChatMessage message = new ChatMessage(mainWindow.getUserName(), jTextArea1.getText());
|
||||
this.sendChatMessage(message);
|
||||
jTextArea1.setText("");
|
||||
}
|
||||
|
||||
Generated
+61
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="AutoImportSettings">
|
||||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="083e72ce-fa9b-4ddf-a0ef-24105aa3eabb" name="Changes" comment="">
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/META-INF/services/pitiupi.plugin.Plugin" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/pitiupi/GUI/QuizWindow.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/pitiupi/control/Pergunta.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/pitiupi/control/Quiz.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/pitiupi/net/QuizMessage.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../pitiupi.quiz/src/pitiupi/plugin/Quiz.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/../.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../.idea/workspace.xml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/src/pitiupi/screenCast/net/ScreenCastMessage.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/pitiupi/screenCast/net/ScreenCastMessage.java" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
|
||||
</component>
|
||||
<component name="ProjectColorInfo"><![CDATA[{
|
||||
"associatedIndex": 7
|
||||
}]]></component>
|
||||
<component name="ProjectId" id="3Gs0wFaRD4HyhP9VXLUWBeq0qTL" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"git-widget-placeholder": "QuizPlugin",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi/pitiupi.screenCast",
|
||||
"settings.editor.selected.configurable": "preferences.keymap"
|
||||
}
|
||||
}]]></component>
|
||||
<component name="SharedIndexes">
|
||||
<attachedChunks>
|
||||
<set>
|
||||
<option value="bundled-jdk-9823dce3aa75-bf35d07a577b-intellij.indexing.shared.core-IU-252.28539.54" />
|
||||
</set>
|
||||
</attachedChunks>
|
||||
</component>
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="083e72ce-fa9b-4ddf-a0ef-24105aa3eabb" name="Changes" comment="" />
|
||||
<created>1784745206049</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1784745206049</updated>
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
</project>
|
||||
@@ -60,7 +60,7 @@ O método `send()` recebe uma mensagem já serializada em bytes e cria um
|
||||
|
||||
De forma geral, o socket atua apenas como mecanismo de transporte das mensagens.
|
||||
A única exceção é o tratamento de HeartbeatMessage, utilizado pela infraestrutura
|
||||
da aplicação para manter a lista de usuários ativos.
|
||||
da aplicação para manter a lista de peers ativos.
|
||||
|
||||
#### Recepção de mensagens
|
||||
|
||||
@@ -98,9 +98,15 @@ comportamentos necessários para cada funcionalidade.
|
||||
O mecanismo de heartbeat é utilizado para identificar quais usuários estão
|
||||
ativos na rede.
|
||||
|
||||
A aplicação envia periodicamente uma `HeartbeatMessage` contendo informações
|
||||
do usuário e um timestamp. Quando outra instância recebe essa mensagem, o
|
||||
`HeartbeatManager` atualiza o registro do usuário correspondente.
|
||||
A aplicação envia periodicamente uma `HeartbeatMessage` contendo
|
||||
informações do usuário, um identificador único da instância da aplicação
|
||||
e um timestamp. Quando outra instância recebe essa mensagem, o `HeartbeatManager`
|
||||
registra ou atualiza o peer correspondente, utilizando o identificador
|
||||
da instância para diferenciá-lo das demais.
|
||||
|
||||
Um peer é considerado inativo quando permanece mais de 15 segundos
|
||||
sem receber um novo heartbeat. O `HeartbeatManager` então remove o peer
|
||||
da lista e notifica os listeners sobre a alteração.
|
||||
|
||||
O fluxo de heartbeat é independente das mensagens dos plugins:
|
||||
|
||||
@@ -109,7 +115,7 @@ O fluxo de heartbeat é independente das mensagens dos plugins:
|
||||
3. O `Socket` transmite a mensagem pela rede multicast.
|
||||
4. O `Socket` identifica mensagens de heartbeat recebidas e encaminha ao
|
||||
`HeartbeatManager`.
|
||||
5. O `HeartbeatManager` atualiza a lista de usuários ativos e notifica os
|
||||
5. O `HeartbeatManager` atualiza a lista de peers ativos e notifica os
|
||||
listeners.
|
||||
|
||||
## Sistema de plugins
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package pitiupi.GUI;
|
||||
|
||||
import java.awt.BorderLayout;
|
||||
@@ -11,6 +6,7 @@ import java.awt.GridBagConstraints;
|
||||
import java.awt.GridBagLayout;
|
||||
import java.awt.Insets;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.util.prefs.Preferences;
|
||||
|
||||
import javax.swing.JButton;
|
||||
import javax.swing.JDialog;
|
||||
@@ -26,9 +22,14 @@ import javax.swing.JTextField;
|
||||
* multicast que será utilizada pela comunicação.</p>
|
||||
*
|
||||
* @author flavio
|
||||
* @author tony
|
||||
*/
|
||||
public final class Login extends JDialog {
|
||||
|
||||
private static final Preferences prefs = Preferences.userNodeForPackage(Login.class);
|
||||
private static final String PREF_NOME = "lastUserName";
|
||||
private static final String PREF_PORTA = "lastPort";
|
||||
|
||||
JLabel nameLabel = new JLabel("Name: ");
|
||||
JLabel portLabel = new JLabel("Port: ");
|
||||
|
||||
@@ -47,8 +48,12 @@ public final class Login extends JDialog {
|
||||
public void initComponents() {
|
||||
this.setTitle("Login");
|
||||
|
||||
portField.setModel(new javax.swing.SpinnerNumberModel(8000, 8000, 9000, 1));
|
||||
nameField.setText(System.getProperty("user.name"));
|
||||
|
||||
String nomeSalvo = prefs.get(PREF_NOME, System.getProperty("user.name"));
|
||||
int portaSalva = prefs.getInt(PREF_PORTA, 8000);
|
||||
|
||||
portField.setModel(new javax.swing.SpinnerNumberModel(portaSalva, 8000, 9000, 1));
|
||||
nameField.setText(nomeSalvo);
|
||||
|
||||
JPanel topPanel = new JPanel(new GridBagLayout());
|
||||
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
|
||||
@@ -87,6 +92,15 @@ public final class Login extends JDialog {
|
||||
this.add(buttonPanel, BorderLayout.SOUTH);
|
||||
|
||||
okButton.addActionListener((ActionEvent e) -> {
|
||||
try {
|
||||
portField.commitEdit();
|
||||
} catch (java.text.ParseException ex) {
|
||||
return;
|
||||
}
|
||||
|
||||
prefs.put(PREF_NOME, nameField.getText());
|
||||
prefs.putInt(PREF_PORTA, (Integer) portField.getValue());
|
||||
|
||||
Login.this.setVisible(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ public class MainWindow extends javax.swing.JFrame {
|
||||
|
||||
private Socket socket;
|
||||
|
||||
private final String userName;
|
||||
private final int port;
|
||||
private String userName;
|
||||
private int port;
|
||||
|
||||
private PluginLoader pluginManager;
|
||||
private final List<Plugin> plugins;
|
||||
@@ -137,4 +137,28 @@ public class MainWindow extends javax.swing.JFrame {
|
||||
public List<Plugin> getPlugins() {
|
||||
return plugins;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
updateStatus();
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
reconnect();
|
||||
updateStatus();
|
||||
}
|
||||
|
||||
private void updateStatus() {
|
||||
this.status.setText("Connected on port " + this.port + " name " + this.userName);
|
||||
}
|
||||
|
||||
private void reconnect() {
|
||||
if (this.socket != null) {
|
||||
this.socket.close();
|
||||
}
|
||||
this.socket = new Socket(this);
|
||||
this.socket.start();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import javax.swing.JMenuBar;
|
||||
*
|
||||
* @author flavio
|
||||
* @author Gustavo
|
||||
* @author tony
|
||||
*
|
||||
*/
|
||||
public class MenuBar extends JMenuBar {
|
||||
|
||||
@@ -27,6 +29,11 @@ public class MenuBar extends JMenuBar {
|
||||
private javax.swing.JMenuItem exitMenu;
|
||||
private final MainWindow mainWindow;
|
||||
|
||||
/**
|
||||
* Cria a barra de menus principal da aplicação.
|
||||
*
|
||||
* @param mainWindow mainWindow janela principal da aplicação utilizada para executar
|
||||
*/
|
||||
public MenuBar(MainWindow mainWindow) {
|
||||
this.mainWindow = mainWindow;
|
||||
this.initComponents();
|
||||
@@ -67,9 +74,14 @@ public class MenuBar extends JMenuBar {
|
||||
mainWindow.exit();
|
||||
}
|
||||
|
||||
private void setupMenuActionPerformed(java.awt.event.ActionEvent evt) {
|
||||
|
||||
private void setupMenuActionPerformed(java.awt.event.ActionEvent evt) {
|
||||
Login login = new Login();
|
||||
login.setVisible(true);
|
||||
|
||||
mainWindow.setUserName(login.getName());
|
||||
mainWindow.setPort(login.getPort());
|
||||
|
||||
login.dispose();
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import java.util.logging.Logger;
|
||||
/**
|
||||
*
|
||||
* @author flavio
|
||||
* @author tony
|
||||
*/
|
||||
public class Main {
|
||||
/**
|
||||
@@ -39,16 +40,17 @@ public class Main {
|
||||
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
|
||||
java.util.logging.Logger.getLogger(pitiupi.GUI.MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
|
||||
}
|
||||
//</editor-fold>
|
||||
|
||||
/* Create and display the form */
|
||||
java.awt.EventQueue.invokeLater(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
pitiupi.GUI.Login login = new pitiupi.GUI.Login();
|
||||
login.setVisible(true);
|
||||
|
||||
pitiupi.GUI.MainWindow main;
|
||||
main = new pitiupi.GUI.MainWindow(System.getProperty("user.name"), 8000);
|
||||
main = new pitiupi.GUI.MainWindow(login.getName(), login.getPort());
|
||||
main.setVisible(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import pitiupi.GUI.MainWindow;
|
||||
import pitiupi.net.HeartbeatMessage;
|
||||
import java.util.UUID;
|
||||
/**
|
||||
* Gerencia o mecanismo de heartbeat da aplicação.
|
||||
*
|
||||
@@ -32,17 +33,30 @@ public class HeartbeatManager {
|
||||
private final Map<String, PeerInfo> peers = new ConcurrentHashMap<>();
|
||||
private final List<PeerListener> listeners = new CopyOnWriteArrayList<>();
|
||||
private ScheduledExecutorService scheduler;
|
||||
private final String instanceId = UUID.randomUUID().toString();
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
this.mainWindow = mainWindow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicia o mecanismo de heartbeat.
|
||||
*/
|
||||
public void start() {
|
||||
scheduler = Executors.newScheduledThreadPool(1);
|
||||
scheduler.scheduleAtFixedRate(this::announce, 0, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS);
|
||||
scheduler.scheduleAtFixedRate(this::checkTimeouts, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Para o mecanismo de heartbeat e encerra as tarefas agendadas.
|
||||
*/
|
||||
public void stop() {
|
||||
if (scheduler != null) {
|
||||
scheduler.shutdownNow();
|
||||
@@ -51,7 +65,7 @@ public class HeartbeatManager {
|
||||
|
||||
private void announce() {
|
||||
try {
|
||||
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName());
|
||||
HeartbeatMessage msg = new HeartbeatMessage(mainWindow.getUserName(), instanceId);
|
||||
mainWindow.getSocket().send(msg.toByteArray());
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger(HeartbeatManager.class.getName()).log(Level.WARNING, "Falha ao enviar heartbeat", ex);
|
||||
@@ -62,21 +76,22 @@ public class HeartbeatManager {
|
||||
/**
|
||||
* Processa uma mensagem de heartbeat recebida de outro usuário.
|
||||
*
|
||||
* <p>Atualiza a informação do peer correspondente e notifica os listeners
|
||||
* caso um novo usuário seja identificado.</p>
|
||||
* <p>Atualiza o momento da última atividade do peer correspondente e notifica os listeners
|
||||
* caso outra instância da aplicação seja identificada.</p>
|
||||
*
|
||||
* <p>Mensagens de heartbeat enviadas pela própria aplicação são ignoradas.</p>
|
||||
*
|
||||
* @param msg mensagem de heartbeat recebida.
|
||||
* @param from endereço de rede do usuário que enviou a mensagem.
|
||||
*/
|
||||
|
||||
public void receiveHeartbeat(HeartbeatMessage msg, InetAddress from) {
|
||||
// ignora o próprio heartbeat
|
||||
if (msg.getUserName().equals(mainWindow.getUserName())) {
|
||||
if (msg.getInstanceId().equals(instanceId) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
String key = from.getHostAddress() + "#" + msg.getUserName();
|
||||
String key = msg.getInstanceId();
|
||||
boolean isNew = !peers.containsKey(key);
|
||||
|
||||
PeerInfo peer = peers.computeIfAbsent(key, k -> new PeerInfo(msg.getUserName(), from, msg.getTimestamp()));
|
||||
@@ -115,10 +130,20 @@ public class HeartbeatManager {
|
||||
l.onPeersChanged(new ArrayList<>(peers.values()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove um listener previamente registrado.
|
||||
*
|
||||
* @param l listener que deixará de receber atualizações.
|
||||
*/
|
||||
public void removePeerListener(PeerListener l) {
|
||||
listeners.remove(l);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna uma cópia da lista atual de peers conhecidos.
|
||||
*
|
||||
* @return lista contendo os peers atualmente conhecidos.
|
||||
*/
|
||||
public List<PeerInfo> getPeers() {
|
||||
return new ArrayList<>(peers.values());
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ public class HeartbeatMessage extends Message {
|
||||
|
||||
private final String userName;
|
||||
private final long timestamp;
|
||||
private final String instanceId;
|
||||
|
||||
public HeartbeatMessage(String userName) {
|
||||
public HeartbeatMessage(String userName, String instanceId) {
|
||||
this.userName = userName;
|
||||
this.instanceId = instanceId;
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
@@ -24,4 +26,8 @@ public class HeartbeatMessage extends Message {
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public String getInstanceId() {
|
||||
return instanceId;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import pitiupi.plugin.Plugin;
|
||||
import pitiupi.net.HeartbeatMessage;
|
||||
|
||||
/**
|
||||
* Responsável pela comunicação multicast entre a aplicação e os plugins.
|
||||
* "Responsável pela comunicação multicast da aplicação e pelo encaminhamento de mensagens aos plugins."
|
||||
*
|
||||
* <p>Esta classe gerencia o envio e o recebimento de mensagens, além de
|
||||
* manter a conexão com o grupo multicast utilizado pela aplicação.</p>
|
||||
@@ -33,6 +33,7 @@ public class Socket extends Thread {
|
||||
private MulticastSocket multicastSocket;
|
||||
private InetAddress address;
|
||||
private MainWindow main;
|
||||
private volatile boolean running = true;
|
||||
public final static String INET_ADDR = "224.0.0.3";
|
||||
|
||||
/**
|
||||
@@ -71,6 +72,22 @@ public class Socket extends Thread {
|
||||
multicastSocket.send(msgPacket);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encerra a comunicação multicast e interrompe a recepção de mensagens.
|
||||
*/
|
||||
public void close() {
|
||||
running = false;
|
||||
if (multicastSocket != null) {
|
||||
try {
|
||||
multicastSocket.leaveGroup(address);
|
||||
} catch (IOException ex) {
|
||||
|
||||
}
|
||||
multicastSocket.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inicia o loop de recepção de mensagens da aplicação.
|
||||
*
|
||||
@@ -84,16 +101,21 @@ public class Socket extends Thread {
|
||||
*/
|
||||
public void receive() throws UnknownHostException, IOException, ClassNotFoundException {
|
||||
byte[] buf = new byte[256000];
|
||||
while (true) {
|
||||
while (running) {
|
||||
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
|
||||
multicastSocket.receive(msgPacket);
|
||||
|
||||
try {
|
||||
multicastSocket.receive(msgPacket);
|
||||
} catch (IOException ex) {
|
||||
if (!running) {
|
||||
break;
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
HeartbeatMessage heartbeat = tryParseHeartbeat(msgPacket.getData());
|
||||
if (heartbeat != null) {
|
||||
main.getHeartbeatManager().receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
||||
continue;
|
||||
}
|
||||
|
||||
for (Plugin plugin : main.getPlugins()) {
|
||||
System.out.println(msgPacket.getAddress().toString());
|
||||
plugin.receiveMessage(msgPacket.getData());
|
||||
|
||||
Reference in new issue
Block a user