From ddad533768b6461e2ba37c14e39bd68d6cf62950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Tue, 8 Jan 2019 19:18:50 +0100 Subject: [PATCH 01/60] a --- .idea/encodings.xml | 4 + .idea/modules.xml | 1 + .idea/resourceBundles.xml | 14 + .idea/uiDesigner.xml | 4 + standalone/build.gradle | 1 + .../undernet/file/StandaloneFileManager.java | 4 +- .../standalone/UnderNetStandalone.java | 72 ++-- .../undernet/standalone/ui/AppFrame.java | 313 ------------------ .../undernet/standalone/ui/ContentPanel.java | 27 -- .../undernet/standalone/ui/NodesPanel.java | 238 ------------- .../standalone/ui/ResourcesPanel.java | 170 ---------- .../undernet/standalone/uix/MainFrame.form | 84 +++++ .../undernet/standalone/uix/MainFrame.java | 199 +++++++++++ .../undernet/standalone/uix/NodePanel.form | 40 +++ .../undernet/standalone/uix/NodePanel.java | 99 ++++++ .../standalone/uix/ResourcePanel.form | 39 +++ .../standalone/uix/ResourcePanel.java | 96 ++++++ .../undernet/standalone/uix/TunnelPanel.form | 29 ++ .../undernet/standalone/uix/TunnelPanel.java | 44 +++ .../undernet/standalone/uix/VisualPanel.form | 12 + .../undernet/standalone/uix/VisualPanel.java | 36 ++ .../standalone/uix/VisualPanelDraw.java | 39 +++ .../dialog/AddNodeCacheDialog.java | 2 +- .../dialog/PullResourceDialog.java | 2 +- .../dialog/UploadResourceDialog.java | 2 +- .../src/main/resources/language.properties | 5 + .../main/resources/language_Polish.properties | 0 .../resources/language_Russian.properties | 0 28 files changed, 779 insertions(+), 797 deletions(-) create mode 100644 .idea/encodings.xml create mode 100644 .idea/resourceBundles.xml delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/ui/AppFrame.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/ui/ContentPanel.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/ui/NodesPanel.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/ui/ResourcesPanel.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java rename standalone/src/main/java/me/matoosh/undernet/standalone/{ui => uix}/dialog/AddNodeCacheDialog.java (98%) rename standalone/src/main/java/me/matoosh/undernet/standalone/{ui => uix}/dialog/PullResourceDialog.java (99%) rename standalone/src/main/java/me/matoosh/undernet/standalone/{ui => uix}/dialog/UploadResourceDialog.java (98%) create mode 100644 standalone/src/main/resources/language.properties create mode 100644 standalone/src/main/resources/language_Polish.properties create mode 100644 standalone/src/main/resources/language_Russian.properties diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 00000000..15a15b21 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml index 9479b186..fd33326f 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,6 +2,7 @@ + diff --git a/.idea/resourceBundles.xml b/.idea/resourceBundles.xml new file mode 100644 index 00000000..e0845a6e --- /dev/null +++ b/.idea/resourceBundles.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + language + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml index e96534fb..c5168f75 100644 --- a/.idea/uiDesigner.xml +++ b/.idea/uiDesigner.xml @@ -121,4 +121,8 @@ + + \ No newline at end of file diff --git a/standalone/build.gradle b/standalone/build.gradle index 0e445f89..6639153d 100644 --- a/standalone/build.gradle +++ b/standalone/build.gradle @@ -3,6 +3,7 @@ apply plugin: 'application' dependencies { compile project(path: ':shared') compile 'com.esotericsoftware.yamlbeans:yamlbeans:1.12' + compile 'com.intellij:forms_rt:7.0.3' compile group: 'commons-io', name: 'commons-io', version: '2.4' } diff --git a/standalone/src/main/java/me/matoosh/undernet/file/StandaloneFileManager.java b/standalone/src/main/java/me/matoosh/undernet/file/StandaloneFileManager.java index 6566336e..8d9160f5 100644 --- a/standalone/src/main/java/me/matoosh/undernet/file/StandaloneFileManager.java +++ b/standalone/src/main/java/me/matoosh/undernet/file/StandaloneFileManager.java @@ -9,9 +9,9 @@ public class StandaloneFileManager extends FileManager { /** - * Returns the main app folder. + * Returns the panel app folder. * - * @return the main app folder. + * @return the panel app folder. */ @Override public File getAppFolder() { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java b/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java index 4b20f1a6..b5be5ec3 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java @@ -6,11 +6,10 @@ import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.file.StandaloneFileManager; import me.matoosh.undernet.identity.NetworkIdentity; -import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.standalone.config.StandaloneConfig; import me.matoosh.undernet.standalone.config.StandaloneConfigManager; import me.matoosh.undernet.standalone.serialization.SerializationTools; -import me.matoosh.undernet.standalone.ui.AppFrame; +import me.matoosh.undernet.standalone.uix.MainFrame; import org.cfg4j.provider.ConfigurationProvider; import org.cfg4j.provider.ConfigurationProviderBuilder; import org.cfg4j.source.ConfigurationSource; @@ -25,7 +24,6 @@ import java.awt.*; import java.io.*; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Map; @@ -37,11 +35,6 @@ */ public class UnderNetStandalone { - /** - * The main frame of the app. - */ - public static AppFrame mainAppFrame; - /** * The network identity to use when connecting. */ @@ -67,36 +60,32 @@ public static void main (String[] args) { setup(); //Starting the ui. - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - mainAppFrame = new AppFrame(); - mainAppFrame.setVisible(true); - - //Creating network identity. - if(standaloneConfig.identity() == null || standaloneConfig.identity().isEmpty() || standaloneConfig.identity().equals("empty")) { - logger.info("No identity cached, creating a new identity!"); - UnderNetStandalone.setNetworkIdentity(null, null); - } else { - logger.info("Identity cached, loading identity {}!", standaloneConfig.identity()); - File currentIdentityFile = new File(standaloneConfig.identity()); - - try { - if (currentIdentityFile.exists()) { - NetworkIdentity identity = (NetworkIdentity) SerializationTools.readObjectFromFile(currentIdentityFile); - UnderNetStandalone.setNetworkIdentity(identity, currentIdentityFile); - } else { - logger.warn("Identity file: {}, doesn't exist! Creating a new identity!", currentIdentityFile); - } - } - catch (NullPointerException e) { - logger.warn("Error reading the identity file!", e); - currentIdentityFile.delete(); + EventQueue.invokeLater(() -> { + MainFrame.newInstance(); + + //Creating network identity. + if(standaloneConfig.identity() == null || standaloneConfig.identity().isEmpty() || standaloneConfig.identity().equals("empty")) { + logger.info("No identity cached, creating a new identity!"); + UnderNetStandalone.setNetworkIdentity(null, null); + } else { + logger.info("Identity cached, loading identity {}!", standaloneConfig.identity()); + File currentIdentityFile = new File(standaloneConfig.identity()); + + try { + if (currentIdentityFile.exists()) { + NetworkIdentity identity = (NetworkIdentity) SerializationTools.readObjectFromFile(currentIdentityFile); + UnderNetStandalone.setNetworkIdentity(identity, currentIdentityFile); + } else { + logger.warn("Identity file: {}, doesn't exist! Creating a new identity!", currentIdentityFile); } - finally { - if(networkIdentity == null) { - UnderNetStandalone.setNetworkIdentity(null, null); - } + } + catch (NullPointerException e) { + logger.warn("Error reading the identity file!", e); + currentIdentityFile.delete(); + } + finally { + if(networkIdentity == null) { + UnderNetStandalone.setNetworkIdentity(null, null); } } } @@ -116,12 +105,7 @@ private static void setup() { //Getting the file configuration source. //Specify which files to load. Configuration from both files will be merged. logger.info("Loading configuration from: {}", tmpFileMgr.getAppFolder()); - ConfigFilesProvider configFilesProvider = new ConfigFilesProvider() { - @Override - public Iterable getConfigFiles() { - return Arrays.asList(Paths.get("network.yaml"), Paths.get("standalone.yaml")); - } - }; + ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("network.yaml"), Paths.get("standalone.yaml")); //Use local files as configuration store ConfigurationSource source = new FilesConfigurationSource(configFilesProvider); @@ -162,7 +146,7 @@ public static void setNetworkIdentity(NetworkIdentity identity, File identityFil //Setting the identity. logger.info("Setting the current UnderNet identity to: {}", identity.getNetworkId().getStringValue()); UnderNetStandalone.networkIdentity = identity; - mainAppFrame.setTitle("UnderNet - " + UnderNetStandalone.networkIdentity.getNetworkId().getStringValue()); + MainFrame.instance.frame.setTitle("UnderNet - " + UnderNetStandalone.networkIdentity.getNetworkId().getStringValue()); //Save the changed identity. try { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/AppFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/ui/AppFrame.java deleted file mode 100644 index 9d8deae1..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/AppFrame.java +++ /dev/null @@ -1,313 +0,0 @@ -package me.matoosh.undernet.standalone.ui; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.event.Event; -import me.matoosh.undernet.event.EventHandler; -import me.matoosh.undernet.event.EventManager; -import me.matoosh.undernet.event.client.ClientExceptionEvent; -import me.matoosh.undernet.event.router.RouterStatusEvent; -import me.matoosh.undernet.event.server.ServerExceptionEvent; -import me.matoosh.undernet.identity.NetworkIdentity; -import me.matoosh.undernet.standalone.UnderNetStandalone; -import me.matoosh.undernet.standalone.serialization.SerializationTools; -import me.matoosh.undernet.standalone.ui.dialog.PullResourceDialog; -import me.matoosh.undernet.standalone.ui.dialog.UploadResourceDialog; -import org.apache.commons.io.FilenameUtils; - -import javax.swing.*; -import javax.swing.filechooser.FileFilter; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -/** - * The main frame of the app. - * Created by Mateusz Rębacz on 09.09.2017. - */ - -public class AppFrame extends JFrame { - /** - * The simulation panel. - */ - public static ContentPanel contentPanel; - /** - * The list of nodes. - */ - public NodesPanel nodesPanel; - /** - * The list of communities. - */ - public ResourcesPanel resourcesPanel; - - /** - * The menu bar of the frame. - */ - private JMenuBar menuBar; - /** - * The nodes menu of the frame. - */ - private JMenu nodesMenu; - /** - * The add node menu item. - */ - private JMenuItem addNodeMenuItem; - - /** - * The identity menu of the frame. - */ - private JMenu identityMenu; - /** - * The change identity menu item. - */ - private JMenuItem identityChangeItem; - /** - * The generate identity menu item. - */ - private JMenuItem identityNewItem; - - /** - * The resource menu of the frame. - */ - private JMenu resourceMenu; - /** - * The resource upload menu item. - */ - private JMenuItem resourcePublishItem; - /** - * The resource pull menu item. - */ - private JMenuItem resourcePullItem; - - - public AppFrame() { - super("UnderNet"); - setSize(800, 600); - - centerWindow(); - - setLayout(new GridBagLayout()); - addMenus(); - addPanels(); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - } - - /** - * Centers the window on the screen. - */ - private void centerWindow() { - //Getting the center of the screen. - GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - int screenWidth = gd.getDisplayMode().getWidth(); - int screenHeight = gd.getDisplayMode().getHeight(); - - setLocation(screenWidth/2 - getSize().width/2, screenHeight/2 - getSize().height/2); - } - - /** - * Adds menus to the frame. - */ - private void addMenus() { - //Adding the menus. - menuBar = new JMenuBar(); - add(menuBar); - - //Nodes menu. - nodesMenu = new JMenu("Nodes"); - menuBar.add(nodesMenu); - addNodeMenuItem = new JMenuItem("Add node"); - addNodeMenuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - nodesPanel.openNodeAddDialog(); - } - }); - nodesMenu.add(addNodeMenuItem); - - //Identity menu - identityMenu = new JMenu("Identity"); - menuBar.add(identityMenu); - identityChangeItem = new JMenuItem("Change identity"); - identityChangeItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Opening file open dialog. - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setDialogTitle("Choose the identity to use"); - fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); - FileFilter filter = new FileNameExtensionFilter("Identity Files", "id"); - fileChooser.setFileFilter(filter); - fileChooser.addChoosableFileFilter(filter); - fileChooser.setCurrentDirectory(UnderNet.fileManager.getAppFolder()); - if(fileChooser.showSaveDialog(AppFrame.this) == JFileChooser.APPROVE_OPTION) { - //Reading the identity file. - NetworkIdentity identity = (NetworkIdentity)SerializationTools.readObjectFromFile(fileChooser.getSelectedFile()); - - if(identity == null) { - //Incorrect file. - JOptionPane.showMessageDialog(AppFrame.this, String.format("Couldn't read the identity file %s", fileChooser.getSelectedFile()),"Can't read identity!", JOptionPane.ERROR_MESSAGE); - - return; - } - - //User chose the save option. - SerializationTools.writeObjectToFile(identity, fileChooser.getSelectedFile()); - - //Setting the new id. - UnderNetStandalone.setNetworkIdentity(identity, fileChooser.getSelectedFile()); - } - } - }); - identityMenu.add(identityChangeItem); - identityNewItem = new JMenuItem("New identity"); - identityNewItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Generating the new identity. - NetworkIdentity newIdentity = new NetworkIdentity(); - - //Opening file save dialog. - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setDialogTitle("Save the new identity"); - fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); - FileFilter filter = new FileNameExtensionFilter("Identity Files", "id"); - fileChooser.setFileFilter(filter); - fileChooser.addChoosableFileFilter(filter); - fileChooser.setCurrentDirectory(UnderNet.fileManager.getAppFolder()); - if(fileChooser.showSaveDialog(AppFrame.this) == JFileChooser.APPROVE_OPTION) { - //User chose the save option. - File file = fileChooser.getSelectedFile(); - if (!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("id")) { - file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".id"); //Remove the extension (if any) and replace it with ".id" - } - - SerializationTools.writeObjectToFile(newIdentity, file); - - //Setting the new id. - UnderNetStandalone.setNetworkIdentity(newIdentity, file); - } - } - }); - identityMenu.add(identityNewItem); - - //Resource menu - resourceMenu = new JMenu("Resource"); - menuBar.add(resourceMenu); - resourcePublishItem = new JMenuItem("Publish resource"); - resourcePublishItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - JDialog resourceUploadDialog = new UploadResourceDialog(UnderNetStandalone.mainAppFrame); - resourceUploadDialog.setVisible(true); - } - }); - resourcePublishItem.setEnabled(false); - resourceMenu.add(resourcePublishItem); - - resourcePullItem = new JMenuItem("Pull resource"); - resourcePullItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - JDialog resourcePullDialog = new PullResourceDialog(UnderNetStandalone.mainAppFrame); - resourcePullDialog.setVisible(true); - } - }); - resourcePullItem.setEnabled(false); - resourceMenu.add(resourcePullItem); - - setJMenuBar(menuBar); - } - /** - * Adds the app panels. - */ - private void addPanels() { - //Adding the content panel, nodes list and communities list. - contentPanel = new ContentPanel(); - contentPanel.setBorder(BorderFactory.createLineBorder(Color.red)); - nodesPanel = new NodesPanel(this); - nodesPanel.setBorder(BorderFactory.createLineBorder(Color.black)); - resourcesPanel = new ResourcesPanel(this); - resourcesPanel.setBorder(BorderFactory.createLineBorder(Color.black)); - add(resourcesPanel, new GridBagConstraints(0, 0, 1, 1, 0.125, 1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); - add(contentPanel, new GridBagConstraints(1, 0, 1, 1, 0.75, 1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); - add(nodesPanel, new GridBagConstraints(2, 0, 1, 1, 0.125, 1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); - - //Connect button. - final JButton connectButton = new JButton("Connect"); - final ActionListener connectActionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - UnderNet.connect(UnderNetStandalone.networkIdentity); - } - }; - final ActionListener disconnectActionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - UnderNet.disconnect(); - } - }; - connectButton.addActionListener(connectActionListener); - - //Status event handler. - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - RouterStatusEvent statusEvent = (RouterStatusEvent)e; - - EventQueue.invokeLater(() -> { - switch (statusEvent.newStatus) { - case STOPPED: - connectButton.setEnabled(true); - connectButton.setText("Connect"); - for (ActionListener al : connectButton.getActionListeners()) { - connectButton.removeActionListener(al); - } - connectButton.addActionListener(connectActionListener); - - resourcePublishItem.setEnabled(false); - resourcePullItem.setEnabled(false); - break; - case STARTING: - connectButton.setEnabled(false); - resourcePublishItem.setEnabled(false); - resourcePullItem.setEnabled(false); - break; - case STARTED: - connectButton.setText("Disconnect"); - connectButton.setEnabled(true); - for (ActionListener al : connectButton.getActionListeners()) { - connectButton.removeActionListener(al); - } - connectButton.addActionListener(disconnectActionListener); - - resourcePublishItem.setEnabled(true); - resourcePullItem.setEnabled(true); - break; - case STOPPING: - connectButton.setEnabled(false); - resourcePublishItem.setEnabled(false); - resourcePullItem.setEnabled(false); - break; - } - }); - } - }, RouterStatusEvent.class); - - //Error events handlers. - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - EventQueue.invokeLater(()-> JOptionPane.showMessageDialog(AppFrame.this, ((ClientExceptionEvent)e).exception.getMessage() + "\nThe router will stop.", "Error with client", JOptionPane.ERROR_MESSAGE)); - } - }, ClientExceptionEvent.class); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - EventQueue.invokeLater(()-> JOptionPane.showMessageDialog(AppFrame.this, ((ClientExceptionEvent)e).exception.getMessage() + "\nThe router will stop.", "Error with server", JOptionPane.ERROR_MESSAGE)); - } - }, ServerExceptionEvent.class); - - add(connectButton, new GridBagConstraints(0, 1, 3, 1, 1, 0.05, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); - } -} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ContentPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ContentPanel.java deleted file mode 100644 index d8a3d38d..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ContentPanel.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.matoosh.undernet.standalone.ui; - -import java.awt.BorderLayout; -import java.awt.Color; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.SwingConstants; - -/** - * The panel showing content from the currently active community. - * Created by Mateusz Rębacz on 09.09.2017. - */ - -public class ContentPanel extends JPanel { - public ContentPanel () { - setLayout(new BorderLayout()); - setOpaque(true); - setBackground(Color.BLACK); - - JLabel underNetText = new JLabel("UnderNet", SwingConstants.CENTER ); - underNetText.setForeground(Color.WHITE); - - //underNetText. - add(underNetText, BorderLayout.CENTER); - } -} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/NodesPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/ui/NodesPanel.java deleted file mode 100644 index 10fb56d9..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/NodesPanel.java +++ /dev/null @@ -1,238 +0,0 @@ -package me.matoosh.undernet.standalone.ui; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.event.Event; -import me.matoosh.undernet.event.EventHandler; -import me.matoosh.undernet.event.EventManager; -import me.matoosh.undernet.event.cache.NodeCacheAddedEvent; -import me.matoosh.undernet.event.cache.NodeCacheRemovedEvent; -import me.matoosh.undernet.event.channel.ChannelClosedEvent; -import me.matoosh.undernet.event.channel.ChannelCreatedEvent; -import me.matoosh.undernet.event.channel.message.ChannelMessageReceivedEvent; -import me.matoosh.undernet.p2p.cache.EntryNodeCache; -import me.matoosh.undernet.p2p.node.Node; -import me.matoosh.undernet.p2p.router.InterfaceStatus; -import me.matoosh.undernet.p2p.router.data.message.PingMessage; -import me.matoosh.undernet.standalone.UnderNetStandalone; -import me.matoosh.undernet.standalone.ui.dialog.AddNodeCacheDialog; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; - -/** - * Panel displaying the list of known nodes. - * Created by Mateusz Rębacz on 09.09.2017. - */ - -public class NodesPanel extends JPanel { - /** - * Nodes that recently sent messages to self. - */ - public ArrayList receivedMsgFrom = new ArrayList<>(); - - /** - * The list of nodes. - */ - private JList nodesList; - - /** - * The app frame. - */ - private AppFrame frame; - - public NodesPanel(AppFrame frame) { - this.frame = frame; - - //Setting to gridbaglayout. - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - - //Adding the label - add(new JLabel("Nodes")); - - //Adding the list. - nodesList = new JList(new Node[] {}); - nodesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - nodesList.addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent evt) { - JList list = (JList)evt.getSource(); - if (evt.getClickCount() == 2) { - //Double-click detected - if(UnderNet.router.status.equals(InterfaceStatus.STARTED)) { - int index = list.locationToIndex(evt.getPoint()); - Node node = (Node)nodesList.getModel().getElementAt(index); - - //Checking if the node is connected. - if(node.isConnected()) { - //Sending a ping content. - node.getIdentity().getNetworkId().sendMessage(new PingMessage(false)); - } else { - //Connecting to the node. - UnderNet.router.connectNode(node); - } - } - } - } - }); - add(new JScrollPane(nodesList)); - - //Setting cell renderer for the nodes list. - nodesList.setCellRenderer(new NodesListCellRenderer(this)); - - //Adding the buttons on the bottom. - JPanel buttonsDrawer = new JPanel(); - buttonsDrawer.setMaximumSize(new Dimension(200 ,50)); - buttonsDrawer.setLayout(new GridLayout()); - - //Add button - JButton addButton = new JButton("Add"); - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - openNodeAddDialog(); - } - }); - buttonsDrawer.add(addButton); - //Remove button - JButton removeButton = new JButton("Remove"); - removeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - if(nodesList.getSelectedValue() == null) return; - Node selected = ((Node) nodesList.getSelectedValue()); - - //Disconnect or remove from cache. - if(selected.isConnected()) { - UnderNet.router.disconnectNode(selected); - } else { - EntryNodeCache.removeNode(selected); - } - } - }); - buttonsDrawer.add(removeButton); - add(buttonsDrawer); - - //Refreshing the nodes list. - refreshNodesList(); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - //Called when a node is added to the node cache. - refreshNodesList(); - } - }, NodeCacheAddedEvent.class); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - //Called when a node is removed from the node cache. - refreshNodesList(); - } - }, NodeCacheRemovedEvent.class); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - //Called when a connection has been established. - refreshNodesList(); - } - }, ChannelCreatedEvent.class); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - //Called when a connection has been dropped. - refreshNodesList(); - } - }, ChannelClosedEvent.class); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - //Called when a message has been received. - ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent)e; - receivedMsgFrom.add(messageReceivedEvent.remoteNode); - } - }, ChannelMessageReceivedEvent.class); - } - - /** - * Refreshes the nodes list based on the current node cache. - */ - private void refreshNodesList() { - if(UnderNet.router.status.equals(InterfaceStatus.STARTED)) { - //Using connected and cached nodes if the router has started. - ArrayList nodesToList = new ArrayList<>(); - nodesToList.addAll(UnderNet.router.getRemoteNodes()); - for (Node cachedNode: - EntryNodeCache.cachedNodes) { - boolean canAdd = true; - for (Node connectedNode : UnderNet.router.getRemoteNodes()) { - if(cachedNode.getAddress().equals(connectedNode.getAddress())) { - canAdd = false; - } - } - if(canAdd) { - nodesToList.add(cachedNode); - } - } - nodesList.setListData(nodesToList.toArray()); - } else { - //Using cached nodes if the router isn't online. - nodesList.setListData(EntryNodeCache.cachedNodes.toArray()); - } - - //repainting - this.frame.repaint(); - } - - /** - * Opens the add node dialog. - */ - public void openNodeAddDialog() { - //The add button was pressed. - JDialog nodeAddDialog = new AddNodeCacheDialog(UnderNetStandalone.mainAppFrame); - nodeAddDialog.setVisible(true); - } -} -class NodesListCellRenderer extends DefaultListCellRenderer -{ - private NodesPanel nodesPanel; - - public NodesListCellRenderer(NodesPanel panel) { - this.nodesPanel = panel; - } - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value instanceof Node) { - Node node = (Node) value; - setText(node.toString()); - if(UnderNet.router.status == InterfaceStatus.STARTED) { - if (node.isConnected()) { - setBackground(Color.GREEN); - for (int i = 0; i < this.nodesPanel.receivedMsgFrom.size(); i++) { - if (this.nodesPanel.receivedMsgFrom.get(i) != null && this.nodesPanel.receivedMsgFrom.get(i).getAddress().equals(node.getAddress())) { - setBackground(Color.CYAN); - this.nodesPanel.receivedMsgFrom.remove(node); - } - } - } else { - setBackground(Color.RED); - } - } else { - setBackground(Color.ORANGE); - } - - if (isSelected) { - setBackground(getBackground().darker()); - } - } else { - setText("UNKNOWN"); - setBackground(Color.gray); - } - return c; - } -} \ No newline at end of file diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ResourcesPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ResourcesPanel.java deleted file mode 100644 index 2edd849a..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/ResourcesPanel.java +++ /dev/null @@ -1,170 +0,0 @@ -package me.matoosh.undernet.standalone.ui; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.event.EventHandler; -import me.matoosh.undernet.event.EventManager; -import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; -import me.matoosh.undernet.p2p.router.InterfaceStatus; -import me.matoosh.undernet.p2p.router.data.resource.Resource; -import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferType; -import me.matoosh.undernet.standalone.serialization.SerializationTools; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.util.ArrayList; - -/** - * List of resources owned by the node within the current community. - * Created by Mateusz Rębacz on 09.09.2017. - */ - -public class ResourcesPanel extends JPanel { - /** - * The list of nodes. - */ - private JList resourcesList; - - /** - * The app frame. - */ - private AppFrame frame; - - /** - * The resources currently owned by self. - */ - public ArrayList resourceCache = new ArrayList<>(); - - public ResourcesPanel(AppFrame frame) { - this.frame = frame; - - //Loading the resource cache. - loadResourceCache(); - if(resourceCache == null) { - resourceCache = new ArrayList<>(); - } - - //Setting to gridbaglayout. - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - - //Adding the label - add(new JLabel("My Resources")); - - //Adding the list. - resourcesList = new JList(new Resource[] {}); - resourcesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - resourcesList.addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent evt) { - JList list = (JList)evt.getSource(); - if (evt.getClickCount() == 2) { - //Double-click detected - if(UnderNet.router.status.equals(InterfaceStatus.STARTED)) { - int index = list.locationToIndex(evt.getPoint()); - if(index < 0) return; - Resource resource = (Resource) resourcesList.getModel().getElementAt(index); - - if(resource.isLocal()) return; //Already pulled - //Pulling the resource. - UnderNet.router.resourceManager.pull(resource.getNetworkID()); - } - } - } - }); - add(new JScrollPane(resourcesList)); - - //Setting cell renderer for the nodes list. - resourcesList.setCellRenderer(new ResourcesListCellRenderer(this)); - - //Adding the buttons on the bottom. - JPanel buttonsDrawer = new JPanel(); - buttonsDrawer.setMaximumSize(new Dimension(100 ,50)); - buttonsDrawer.setLayout(new GridLayout()); - - - //Refreshing the nodes list. - refreshResourcesList(); - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(me.matoosh.undernet.event.Event e) { - ResourceTransferStartedEvent transferStartedEvent = (ResourceTransferStartedEvent) e; - if(transferStartedEvent.transferHandler.getTransferType() == ResourceTransferType.OUTBOUND) { - addCachedResource(transferStartedEvent.transferHandler.getResource()); - refreshResourcesList(); - } - } - }, ResourceTransferStartedEvent.class); - } - - /** - * Refreshes the resources list. - */ - private void refreshResourcesList() { - if(resourceCache != null) { - resourcesList.setListData(resourceCache.toArray()); - frame.repaint(); - } - } - private void addCachedResource(Resource resource) { - for (int i = 0; i < resourceCache.size(); i++) { - if(resource.getNetworkID().equals(resourceCache.get(i).getNetworkID())) { - return; - } - } - - resourceCache.add(resource); - - saveResourceCache(); - } - private void removeCachedResource(Resource resource) { - resourceCache.remove(resource); - - saveResourceCache(); - } - private void loadResourceCache() { - File resourcesFile = new File(UnderNet.fileManager.getCacheFolder() + "/owned.resources"); - this.resourceCache = (ArrayList) SerializationTools.readObjectFromFile(resourcesFile); - if(this.resourceCache == null && resourcesFile.exists()) { - resourcesFile.delete(); - } - } - private void saveResourceCache() { - SerializationTools.writeObjectToFile(resourceCache, new File(UnderNet.fileManager.getCacheFolder() + "/owned.resources")); - } -} - -/** - * Renders the resource cells. - */ -class ResourcesListCellRenderer extends DefaultListCellRenderer -{ - private ResourcesPanel resourcesPanel; - - public ResourcesListCellRenderer(ResourcesPanel panel) { - this.resourcesPanel = panel; - } - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value instanceof Resource) { - Resource resource = (Resource) value; - setText(resource.getNetworkID().toString()); - if(resource.isLocal()) { - setBackground(Color.GREEN); - } else { - setBackground(Color.CYAN); - } - - if (isSelected) { - setBackground(getBackground().darker()); - } - } else { - setText("UNKNOWN"); - setBackground(Color.gray); - } - return c; - } -} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form new file mode 100644 index 00000000..85243feb --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form @@ -0,0 +1,84 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java new file mode 100644 index 00000000..270cf90f --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -0,0 +1,199 @@ +package me.matoosh.undernet.standalone.uix; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.router.RouterStatusEvent; +import me.matoosh.undernet.p2p.router.InterfaceStatus; +import me.matoosh.undernet.standalone.UnderNetStandalone; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ResourceBundle; + +public class MainFrame extends EventHandler { + + /** + * The logger of the class. + */ + public static Logger logger = LoggerFactory.getLogger(MainFrame.class); + + /** + * The instance of the class. + */ + public static MainFrame instance; + + /** + * The frame. + */ + public JFrame frame; + + private JPanel panel; + private ResourcePanel resourcePanel; + private NodePanel nodePanel; + private TunnelPanel tunnelPanel; + private JProgressBar progressBar; + private JButton mainButton; + private VisualPanel visualPanel; + + public static final int START_HEIGHT = 600; + public static final int START_WIDTH = 950; + + public static void newInstance() { + if (instance != null) { + logger.warn("Can't open more than one Mainframe!"); + return; + } + logger.info("Opening the Mainframe..."); + instance = new MainFrame(); + + instance.frame = new JFrame("UnderNet"); + instance.frame.setContentPane(new MainFrame().panel); + instance.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + instance.initialize(); + instance.frame.pack(); + instance.frame.setSize(START_WIDTH, START_HEIGHT); + + instance.frame.setVisible(true); + } + + private void initialize() { + registerButtons(); + addMenus(); + } + + private void registerButtons() { + this.mainButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + onMainButtonClicked(); + } + }); + } + + private void addMenus() { + + } + + /** + * Called when the main button is clicked. + */ + public void onMainButtonClicked() { + System.out.println("SSSSS"); + logger.info("Main button pressed!"); + + if (UnderNet.router.status == InterfaceStatus.STOPPED) + UnderNet.router.start(UnderNetStandalone.networkIdentity); + else if (UnderNet.router.status == InterfaceStatus.STARTED) + UnderNet.router.stop(); + } + + @Override + public void onEventCalled(Event e) { + //router status event + if (e instanceof RouterStatusEvent) { + RouterStatusEvent statusEvent = (RouterStatusEvent) e; + + switch (statusEvent.newStatus) { + case STOPPED: + mainButton.setText(ResourceBundle.getBundle("language").getString("button_connect")); + break; + case STARTED: + mainButton.setText(ResourceBundle.getBundle("language").getString("button_disconnect")); + break; + case STOPPING: + mainButton.setEnabled(false); + break; + case STARTING: + mainButton.setEnabled(false); + new Thread(() -> drawLoop()).start(); + break; + } + } + } + + /** + * The draw loop logic. + */ + private void drawLoop() { + int FRAMES_PER_SECOND = 30; + int SKIP_TICKS = 1000 / FRAMES_PER_SECOND; + + long next_game_tick = System.currentTimeMillis(); + long sleep_time = 0; + + while (UnderNet.router != null && UnderNet.router.status != InterfaceStatus.STOPPED) { + this.frame.repaint(); + + next_game_tick += SKIP_TICKS; + sleep_time = next_game_tick - System.currentTimeMillis(); + if (sleep_time >= 0) { + try { + Thread.sleep(sleep_time); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + // Shit, we are running behind! + } + } + } + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + panel = new JPanel(); + panel.setLayout(new GridLayoutManager(8, 5, new Insets(0, 0, 0, 0), -1, -1)); + final Spacer spacer1 = new Spacer(); + panel.add(spacer1, new GridConstraints(1, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final Spacer spacer2 = new Spacer(); + panel.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + resourcePanel = new ResourcePanel(); + panel.add(resourcePanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + nodePanel = new NodePanel(); + panel.add(nodePanel.$$$getRootComponent$$$(), new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + tunnelPanel = new TunnelPanel(); + panel.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(4, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + mainButton = new JButton(); + mainButton.setText("Connect"); + panel.add(mainButton, new GridConstraints(6, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 50), null, 0, false)); + final Spacer spacer3 = new Spacer(); + panel.add(spacer3, new GridConstraints(5, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final Spacer spacer4 = new Spacer(); + panel.add(spacer4, new GridConstraints(3, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final JSeparator separator1 = new JSeparator(); + panel.add(separator1, new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, new Dimension(-1, 10), 0, false)); + progressBar = new JProgressBar(); + panel.add(progressBar, new GridConstraints(7, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final Spacer spacer5 = new Spacer(); + panel.add(spacer5, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + visualPanel = new VisualPanel(); + panel.add(visualPanel.$$$getRootComponent$$$(), new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(350, -1), null, 0, false)); + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form new file mode 100644 index 00000000..1bb302bf --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form @@ -0,0 +1,40 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java new file mode 100644 index 00000000..53b7b476 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -0,0 +1,99 @@ +package me.matoosh.undernet.standalone.uix; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; + +import javax.swing.*; +import java.awt.*; +import java.util.ResourceBundle; + +public class NodePanel { + private JPanel panel; + private JList nodesList; + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + panel = new JPanel(); + panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + final JLabel label1 = new JLabel(); + Font label1Font = this.$$$getFont$$$("Droid Sans", Font.BOLD, 18, label1.getFont()); + if (label1Font != null) label1.setFont(label1Font); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("title_nodes")); + label1.setVerticalAlignment(0); + panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JScrollPane scrollPane1 = new JScrollPane(); + panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + nodesList = new JList(); + nodesList.setDragEnabled(false); + final DefaultListModel defaultListModel1 = new DefaultListModel(); + nodesList.setModel(defaultListModel1); + nodesList.setSelectionMode(1); + scrollPane1.setViewportView(nodesList); + } + + /** + * @noinspection ALL + */ + private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) { + if (currentFont == null) return null; + String resultName; + if (fontName == null) { + resultName = currentFont.getName(); + } else { + Font testFont = new Font(fontName, Font.PLAIN, 10); + if (testFont.canDisplay('a') && testFont.canDisplay('1')) { + resultName = fontName; + } else { + resultName = currentFont.getName(); + } + } + return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize()); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form new file mode 100644 index 00000000..e5200ccd --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form @@ -0,0 +1,39 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java new file mode 100644 index 00000000..c5a21885 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -0,0 +1,96 @@ +package me.matoosh.undernet.standalone.uix; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; + +import javax.swing.*; +import java.awt.*; +import java.util.ResourceBundle; + +public class ResourcePanel { + private JPanel panel; + private JList resourceList; + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + panel = new JPanel(); + panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setForeground(new Color(-1)); + final JLabel label1 = new JLabel(); + Font label1Font = this.$$$getFont$$$("Droid Sans", Font.BOLD, 18, label1.getFont()); + if (label1Font != null) label1.setFont(label1Font); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("title_resources")); + panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JScrollPane scrollPane1 = new JScrollPane(); + panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + resourceList = new JList(); + resourceList.setSelectionMode(1); + scrollPane1.setViewportView(resourceList); + } + + /** + * @noinspection ALL + */ + private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) { + if (currentFont == null) return null; + String resultName; + if (fontName == null) { + resultName = currentFont.getName(); + } else { + Font testFont = new Font(fontName, Font.PLAIN, 10); + if (testFont.canDisplay('a') && testFont.canDisplay('1')) { + resultName = fontName; + } else { + resultName = currentFont.getName(); + } + } + return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize()); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form new file mode 100644 index 00000000..2a7dc116 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form @@ -0,0 +1,29 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java new file mode 100644 index 00000000..ad148438 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java @@ -0,0 +1,44 @@ +package me.matoosh.undernet.standalone.uix; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; + +import javax.swing.*; +import java.awt.*; + +public class TunnelPanel { + private JPanel panel; + private JList tunnelList; + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + panel = new JPanel(); + panel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setEnabled(true); + panel.setForeground(new Color(-1)); + final JScrollPane scrollPane1 = new JScrollPane(); + panel.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + tunnelList = new JList(); + scrollPane1.setViewportView(tunnelList); + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form new file mode 100644 index 00000000..d8054edc --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form @@ -0,0 +1,12 @@ + +
+ + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java new file mode 100644 index 00000000..4cae3f93 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java @@ -0,0 +1,36 @@ +package me.matoosh.undernet.standalone.uix; + +import javax.swing.*; + +public class VisualPanel { + private JPanel panel; + + private void createUIComponents() { + panel = new VisualPanelDraw(); + } + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + createUIComponents(); + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java new file mode 100644 index 00000000..860845b2 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -0,0 +1,39 @@ +package me.matoosh.undernet.standalone.uix; + +import me.matoosh.undernet.UnderNet; + +import javax.swing.*; +import java.awt.*; + +public class VisualPanelDraw extends JPanel { + + @Override + protected void paintComponent(Graphics g) { + //background + g.setColor(Color.black); + g.fillRect(0,0,this.getWidth(),this.getHeight()); + + //self + drawSelfNode(g); + } + + private void drawSelfNode(Graphics g) { + if(UnderNet.router != null) { + switch (UnderNet.router.status) { + case STOPPED: + g.setColor(Color.gray); + break; + case STARTED: + g.setColor(Color.green); + break; + default: + g.setColor(Color.orange); + break; + } + } + + int ovalHeight = 50; + int ovalWidth = 50; + g.fillOval(getWidth()/2 - ovalWidth/2, getHeight()/2 - ovalHeight/2, ovalWidth, ovalHeight); + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/AddNodeCacheDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java similarity index 98% rename from standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/AddNodeCacheDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java index 78565b11..693db6ab 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/AddNodeCacheDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java @@ -1,4 +1,4 @@ -package me.matoosh.undernet.standalone.ui.dialog; +package me.matoosh.undernet.standalone.uix.dialog; import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.p2p.cache.EntryNodeCache; diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/PullResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java similarity index 99% rename from standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/PullResourceDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java index 69672368..4d318498 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/PullResourceDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java @@ -1,4 +1,4 @@ -package me.matoosh.undernet.standalone.ui.dialog; +package me.matoosh.undernet.standalone.uix.dialog; import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.event.Event; diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/UploadResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java similarity index 98% rename from standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/UploadResourceDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java index 0e7f40c0..178b3e4b 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/ui/dialog/UploadResourceDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java @@ -1,4 +1,4 @@ -package me.matoosh.undernet.standalone.ui.dialog; +package me.matoosh.undernet.standalone.uix.dialog; import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.p2p.router.data.resource.FileResource; diff --git a/standalone/src/main/resources/language.properties b/standalone/src/main/resources/language.properties new file mode 100644 index 00000000..670da023 --- /dev/null +++ b/standalone/src/main/resources/language.properties @@ -0,0 +1,5 @@ +button_connect=Connect +button_disconnect=Disconnect +title_nodes=Nodes +title_resources=Resources +title_tunnels=Active Tunnels \ No newline at end of file diff --git a/standalone/src/main/resources/language_Polish.properties b/standalone/src/main/resources/language_Polish.properties new file mode 100644 index 00000000..e69de29b diff --git a/standalone/src/main/resources/language_Russian.properties b/standalone/src/main/resources/language_Russian.properties new file mode 100644 index 00000000..e69de29b From d8789e8b047c284fdd50b537c9e6e86874c62a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Tue, 8 Jan 2019 20:30:09 +0100 Subject: [PATCH 02/60] b --- .../undernet/standalone/uix/MainFrame.form | 4 +-- .../undernet/standalone/uix/MainFrame.java | 35 +++++++++++-------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form index 85243feb..25aefb6e 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form @@ -39,9 +39,7 @@ - - - + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 270cf90f..d59f58e5 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -6,6 +6,7 @@ import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.event.Event; import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.router.InterfaceStatus; import me.matoosh.undernet.standalone.UnderNetStandalone; @@ -46,6 +47,10 @@ public class MainFrame extends EventHandler { public static final int START_HEIGHT = 600; public static final int START_WIDTH = 950; + public MainFrame() { + mainButton.addActionListener(e -> onMainButtonClicked()); + } + public static void newInstance() { if (instance != null) { logger.warn("Can't open more than one Mainframe!"); @@ -65,23 +70,18 @@ public static void newInstance() { } private void initialize() { - registerButtons(); addMenus(); - } - - private void registerButtons() { - this.mainButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - onMainButtonClicked(); - } - }); + registerListener(); } private void addMenus() { } + private void registerListener() { + EventManager.registerHandler(this, RouterStatusEvent.class); + } + /** * Called when the main button is clicked. */ @@ -103,16 +103,23 @@ public void onEventCalled(Event e) { switch (statusEvent.newStatus) { case STOPPED: - mainButton.setText(ResourceBundle.getBundle("language").getString("button_connect")); + EventQueue.invokeLater(() -> { + mainButton.setEnabled(true); + mainButton.setText(ResourceBundle.getBundle("language").getString("button_connect")); + }); break; case STARTED: - mainButton.setText(ResourceBundle.getBundle("language").getString("button_disconnect")); + EventQueue.invokeLater(() -> { + mainButton.setEnabled(true); + mainButton.setText(ResourceBundle.getBundle("language").getString("button_disconnect")); + System.out.println(statusEvent.newStatus); + }); break; case STOPPING: - mainButton.setEnabled(false); + EventQueue.invokeLater(() -> mainButton.setEnabled(false)); break; case STARTING: - mainButton.setEnabled(false); + EventQueue.invokeLater(() -> mainButton.setEnabled(false)); new Thread(() -> drawLoop()).start(); break; } From 265cfa55b87eec171d7d331b1ee8ff0930edc210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 21:11:59 +0100 Subject: [PATCH 03/60] c --- .../undernet/p2p/router/data/NetworkID.java | 9 +- .../standalone/UnderNetStandalone.java | 73 ++++++++++------ .../undernet/standalone/uix/MainFrame.form | 27 ++---- .../undernet/standalone/uix/MainFrame.java | 73 ++++++---------- .../undernet/standalone/uix/NodePanel.form | 56 ++++++++---- .../undernet/standalone/uix/NodePanel.java | 58 ++++++++++--- .../standalone/uix/ResourcePanel.form | 29 ++++++- .../standalone/uix/ResourcePanel.java | 43 ++++++++- .../standalone/uix/VisualPanelDraw.java | 87 +++++++++++++++++-- .../src/main/resources/language.properties | 4 + 10 files changed, 325 insertions(+), 134 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/NetworkID.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/NetworkID.java index 182d3920..b5ba40c7 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/NetworkID.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/NetworkID.java @@ -35,6 +35,10 @@ public class NetworkID implements Serializable { * Used for distance measurement. */ private BigInteger bigIntegerValue; + /** + * The string value of data. + */ + private String stringValue; public NetworkID() { } @@ -127,7 +131,10 @@ public static String getStringValue(byte[] data) { * @return */ public String getStringValue() { - return getStringValue(this.data); + if(stringValue == null) { + stringValue = getStringValue(this.data); + } + return stringValue; } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java b/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java index b5be5ec3..d3cf962a 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/UnderNetStandalone.java @@ -50,6 +50,11 @@ public class UnderNetStandalone { */ private static StandaloneFileManager tmpFileMgr; + /** + * The undernet thread. + */ + private static Thread unetThread; + /** * The logger of the class. */ @@ -60,36 +65,34 @@ public static void main (String[] args) { setup(); //Starting the ui. - EventQueue.invokeLater(() -> { - MainFrame.newInstance(); - - //Creating network identity. - if(standaloneConfig.identity() == null || standaloneConfig.identity().isEmpty() || standaloneConfig.identity().equals("empty")) { - logger.info("No identity cached, creating a new identity!"); - UnderNetStandalone.setNetworkIdentity(null, null); - } else { - logger.info("Identity cached, loading identity {}!", standaloneConfig.identity()); - File currentIdentityFile = new File(standaloneConfig.identity()); - - try { - if (currentIdentityFile.exists()) { - NetworkIdentity identity = (NetworkIdentity) SerializationTools.readObjectFromFile(currentIdentityFile); - UnderNetStandalone.setNetworkIdentity(identity, currentIdentityFile); - } else { - logger.warn("Identity file: {}, doesn't exist! Creating a new identity!", currentIdentityFile); - } - } - catch (NullPointerException e) { - logger.warn("Error reading the identity file!", e); - currentIdentityFile.delete(); + EventQueue.invokeLater(() -> MainFrame.newInstance()); + + //Creating network identity. + if(standaloneConfig.identity() == null || standaloneConfig.identity().isEmpty() || standaloneConfig.identity().equals("empty")) { + logger.info("No identity cached, creating a new identity!"); + UnderNetStandalone.setNetworkIdentity(null, null); + } else { + logger.info("Identity cached, loading identity {}!", standaloneConfig.identity()); + File currentIdentityFile = new File(standaloneConfig.identity()); + + try { + if (currentIdentityFile.exists()) { + NetworkIdentity identity = (NetworkIdentity) SerializationTools.readObjectFromFile(currentIdentityFile); + UnderNetStandalone.setNetworkIdentity(identity, currentIdentityFile); + } else { + logger.warn("Identity file: {}, doesn't exist! Creating a new identity!", currentIdentityFile); } - finally { - if(networkIdentity == null) { - UnderNetStandalone.setNetworkIdentity(null, null); - } + } + catch (NullPointerException e) { + logger.warn("Error reading the identity file!", e); + currentIdentityFile.delete(); + } + finally { + if(networkIdentity == null) { + UnderNetStandalone.setNetworkIdentity(null, null); } } - }); + } } /** @@ -146,7 +149,6 @@ public static void setNetworkIdentity(NetworkIdentity identity, File identityFil //Setting the identity. logger.info("Setting the current UnderNet identity to: {}", identity.getNetworkId().getStringValue()); UnderNetStandalone.networkIdentity = identity; - MainFrame.instance.frame.setTitle("UnderNet - " + UnderNetStandalone.networkIdentity.getNetworkId().getStringValue()); //Save the changed identity. try { @@ -175,4 +177,19 @@ public static void setNetworkIdentity(NetworkIdentity identity, File identityFil } } + + /** + * Connects to UnderNet. + */ + public static void connect() { + unetThread = new Thread(() -> UnderNet.connect(networkIdentity)); + unetThread.start(); + } + + /** + * Disconnects from UnderNet. + */ + public static void disconnect() { + new Thread(() -> UnderNet.disconnect()).start(); + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form index 25aefb6e..18cad055 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form @@ -1,6 +1,6 @@
- + @@ -8,11 +8,6 @@ - - - - - @@ -30,12 +25,12 @@ - + - + - + @@ -43,25 +38,17 @@ - + - + - - - - - - - - - + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index d59f58e5..4cda9227 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -15,8 +15,6 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ResourceBundle; public class MainFrame extends EventHandler { @@ -48,6 +46,7 @@ public class MainFrame extends EventHandler { public static final int START_WIDTH = 950; public MainFrame() { + $$$setupUI$$$(); mainButton.addActionListener(e -> onMainButtonClicked()); } @@ -60,7 +59,7 @@ public static void newInstance() { instance = new MainFrame(); instance.frame = new JFrame("UnderNet"); - instance.frame.setContentPane(new MainFrame().panel); + instance.frame.setContentPane(instance.panel); instance.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); instance.initialize(); instance.frame.pack(); @@ -86,13 +85,10 @@ private void registerListener() { * Called when the main button is clicked. */ public void onMainButtonClicked() { - System.out.println("SSSSS"); - logger.info("Main button pressed!"); - if (UnderNet.router.status == InterfaceStatus.STOPPED) - UnderNet.router.start(UnderNetStandalone.networkIdentity); + UnderNetStandalone.connect(); else if (UnderNet.router.status == InterfaceStatus.STARTED) - UnderNet.router.stop(); + UnderNetStandalone.disconnect(); } @Override @@ -103,23 +99,19 @@ public void onEventCalled(Event e) { switch (statusEvent.newStatus) { case STOPPED: - EventQueue.invokeLater(() -> { - mainButton.setEnabled(true); - mainButton.setText(ResourceBundle.getBundle("language").getString("button_connect")); - }); + mainButton.setEnabled(true); + mainButton.setText(ResourceBundle.getBundle("language").getString("button_connect")); + this.frame.repaint(); break; case STARTED: - EventQueue.invokeLater(() -> { - mainButton.setEnabled(true); - mainButton.setText(ResourceBundle.getBundle("language").getString("button_disconnect")); - System.out.println(statusEvent.newStatus); - }); + instance.mainButton.setEnabled(true); + instance.mainButton.setText(ResourceBundle.getBundle("language").getString("button_disconnect")); break; case STOPPING: - EventQueue.invokeLater(() -> mainButton.setEnabled(false)); + mainButton.setEnabled(false); break; case STARTING: - EventQueue.invokeLater(() -> mainButton.setEnabled(false)); + mainButton.setEnabled(false); new Thread(() -> drawLoop()).start(); break; } @@ -137,29 +129,21 @@ private void drawLoop() { long sleep_time = 0; while (UnderNet.router != null && UnderNet.router.status != InterfaceStatus.STOPPED) { - this.frame.repaint(); - next_game_tick += SKIP_TICKS; sleep_time = next_game_tick - System.currentTimeMillis(); if (sleep_time >= 0) { try { + frame.repaint(); Thread.sleep(sleep_time); } catch (InterruptedException e) { e.printStackTrace(); } } else { - // Shit, we are running behind! + logger.warn("Can't keep up! Did the system time change, or is the node overloaded?"); } } } - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< @@ -168,31 +152,26 @@ private void drawLoop() { * @noinspection ALL */ private void $$$setupUI$$$() { + createUIComponents(); panel = new JPanel(); - panel.setLayout(new GridLayoutManager(8, 5, new Insets(0, 0, 0, 0), -1, -1)); + panel.setLayout(new GridLayoutManager(6, 5, new Insets(0, 0, 0, 0), -1, -1)); final Spacer spacer1 = new Spacer(); - panel.add(spacer1, new GridConstraints(1, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); - final Spacer spacer2 = new Spacer(); - panel.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + panel.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); resourcePanel = new ResourcePanel(); panel.add(resourcePanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); nodePanel = new NodePanel(); panel.add(nodePanel.$$$getRootComponent$$$(), new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); tunnelPanel = new TunnelPanel(); - panel.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(4, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); - mainButton = new JButton(); - mainButton.setText("Connect"); - panel.add(mainButton, new GridConstraints(6, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 50), null, 0, false)); + panel.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + panel.add(mainButton, new GridConstraints(4, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 50), null, 0, false)); + final Spacer spacer2 = new Spacer(); + panel.add(spacer2, new GridConstraints(3, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final Spacer spacer3 = new Spacer(); - panel.add(spacer3, new GridConstraints(5, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); - final Spacer spacer4 = new Spacer(); - panel.add(spacer4, new GridConstraints(3, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); - final JSeparator separator1 = new JSeparator(); - panel.add(separator1, new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, new Dimension(-1, 10), 0, false)); + panel.add(spacer3, new GridConstraints(1, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); progressBar = new JProgressBar(); - panel.add(progressBar, new GridConstraints(7, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - final Spacer spacer5 = new Spacer(); - panel.add(spacer5, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + panel.add(progressBar, new GridConstraints(5, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final Spacer spacer4 = new Spacer(); + panel.add(spacer4, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); visualPanel = new VisualPanel(); panel.add(visualPanel.$$$getRootComponent$$$(), new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(350, -1), null, 0, false)); } @@ -203,4 +182,8 @@ private void drawLoop() { public JComponent $$$getRootComponent$$$() { return panel; } + + private void createUIComponents() { + mainButton = new JButton(ResourceBundle.getBundle("language").getString("button_connect")); + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form index 1bb302bf..c8592be4 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form @@ -1,40 +1,58 @@ - + - + - + + + - + - + - - - - - - - + + + + + + - + - - + + + + - - - + + + + + + + + + - + + + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 53b7b476..54a76332 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -9,7 +9,8 @@ public class NodePanel { private JPanel panel; - private JList nodesList; + private JButton removeNodeButton; + private JButton addNodeButton; { // GUI initializer generated by IntelliJ IDEA GUI Designer @@ -27,21 +28,24 @@ public class NodePanel { */ private void $$$setupUI$$$() { panel = new JPanel(); - panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setMinimumSize(new Dimension(-1, -1)); + final JScrollPane scrollPane1 = new JScrollPane(); + panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); + panel.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + addNodeButton = new JButton(); + this.$$$loadButtonText$$$(addNodeButton, ResourceBundle.getBundle("language").getString("button_addNode")); + panel1.add(addNodeButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + removeNodeButton = new JButton(); + this.$$$loadButtonText$$$(removeNodeButton, ResourceBundle.getBundle("language").getString("button_removeNode")); + panel1.add(removeNodeButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label1 = new JLabel(); - Font label1Font = this.$$$getFont$$$("Droid Sans", Font.BOLD, 18, label1.getFont()); + Font label1Font = this.$$$getFont$$$("Droid Sans Mono", Font.BOLD, 16, label1.getFont()); if (label1Font != null) label1.setFont(label1Font); this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("title_nodes")); - label1.setVerticalAlignment(0); - panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - final JScrollPane scrollPane1 = new JScrollPane(); - panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); - nodesList = new JList(); - nodesList.setDragEnabled(false); - final DefaultListModel defaultListModel1 = new DefaultListModel(); - nodesList.setModel(defaultListModel1); - nodesList.setSelectionMode(1); - scrollPane1.setViewportView(nodesList); + panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } /** @@ -90,10 +94,38 @@ public class NodePanel { } } + /** + * @noinspection ALL + */ + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return panel; } + } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form index e5200ccd..99c781ef 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form @@ -1,6 +1,6 @@
- + @@ -29,11 +29,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index c5a21885..606bfccc 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -10,6 +10,8 @@ public class ResourcePanel { private JPanel panel; private JList resourceList; + private JButton publishButton; + private JButton pullButton; { // GUI initializer generated by IntelliJ IDEA GUI Designer @@ -27,7 +29,7 @@ public class ResourcePanel { */ private void $$$setupUI$$$() { panel = new JPanel(); - panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); panel.setForeground(new Color(-1)); final JLabel label1 = new JLabel(); Font label1Font = this.$$$getFont$$$("Droid Sans", Font.BOLD, 18, label1.getFont()); @@ -37,8 +39,19 @@ public class ResourcePanel { final JScrollPane scrollPane1 = new JScrollPane(); panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); resourceList = new JList(); + final DefaultListModel defaultListModel1 = new DefaultListModel(); + resourceList.setModel(defaultListModel1); resourceList.setSelectionMode(1); scrollPane1.setViewportView(resourceList); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); + panel.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + publishButton = new JButton(); + this.$$$loadButtonText$$$(publishButton, ResourceBundle.getBundle("language").getString("button_publishResource")); + panel1.add(publishButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + pullButton = new JButton(); + this.$$$loadButtonText$$$(pullButton, ResourceBundle.getBundle("language").getString("button_pullResource")); + panel1.add(pullButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } /** @@ -87,10 +100,38 @@ public class ResourcePanel { } } + /** + * @noinspection ALL + */ + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return panel; } + } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java index 860845b2..f36f0b49 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -1,39 +1,114 @@ package me.matoosh.undernet.standalone.uix; import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.channel.message.MessageReceivedEvent; +import me.matoosh.undernet.p2p.node.Node; +import me.matoosh.undernet.p2p.router.InterfaceStatus; import javax.swing.*; import java.awt.*; +import java.util.HashMap; public class VisualPanelDraw extends JPanel { + /** + * The nodes that recently sent messages to self. + */ + private HashMap recentlyReceived = new HashMap<>(); + + public VisualPanelDraw() { + registerCallbacks(); + } + + private void registerCallbacks() { + EventManager.registerHandler(new EventHandler() { + @Override + public void onEventCalled(Event e) { + MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) e; + + //coloring the line to the node. + recentlyReceived.put(messageReceivedEvent.forwarder, System.currentTimeMillis() + 1000); + } + }, MessageReceivedEvent.class); + } + @Override protected void paintComponent(Graphics g) { //background g.setColor(Color.black); g.fillRect(0,0,this.getWidth(),this.getHeight()); + //other + if(UnderNet.router.status == InterfaceStatus.STARTED) { + drawOtherNodes(g); + } + //self drawSelfNode(g); } + private void drawString(String str, int startIndex, int endIndex, int direction) { + + } + private void drawSelfNode(Graphics g) { + Color fill = Color.gray; if(UnderNet.router != null) { switch (UnderNet.router.status) { case STOPPED: - g.setColor(Color.gray); + fill = Color.gray; break; case STARTED: - g.setColor(Color.green); + fill = Color.green; break; default: - g.setColor(Color.orange); + fill = Color.orange; break; } } - int ovalHeight = 50; - int ovalWidth = 50; - g.fillOval(getWidth()/2 - ovalWidth/2, getHeight()/2 - ovalHeight/2, ovalWidth, ovalHeight); + int rad = 40; + g.setColor(fill); + g.fillOval(getWidth()/2 - rad/2, getHeight()/2 - rad/2, rad, rad); + g.setColor(Color.BLACK); + g.drawOval(getWidth()/2 - rad/2, getHeight()/2 - rad/2, rad, rad); } + + /** + * Draws representations of other nodes. + * @param g + */ + private void drawOtherNodes(Graphics g) { + double angle = (2 * Math.PI) / UnderNet.router.getRemoteNodes().size(); + int distance = 100; + int rad = 30; + + double currAngle = ((double)(System.currentTimeMillis() % 5000) / 5000d) * (2 * Math.PI); + for (int i = 0; i < UnderNet.router.getRemoteNodes().size(); i++) { + + int x = (int) (getWidth()/2 + distance * Math.cos(currAngle)); + int y = (int) (getHeight()/2 + distance * Math.sin(currAngle)); + + //line + Node n = UnderNet.router.getRemoteNodes().get(i); + if(recentlyReceived.containsKey(n)) { + g.setColor(Color.green); + + if(System.currentTimeMillis() > recentlyReceived.get(n)) recentlyReceived.remove(n); + } else { + g.setColor(Color.gray); + } + g.drawLine(getWidth()/2, getHeight()/2, x, y); + + //circle + g.setColor(Color.CYAN); + g.fillOval( x - rad/2, y - rad/2, rad, rad); + g.setColor(Color.BLACK); + g.drawOval(getWidth()/2 + x - rad/2, getHeight()/2 + y - rad/2, rad, rad); + + currAngle += angle; + } } } diff --git a/standalone/src/main/resources/language.properties b/standalone/src/main/resources/language.properties index 670da023..7bfa3844 100644 --- a/standalone/src/main/resources/language.properties +++ b/standalone/src/main/resources/language.properties @@ -1,5 +1,9 @@ +button_addNode=Add Node button_connect=Connect button_disconnect=Disconnect +button_publishResource=Publish +button_pullResource=Pull +button_removeNode=Remove Node title_nodes=Nodes title_resources=Resources title_tunnels=Active Tunnels \ No newline at end of file From b157cb90cb5eaf5022cd139145a6df3baf94b9ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 23:17:41 +0100 Subject: [PATCH 04/60] d --- .../event/router/RouterControlLoopEvent.java | 14 ++ .../matoosh/undernet/p2p/router/Router.java | 23 ++- .../p2p/router/data/message/MsgType.java | 2 + .../data/message/NetworkMessageManager.java | 5 + .../data/message/tunnel/MessageTunnel.java | 42 ++++- .../message/tunnel/MessageTunnelManager.java | 34 +++- .../tunnel/TunnelCloseRequestMessage.java | 11 ++ .../message/tunnel/TunnelControlMessage.java | 14 ++ .../undernet/standalone/uix/NodePanel.form | 9 +- .../undernet/standalone/uix/NodePanel.java | 167 +++++++++++++++++- .../standalone/uix/ResourcePanel.form | 2 + .../standalone/uix/ResourcePanel.java | 41 ++++- .../undernet/standalone/uix/TunnelPanel.form | 2 +- .../undernet/standalone/uix/TunnelPanel.java | 75 +++++++- .../standalone/uix/VisualPanelDraw.java | 12 +- .../src/main/resources/language.properties | 1 + 16 files changed, 422 insertions(+), 32 deletions(-) create mode 100644 shared/src/main/java/me/matoosh/undernet/event/router/RouterControlLoopEvent.java create mode 100644 shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelCloseRequestMessage.java create mode 100644 shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelControlMessage.java diff --git a/shared/src/main/java/me/matoosh/undernet/event/router/RouterControlLoopEvent.java b/shared/src/main/java/me/matoosh/undernet/event/router/RouterControlLoopEvent.java new file mode 100644 index 00000000..7a8a5652 --- /dev/null +++ b/shared/src/main/java/me/matoosh/undernet/event/router/RouterControlLoopEvent.java @@ -0,0 +1,14 @@ +package me.matoosh.undernet.event.router; + +import me.matoosh.undernet.p2p.router.Router; + +public class RouterControlLoopEvent extends RouterEvent { + public RouterControlLoopEvent(Router r) { + super(r); + } + + @Override + public void onCalled() { + + } +} diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 08ac042e..08224735 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -11,6 +11,7 @@ import me.matoosh.undernet.event.channel.message.ChannelMessageReceivedEvent; import me.matoosh.undernet.event.client.ClientExceptionEvent; import me.matoosh.undernet.event.client.ClientStatusEvent; +import me.matoosh.undernet.event.router.RouterControlLoopEvent; import me.matoosh.undernet.event.router.RouterErrorEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.event.server.ServerExceptionEvent; @@ -22,7 +23,9 @@ import me.matoosh.undernet.p2p.router.client.ClientNetworkMessageHandler; import me.matoosh.undernet.p2p.router.data.message.NetworkMessageManager; import me.matoosh.undernet.p2p.router.data.message.NodeNeighborsRequest; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelManager; +import me.matoosh.undernet.p2p.router.data.message.tunnel.TunnelControlMessage; import me.matoosh.undernet.p2p.router.data.resource.ResourceManager; import me.matoosh.undernet.p2p.router.server.Server; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -88,6 +91,11 @@ public class Router extends EventHandler { */ private int reconnectNum = 0; + /** + * The interval of the control loop. + */ + private final int controlLoopInterval = 30; + /** * Nodes the router is connected to at the moment. */ @@ -200,13 +208,21 @@ private void controlLoop() { //Checking if enough nodes are connected. ArrayList remote = getRemoteNodes(); - if (remote.size() > 0 && remote.size() < UnderNet.networkConfig.optNeighbors()) { //Request more neighbors. int id = UnderNet.secureRandom.nextInt(remote.size()); Node neighbor = remote.get(id); this.networkMessageManager.sendMessage(new NodeNeighborsRequest(), neighbor.getIdentity().getNetworkId()); } + + //Sending control message to tunnels. + for (MessageTunnel tunnel : + messageTunnelManager.messageTunnels) { + if((tunnel.getLastMessageTime() / 1000) > 2*controlLoopInterval) messageTunnelManager.closeTunnel(tunnel); + else tunnel.sendMessage(new TunnelControlMessage()); + } + + EventManager.callEvent(new RouterControlLoopEvent(this)); } /** @@ -274,7 +290,7 @@ public ArrayList getRemoteNodes() { ArrayList remote = new ArrayList<>(); for (Node n : connectedNodes) { - if (!Node.isLocalAddress(n.getAddress())) { + if (n.getAddress() != null && !Node.isLocalAddress(n.getAddress())) { remote.add(n); } } @@ -287,6 +303,7 @@ public ArrayList getRemoteNodes() { private void registerEvents() { //Router events EventManager.registerEvent(RouterStatusEvent.class); + EventManager.registerEvent(RouterControlLoopEvent.class); EventManager.registerEvent(RouterErrorEvent.class); //Connection events @@ -344,7 +361,7 @@ else if(e.getClass() == ChannelErrorEvent.class) { break; case STARTED: //Starting the control loop. - timerHandle = timer.scheduleAtFixedRate(() -> controlLoop(), 5, 30, TimeUnit.SECONDS); + timerHandle = timer.scheduleAtFixedRate(() -> controlLoop(), 5, controlLoopInterval, TimeUnit.SECONDS); break; case STOPPING: break; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java index 594ae32f..ee6b4b6a 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java @@ -18,6 +18,8 @@ public enum MsgType { RES_PULL((short) 7), //Contains the Network id of the pulled resource. RES_DATA((short) 8), //Data of a resource. RES_DATA_REQUEST((short) 9), //Confirm data of a resource. + TUNNEL_CONTROL((short) 10), //Check if a tunnel is alive. + TUNNEL_CLOSE_REQUEST((short) 11), //Request closure of a tunnel. UNKNOWN((short)-1); //Unknown msg type. public short id; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index cae8675c..37aa2304 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -176,6 +176,11 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { if(decryptMessage(message, tunnel)) { //Message can be read. message.deserialize(); + + //Set last message received on tunnel. + message.getTunnel().setLastMessageTime(System.currentTimeMillis()); + + //Calling received event. EventManager.callEvent(new MessageReceivedEvent(message, forwarder)); } else { //Message can't be read. diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 0a05092d..ca1c86ef 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -69,6 +69,11 @@ public class MessageTunnel { */ private MessageTunnelSide side; + /** + * The time that the last message was received from the tunnel. + */ + private long lastMessageTime; + //Messages /** * The list of messages awaiting sending. @@ -144,6 +149,14 @@ public void calcSharedSecret() { } } + /** + * Closes the tunnel. + */ + public void close() { + sendMessage(new TunnelCloseRequestMessage()); + UnderNet.router.messageTunnelManager.closeTunnel(this); + } + /** * Returns the shared secret of the tunnel. * @return @@ -280,6 +293,14 @@ public void setSide(MessageTunnelSide side) { this.side = side; } + public long getLastMessageTime() { + return this.lastMessageTime; + } + + public void setLastMessageTime(long currentTimeMillis) { + this.lastMessageTime = currentTimeMillis; + } + /** * Sends the specified message. * @param content @@ -302,13 +323,22 @@ public void sendMessage(MsgBase content) { @Override public String toString() { if(getTunnelState() == MessageTunnelState.HOSTED) { - return String.format("MT:{(%1$s) <-> (%2$s) <-> (%3$s)}", getOrigin(), Node.self, getDestination()); - } - if(getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { - return String.format("MT:{(%1$s) (%2$s)}", getOrigin(), getDestination()); + return String.format("{(%1$s) <-> (%2$s) <-> (%3$s)}", getOrigin(), Node.self, getDestination()); } - if(getTunnelState() == MessageTunnelState.ESTABLISHED) { - return String.format("MT:{(%1$s) <-> (%2$s)}", getOrigin(), getDestination()); + if(getSide() == MessageTunnelSide.ORIGIN) { + if(getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { + return String.format("{(%1$s) (%2$s)}", Node.self, getDestination()); + } + if(getTunnelState() == MessageTunnelState.ESTABLISHED) { + return String.format("{(%1$s) <-> (%2$s)}", Node.self, getDestination()); + } + } else { + if(getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { + return String.format("{(%1$s) (%2$s)}", getOrigin(), Node.self); + } + if(getTunnelState() == MessageTunnelState.ESTABLISHED) { + return String.format("{(%1$s) <-> (%2$s)}", getOrigin(), Node.self); + } } return "MT:{UNKNOWN}"; } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 6ae1fdf0..9885a278 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -3,6 +3,7 @@ import me.matoosh.undernet.event.Event; import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.channel.message.MessageReceivedEvent; +import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelClosedEvent; import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelEstablishedEvent; import me.matoosh.undernet.p2p.Manager; import me.matoosh.undernet.p2p.crypto.KeyTools; @@ -82,10 +83,35 @@ public void establishTunnel(MessageTunnel tunnel) { /** * Closes the given message tunnel. + * Doesn't send the close message, for that use the tunnel close() message. * @param tunnel */ public void closeTunnel(MessageTunnel tunnel) { - //TODO + logger.info("Closing tunnel: {}", tunnel); + tunnel.setPreviousNode(null); + tunnel.setNextNode(null); + messageTunnels.remove(tunnel); + if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { + for (MessageTunnel tunn : + messageTunnels) { + if(tunn.getDestination().equals(Node.self)) { + tunn.setPreviousNode(null); + tunn.setNextNode(null); + messageTunnels.remove(tunn); + } + } + } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { + for (MessageTunnel tunn : + messageTunnels) { + if(tunn.getOrigin().equals(Node.self)) { + tunn.setPreviousNode(null); + tunn.setNextNode(null); + messageTunnels.remove(tunn); + } + } + } + + EventManager.callEvent(new MessageTunnelClosedEvent(tunnel)); } @@ -148,6 +174,7 @@ public MessageTunnel getOrCreateTunnel(NetworkID origin, NetworkID destination, @Override protected void registerEvents() { EventManager.registerEvent(MessageTunnelEstablishedEvent.class); + EventManager.registerEvent(MessageTunnelClosedEvent.class); } @Override @@ -199,6 +226,11 @@ public void onEventCalled(Event e) { } catch (Exception e1) { logger.error("Couldn't decode the received public key for tunnel!", e1); } + } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_CLOSE_REQUEST) { + TunnelCloseRequestMessage closeRequestMessage = (TunnelCloseRequestMessage) messageReceivedEvent.networkMessage.getContent(); + closeTunnel(closeRequestMessage.getNetworkMessage().getTunnel()); + } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_CONTROL) { + messageReceivedEvent.networkMessage.getTunnel().sendMessage(new TunnelControlMessage()); } } } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelCloseRequestMessage.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelCloseRequestMessage.java new file mode 100644 index 00000000..1d0a33f2 --- /dev/null +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelCloseRequestMessage.java @@ -0,0 +1,11 @@ +package me.matoosh.undernet.p2p.router.data.message.tunnel; + +import me.matoosh.undernet.p2p.router.data.message.MsgBase; +import me.matoosh.undernet.p2p.router.data.message.MsgType; + +public class TunnelCloseRequestMessage extends MsgBase { + @Override + public MsgType getType() { + return MsgType.TUNNEL_CLOSE_REQUEST; + } +} diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelControlMessage.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelControlMessage.java new file mode 100644 index 00000000..b19a3395 --- /dev/null +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/TunnelControlMessage.java @@ -0,0 +1,14 @@ +package me.matoosh.undernet.p2p.router.data.message.tunnel; + +import me.matoosh.undernet.p2p.router.data.message.MsgBase; +import me.matoosh.undernet.p2p.router.data.message.MsgType; + +/** + * Message to check whether a tunnel is alive. + */ +public class TunnelControlMessage extends MsgBase { + @Override + public MsgType getType() { + return MsgType.TUNNEL_CONTROL; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form index c8592be4..5a68b022 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.form @@ -16,7 +16,14 @@
- + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 54a76332..a72168f1 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -2,21 +2,129 @@ import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.cache.NodeCacheAddedEvent; +import me.matoosh.undernet.event.cache.NodeCacheRemovedEvent; +import me.matoosh.undernet.event.channel.ChannelClosedEvent; +import me.matoosh.undernet.event.channel.ChannelCreatedEvent; +import me.matoosh.undernet.p2p.cache.EntryNodeCache; +import me.matoosh.undernet.p2p.node.Node; +import me.matoosh.undernet.p2p.router.InterfaceStatus; +import me.matoosh.undernet.standalone.uix.dialog.AddNodeCacheDialog; import javax.swing.*; import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; import java.util.ResourceBundle; -public class NodePanel { +public class NodePanel extends EventHandler { private JPanel panel; private JButton removeNodeButton; private JButton addNodeButton; + private JList nodeList; - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! + public NodePanel() { + //add node button clicked. $$$setupUI$$$(); + addNodeButton.addActionListener(e -> new AddNodeCacheDialog(MainFrame.instance.frame).setVisible(true)); + + //remove node button + removeNodeButton.addActionListener(e -> { + if (nodeList.getSelectedValue() == null) return; + Node selected = ((Node) nodeList.getSelectedValue()); + + //Disconnect or remove from cache. + if (selected.isConnected()) { + UnderNet.router.disconnectNode(selected); + } else { + EntryNodeCache.removeNode(selected); + } + }); + + //node list clicked + nodeList.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + JList list = (JList) e.getSource(); + if (e.getClickCount() == 2) { + //Double-click detected + if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { + int index = list.locationToIndex(e.getPoint()); + Node node = (Node) nodeList.getModel().getElementAt(index); + + //Checking if the node is connected. + if (!node.isConnected()) { + //Connecting to the node. + UnderNet.router.connectNode(node); + } + } + } else if (e.getClickCount() == 1) { + //Single click detected + int index = list.locationToIndex(e.getPoint()); + Node node = (Node) nodeList.getModel().getElementAt(index); + + //Checking if the node is connected. + if (node.isConnected()) { + NodePanel.this.removeNodeButton.setText(ResourceBundle.getBundle("language").getString("button_disconnectNode")); + } else { + NodePanel.this.removeNodeButton.setText(ResourceBundle.getBundle("language").getString("button_removeNode")); + } + } + } + }); + + //event listeners + registerListeners(); + + //refresh + refreshNodeList(); + } + + /** + * Registers event listeners. + */ + private void registerListeners() { + EventManager.registerHandler(this, NodeCacheAddedEvent.class); + EventManager.registerHandler(this, NodeCacheRemovedEvent.class); + EventManager.registerHandler(this, ChannelCreatedEvent.class); + EventManager.registerHandler(this, ChannelClosedEvent.class); + } + + @Override + public void onEventCalled(Event e) { + refreshNodeList(); + } + + /** + * Refreshes the nodes list based on the current node cache. + */ + private void refreshNodeList() { + if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { + //Using connected and cached nodes if the router has started. + ArrayList nodesToList = new ArrayList<>(); + nodesToList.addAll(UnderNet.router.getRemoteNodes()); + for (Node cachedNode : + EntryNodeCache.cachedNodes) { + boolean canAdd = true; + for (Node connectedNode : UnderNet.router.getRemoteNodes()) { + if (cachedNode.getAddress().equals(connectedNode.getAddress())) { + canAdd = false; + } + } + if (canAdd) { + nodesToList.add(cachedNode); + } + } + nodeList.setListData(nodesToList.toArray()); + } else { + //Using cached nodes if the router isn't online. + nodeList.setListData(EntryNodeCache.cachedNodes.toArray()); + } } /** @@ -27,11 +135,14 @@ public class NodePanel { * @noinspection ALL */ private void $$$setupUI$$$() { + createUIComponents(); panel = new JPanel(); panel.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); panel.setMinimumSize(new Dimension(-1, -1)); final JScrollPane scrollPane1 = new JScrollPane(); panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + nodeList.setSelectionMode(1); + scrollPane1.setViewportView(nodeList); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); @@ -128,4 +239,50 @@ public class NodePanel { return panel; } + private void createUIComponents() { + nodeList = new JList(new Node[]{}); + nodeList.setCellRenderer(new NodesListCellRenderer()); + } +} + +/** + * Renders elements within the nodes list. + */ +class NodesListCellRenderer extends DefaultListCellRenderer +{ + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value instanceof Node) { + Node node = (Node) value; + setText(node.toString()); + if(UnderNet.router.status == InterfaceStatus.STARTED) { + if (node.isConnected()) { + setBackground(Color.GREEN); + + //msg bg update + if(VisualPanelDraw.recentlyReceived.containsKey(node)) { + setBackground(Color.CYAN); + } + } else { + setBackground(Color.GRAY); + } + } + else if(UnderNet.router.status == InterfaceStatus.STARTING) { + setBackground(Color.ORANGE); + } + else { + setBackground(Color.GRAY); + } + + if (isSelected) { + setBackground(getBackground().darker()); + } + } else { + setText("UNKNOWN"); + setBackground(Color.GRAY); + } + return c; + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form index 99c781ef..024d181e 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form @@ -48,6 +48,7 @@
+ @@ -56,6 +57,7 @@
+ diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index 606bfccc..f90c124c 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -2,17 +2,29 @@ import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.router.RouterStatusEvent; import javax.swing.*; import java.awt.*; import java.util.ResourceBundle; -public class ResourcePanel { +public class ResourcePanel extends EventHandler { private JPanel panel; private JList resourceList; private JButton publishButton; private JButton pullButton; + public ResourcePanel() { + registerListeners(); + } + + private void registerListeners() { + EventManager.registerHandler(this, RouterStatusEvent.class); + } + { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< @@ -47,9 +59,11 @@ public class ResourcePanel { panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); publishButton = new JButton(); + publishButton.setEnabled(false); this.$$$loadButtonText$$$(publishButton, ResourceBundle.getBundle("language").getString("button_publishResource")); panel1.add(publishButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); pullButton = new JButton(); + pullButton.setEnabled(false); this.$$$loadButtonText$$$(pullButton, ResourceBundle.getBundle("language").getString("button_pullResource")); panel1.add(pullButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } @@ -134,4 +148,29 @@ public class ResourcePanel { return panel; } + @Override + public void onEventCalled(Event e) { + if (e instanceof RouterStatusEvent) { + RouterStatusEvent statusEvent = (RouterStatusEvent) e; + + switch (statusEvent.newStatus) { + case STARTED: + publishButton.setEnabled(true); + pullButton.setEnabled(true); + break; + case STOPPED: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + case STARTING: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + case STOPPING: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + } + } + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form index 2a7dc116..2188b640 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form @@ -18,7 +18,7 @@ - + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java index ad148438..25aefae1 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java @@ -2,19 +2,57 @@ import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelClosedEvent; +import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelEstablishedEvent; +import me.matoosh.undernet.event.router.RouterStatusEvent; +import me.matoosh.undernet.p2p.router.InterfaceStatus; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; import javax.swing.*; import java.awt.*; -public class TunnelPanel { +/** + * Represents a message tunnel panel. + */ +public class TunnelPanel extends EventHandler { private JPanel panel; private JList tunnelList; - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! + + public TunnelPanel() { $$$setupUI$$$(); + registerListeners(); + } + + /** + * Registers event listeners. + */ + private void registerListeners() { + EventManager.registerHandler(this, MessageTunnelEstablishedEvent.class); + EventManager.registerHandler(this, MessageTunnelClosedEvent.class); + EventManager.registerHandler(this, RouterStatusEvent.class); + } + + private void createUIComponents() { + tunnelList = new JList(new MessageTunnel[]{}); + tunnelList.setCellRenderer(new TunnelListCellRenderer()); + } + + @Override + public void onEventCalled(Event e) { + refreshTunnelList(); + } + + private void refreshTunnelList() { + if (UnderNet.router.status == InterfaceStatus.STARTED) { + this.tunnelList.setListData(UnderNet.router.messageTunnelManager.messageTunnels.toArray()); + } else { + this.tunnelList.setListData(new MessageTunnel[0]); + } } /** @@ -25,13 +63,13 @@ public class TunnelPanel { * @noinspection ALL */ private void $$$setupUI$$$() { + createUIComponents(); panel = new JPanel(); panel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); panel.setEnabled(true); panel.setForeground(new Color(-1)); final JScrollPane scrollPane1 = new JScrollPane(); panel.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); - tunnelList = new JList(); scrollPane1.setViewportView(tunnelList); } @@ -41,4 +79,29 @@ public class TunnelPanel { public JComponent $$$getRootComponent$$$() { return panel; } + +} +/** + * Renders elements within the nodes list. + */ +class TunnelListCellRenderer extends DefaultListCellRenderer +{ + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value instanceof MessageTunnel) { + MessageTunnel tunnel = (MessageTunnel) value; + setText(tunnel.toString()); + setBackground(Color.GREEN); + + if (isSelected) { + setBackground(getBackground().darker()); + } + } else { + setText("UNKNOWN"); + setBackground(Color.GRAY); + } + return c; + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java index f36f0b49..c13abe62 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -17,7 +17,7 @@ public class VisualPanelDraw extends JPanel { /** * The nodes that recently sent messages to self. */ - private HashMap recentlyReceived = new HashMap<>(); + public static HashMap recentlyReceived = new HashMap<>(); public VisualPanelDraw() { registerCallbacks(); @@ -50,12 +50,8 @@ protected void paintComponent(Graphics g) { drawSelfNode(g); } - private void drawString(String str, int startIndex, int endIndex, int direction) { - - } - private void drawSelfNode(Graphics g) { - Color fill = Color.gray; + Color fill = Color.GRAY; if(UnderNet.router != null) { switch (UnderNet.router.status) { case STOPPED: @@ -94,11 +90,11 @@ private void drawOtherNodes(Graphics g) { //line Node n = UnderNet.router.getRemoteNodes().get(i); if(recentlyReceived.containsKey(n)) { - g.setColor(Color.green); + g.setColor(Color.CYAN); if(System.currentTimeMillis() > recentlyReceived.get(n)) recentlyReceived.remove(n); } else { - g.setColor(Color.gray); + g.setColor(Color.GRAY); } g.drawLine(getWidth()/2, getHeight()/2, x, y); diff --git a/standalone/src/main/resources/language.properties b/standalone/src/main/resources/language.properties index 7bfa3844..02b1dc25 100644 --- a/standalone/src/main/resources/language.properties +++ b/standalone/src/main/resources/language.properties @@ -1,6 +1,7 @@ button_addNode=Add Node button_connect=Connect button_disconnect=Disconnect +button_disconnectNode=Disconnect Node button_publishResource=Publish button_pullResource=Pull button_removeNode=Remove Node From 7a9f6a0c11f925d7538fed7ad04b6aaed9c599ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 23:23:58 +0100 Subject: [PATCH 05/60] Tunnel auto closing due to inactivity added --- .../src/main/java/me/matoosh/undernet/p2p/router/Router.java | 4 ++-- .../p2p/router/data/message/tunnel/MessageTunnel.java | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 08224735..1d4c81c6 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -94,7 +94,7 @@ public class Router extends EventHandler { /** * The interval of the control loop. */ - private final int controlLoopInterval = 30; + public static final int controlLoopInterval = 30; /** * Nodes the router is connected to at the moment. @@ -218,7 +218,7 @@ private void controlLoop() { //Sending control message to tunnels. for (MessageTunnel tunnel : messageTunnelManager.messageTunnels) { - if((tunnel.getLastMessageTime() / 1000) > 2*controlLoopInterval) messageTunnelManager.closeTunnel(tunnel); + if(System.currentTimeMillis() > tunnel.getLastMessageTime() + 2*controlLoopInterval*1000) messageTunnelManager.closeTunnel(tunnel); else tunnel.sendMessage(new TunnelControlMessage()); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index ca1c86ef..623f387f 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -3,6 +3,7 @@ import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.p2p.crypto.KeyTools; import me.matoosh.undernet.p2p.node.Node; +import me.matoosh.undernet.p2p.router.Router; import me.matoosh.undernet.p2p.router.data.NetworkID; import me.matoosh.undernet.p2p.router.data.message.MsgBase; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; @@ -99,6 +100,7 @@ public MessageTunnel(NetworkID origin, NetworkID destination) { this.destination = destination; this.origin = origin; this.side = MessageTunnelSide.UNDEFINED; + this.lastMessageTime = System.currentTimeMillis() + 2 * Router.controlLoopInterval; } /** * Creates a message tunnel. @@ -109,6 +111,7 @@ public MessageTunnel(NetworkID origin, NetworkID destination, MessageTunnelSide this.destination = destination; this.origin = origin; this.side = side; + this.lastMessageTime = System.currentTimeMillis() + 2 * Router.controlLoopInterval; } public PublicKey getOtherPublicKey() { From e5b31ab89004f041732a352090230bbf339b1aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 23:25:37 +0100 Subject: [PATCH 06/60] Tunnel expieration fixes --- .../p2p/router/data/message/tunnel/MessageTunnelManager.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 9885a278..959373c5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -229,8 +229,6 @@ public void onEventCalled(Event e) { } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_CLOSE_REQUEST) { TunnelCloseRequestMessage closeRequestMessage = (TunnelCloseRequestMessage) messageReceivedEvent.networkMessage.getContent(); closeTunnel(closeRequestMessage.getNetworkMessage().getTunnel()); - } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_CONTROL) { - messageReceivedEvent.networkMessage.getTunnel().sendMessage(new TunnelControlMessage()); } } } From f72c74509b6247a037e93cc16a61f25ccec44dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 23:46:23 +0100 Subject: [PATCH 07/60] Auto closing tunnels on disconnect. --- .../matoosh/undernet/p2p/router/Router.java | 5 ++-- .../client/ClientNetworkMessageHandler.java | 17 +++++++++++ .../transfer/FileTransferHandler.java | 12 ++++++++ .../server/ServerNetworkMessageHandler.java | 17 +++++++++++ .../undernet/standalone/uix/MainFrame.java | 29 +++++++++++++++---- 5 files changed, 73 insertions(+), 7 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 1d4c81c6..22f74db0 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -288,8 +288,9 @@ public ArrayList getConnectedNodes() { */ public ArrayList getRemoteNodes() { ArrayList remote = new ArrayList<>(); - for (Node n : - connectedNodes) { + for (int i = 0; i < connectedNodes.size(); i++) { + Node n = connectedNodes.get(i); + if (n.getAddress() != null && !Node.isLocalAddress(n.getAddress())) { remote.add(n); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java index 5d9f0975..c1c4f9eb 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java @@ -1,5 +1,7 @@ package me.matoosh.undernet.p2p.router.client; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,6 +84,21 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { serverNode.channel = null; client.router.getConnectedNodes().remove(serverNode); + //Removing tunnels with node. + for (int i = 0; i < client.router.messageTunnelManager.messageTunnels.size(); i++) { + MessageTunnel tunnel = client.router.messageTunnelManager.messageTunnels.get(i); + if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { + if(tunnel.getDestination().equals(serverNode.getIdentity().getNetworkId())) { + client.router.messageTunnelManager.closeTunnel(tunnel); + } + } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { + if(tunnel.getOrigin().equals(serverNode.getIdentity().getNetworkId())) { + client.router.messageTunnelManager.closeTunnel(tunnel); + } + } + + } + //Calling the channel closed event. EventManager.callEvent(new ChannelClosedEvent(ctx.channel(), false)); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index be99c863..c0a1faed 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -229,4 +229,16 @@ public void onDataReceived(ResourceDataMessage dataMessage) { } } } + + public long getFileLength() { + return fileLength; + } + + public int getWritten() { + return written; + } + + public int getSent() { + return sent; + } } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java index fc96f532..c8ca8667 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java @@ -10,6 +10,8 @@ import me.matoosh.undernet.event.channel.message.ChannelMessageReceivedEvent; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,6 +81,21 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { clientNode.channel = null; server.router.getConnectedNodes().remove(clientNode); + //Removing tunnels with node. + for (int i = 0; i < server.router.messageTunnelManager.messageTunnels.size(); i++) { + MessageTunnel tunnel = server.router.messageTunnelManager.messageTunnels.get(i); + if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { + if(tunnel.getDestination().equals(clientNode.getIdentity().getNetworkId())) { + server.router.messageTunnelManager.closeTunnel(tunnel); + } + } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { + if(tunnel.getOrigin().equals(clientNode.getIdentity().getNetworkId())) { + server.router.messageTunnelManager.closeTunnel(tunnel); + } + } + + } + //Calling the channel closed event. EventManager.callEvent(new ChannelClosedEvent(ctx.channel(), true)); } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 4cda9227..8b4a3e6c 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -7,8 +7,12 @@ import me.matoosh.undernet.event.Event; import me.matoosh.undernet.event.EventHandler; import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferDataReceivedEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferDataSentEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.router.InterfaceStatus; +import me.matoosh.undernet.p2p.router.data.resource.transfer.FileTransferHandler; +import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; import me.matoosh.undernet.standalone.UnderNetStandalone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -69,16 +73,13 @@ public static void newInstance() { } private void initialize() { - addMenus(); registerListener(); } - private void addMenus() { - - } - private void registerListener() { EventManager.registerHandler(this, RouterStatusEvent.class); + EventManager.registerHandler(this, ResourceTransferDataReceivedEvent.class); + EventManager.registerHandler(this, ResourceTransferDataSentEvent.class); } /** @@ -115,6 +116,24 @@ public void onEventCalled(Event e) { new Thread(() -> drawLoop()).start(); break; } + } else if(e instanceof ResourceTransferDataReceivedEvent) { + ResourceTransferDataReceivedEvent dataReceivedEvent = (ResourceTransferDataReceivedEvent)e; + ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; + + if(transferHandler instanceof FileTransferHandler) { + FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; + + progressBar.setValue((int) (((float)fileTransferHandler.getWritten())/((float) fileTransferHandler.getFileLength()) * 100f)); + } + } else if(e instanceof ResourceTransferDataSentEvent) { + ResourceTransferDataSentEvent dataReceivedEvent = (ResourceTransferDataSentEvent)e; + ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; + + if(transferHandler instanceof FileTransferHandler) { + FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; + + progressBar.setValue((int) (((float)fileTransferHandler.getSent())/((float) fileTransferHandler.getFileLength()) * 100f)); + } } } From 7732e0fa4f4b1a999d97c46418230df74cef7d98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Wed, 9 Jan 2019 23:57:09 +0100 Subject: [PATCH 08/60] Better disconnect handling --- .../client/ClientNetworkMessageHandler.java | 21 +++---------------- .../message/tunnel/MessageTunnelManager.java | 13 ++++++++++++ .../server/ServerNetworkMessageHandler.java | 16 +------------- .../undernet/standalone/uix/MainFrame.java | 16 +++++++------- 4 files changed, 25 insertions(+), 41 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java index c1c4f9eb..54876cf5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java @@ -1,10 +1,5 @@ package me.matoosh.undernet.p2p.router.client; -import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; -import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.AttributeKey; @@ -15,6 +10,8 @@ import me.matoosh.undernet.event.channel.message.ChannelMessageReceivedEvent; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; @@ -85,19 +82,7 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { client.router.getConnectedNodes().remove(serverNode); //Removing tunnels with node. - for (int i = 0; i < client.router.messageTunnelManager.messageTunnels.size(); i++) { - MessageTunnel tunnel = client.router.messageTunnelManager.messageTunnels.get(i); - if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { - if(tunnel.getDestination().equals(serverNode.getIdentity().getNetworkId())) { - client.router.messageTunnelManager.closeTunnel(tunnel); - } - } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { - if(tunnel.getOrigin().equals(serverNode.getIdentity().getNetworkId())) { - client.router.messageTunnelManager.closeTunnel(tunnel); - } - } - - } + client.router.messageTunnelManager.closeTunnelsOnDisconnect(serverNode); //Calling the channel closed event. EventManager.callEvent(new ChannelClosedEvent(ctx.channel(), false)); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 959373c5..8e17c7cc 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -81,6 +81,19 @@ public void establishTunnel(MessageTunnel tunnel) { sendTunnelRequest(tunnel); } + /** + * Closes tunnels when a node disconnects. + * @param disconnected + */ + public void closeTunnelsOnDisconnect(Node disconnected) { + for (MessageTunnel tunnel : + messageTunnels) { + if (tunnel.getNextNode() == disconnected || tunnel.getPreviousNode() == disconnected) { + closeTunnel(tunnel); + } + } + } + /** * Closes the given message tunnel. * Doesn't send the close message, for that use the tunnel close() message. diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java index c8ca8667..c0357e11 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java @@ -10,8 +10,6 @@ import me.matoosh.undernet.event.channel.message.ChannelMessageReceivedEvent; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; -import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; -import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,19 +80,7 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { server.router.getConnectedNodes().remove(clientNode); //Removing tunnels with node. - for (int i = 0; i < server.router.messageTunnelManager.messageTunnels.size(); i++) { - MessageTunnel tunnel = server.router.messageTunnelManager.messageTunnels.get(i); - if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { - if(tunnel.getDestination().equals(clientNode.getIdentity().getNetworkId())) { - server.router.messageTunnelManager.closeTunnel(tunnel); - } - } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { - if(tunnel.getOrigin().equals(clientNode.getIdentity().getNetworkId())) { - server.router.messageTunnelManager.closeTunnel(tunnel); - } - } - - } + server.router.messageTunnelManager.closeTunnelsOnDisconnect(clientNode); //Calling the channel closed event. EventManager.callEvent(new ChannelClosedEvent(ctx.channel(), true)); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 8b4a3e6c..bca43349 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -116,23 +116,23 @@ public void onEventCalled(Event e) { new Thread(() -> drawLoop()).start(); break; } - } else if(e instanceof ResourceTransferDataReceivedEvent) { - ResourceTransferDataReceivedEvent dataReceivedEvent = (ResourceTransferDataReceivedEvent)e; + } else if (e instanceof ResourceTransferDataReceivedEvent) { + ResourceTransferDataReceivedEvent dataReceivedEvent = (ResourceTransferDataReceivedEvent) e; ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; - if(transferHandler instanceof FileTransferHandler) { + if (transferHandler instanceof FileTransferHandler) { FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; - progressBar.setValue((int) (((float)fileTransferHandler.getWritten())/((float) fileTransferHandler.getFileLength()) * 100f)); + progressBar.setValue((int) (((float) fileTransferHandler.getWritten()) / ((float) fileTransferHandler.getFileLength()) * 100f)); } - } else if(e instanceof ResourceTransferDataSentEvent) { - ResourceTransferDataSentEvent dataReceivedEvent = (ResourceTransferDataSentEvent)e; + } else if (e instanceof ResourceTransferDataSentEvent) { + ResourceTransferDataSentEvent dataReceivedEvent = (ResourceTransferDataSentEvent) e; ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; - if(transferHandler instanceof FileTransferHandler) { + if (transferHandler instanceof FileTransferHandler) { FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; - progressBar.setValue((int) (((float)fileTransferHandler.getSent())/((float) fileTransferHandler.getFileLength()) * 100f)); + progressBar.setValue((int) (((float) fileTransferHandler.getSent()) / ((float) fileTransferHandler.getFileLength()) * 100f)); } } } From 3c41c3ed13e94614112202ce56c7e5cb85ccc27e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Thu, 10 Jan 2019 00:16:35 +0100 Subject: [PATCH 09/60] sss --- .../router/data/message/NetworkMessageManager.java | 1 + .../data/message/tunnel/MessageTunnelManager.java | 12 +++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 37aa2304..433b40a3 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -226,6 +226,7 @@ public void onEventCalled(Event e) { ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent)e; NetworkMessage message = messageReceivedEvent.message; + System.out.println("DD " + messageReceivedEvent.remoteNode); forwardMessage(message, messageReceivedEvent.remoteNode); } else if (e instanceof MessageTunnelEstablishedEvent) { MessageTunnelEstablishedEvent messageTunnelEstablishedEvent = (MessageTunnelEstablishedEvent)e; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 8e17c7cc..23df4b8d 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -86,12 +86,18 @@ public void establishTunnel(MessageTunnel tunnel) { * @param disconnected */ public void closeTunnelsOnDisconnect(Node disconnected) { - for (MessageTunnel tunnel : - messageTunnels) { + ArrayList toClose = new ArrayList<>(); + for (int i = 0; i < messageTunnels.size(); i++) { + MessageTunnel tunnel = messageTunnels.get(i); if (tunnel.getNextNode() == disconnected || tunnel.getPreviousNode() == disconnected) { - closeTunnel(tunnel); + toClose.add(tunnel); } } + + for (MessageTunnel tunnel : + toClose) { + closeTunnel(tunnel); + } } /** From 8ba6b7d547cf6963bfe797fc19fbc000006ce7e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Thu, 10 Jan 2019 00:19:59 +0100 Subject: [PATCH 10/60] fixed disconnection clearup --- .../p2p/router/data/message/NetworkMessageManager.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 433b40a3..db006f50 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -225,8 +225,7 @@ public void onEventCalled(Event e) { if(e instanceof ChannelMessageReceivedEvent) { //A network message was received. ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent)e; NetworkMessage message = messageReceivedEvent.message; - - System.out.println("DD " + messageReceivedEvent.remoteNode); + forwardMessage(message, messageReceivedEvent.remoteNode); } else if (e instanceof MessageTunnelEstablishedEvent) { MessageTunnelEstablishedEvent messageTunnelEstablishedEvent = (MessageTunnelEstablishedEvent)e; From b1d5658d305c6f16b1215c7778f416859c7f2a0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 17:44:23 +0100 Subject: [PATCH 11/60] Resource Panel additions --- .../matoosh/undernet/p2p/router/Router.java | 5 +- .../data/message/NetworkMessageManager.java | 2 +- .../router/data/resource/ResourceManager.java | 2 +- .../undernet/standalone/uix/ControlIcon.java | 37 +++++++++++ .../undernet/standalone/uix/MainFrame.java | 2 + .../undernet/standalone/uix/NodePanel.java | 4 +- .../standalone/uix/ResourcePanel.form | 2 +- .../standalone/uix/ResourcePanel.java | 66 ++++++++++++++++--- ...odeCacheDialog.java => NodeAddDialog.java} | 8 +-- ...Dialog.java => ResourcePublishDialog.java} | 14 ++-- ...rceDialog.java => ResourcePullDialog.java} | 14 ++-- 11 files changed, 124 insertions(+), 32 deletions(-) create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/ControlIcon.java rename standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/{AddNodeCacheDialog.java => NodeAddDialog.java} (92%) rename standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/{UploadResourceDialog.java => ResourcePublishDialog.java} (78%) rename standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/{PullResourceDialog.java => ResourcePullDialog.java} (93%) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 22f74db0..4e367e19 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -25,6 +25,7 @@ import me.matoosh.undernet.p2p.router.data.message.NodeNeighborsRequest; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelManager; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import me.matoosh.undernet.p2p.router.data.message.tunnel.TunnelControlMessage; import me.matoosh.undernet.p2p.router.data.resource.ResourceManager; import me.matoosh.undernet.p2p.router.server.Server; @@ -218,7 +219,9 @@ private void controlLoop() { //Sending control message to tunnels. for (MessageTunnel tunnel : messageTunnelManager.messageTunnels) { - if(System.currentTimeMillis() > tunnel.getLastMessageTime() + 2*controlLoopInterval*1000) messageTunnelManager.closeTunnel(tunnel); + if(tunnel.getSide() == MessageTunnelSide.ORIGIN && tunnel.getNextNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); + else if(tunnel.getSide() == MessageTunnelSide.DESTINATION && tunnel.getPreviousNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); + else if(System.currentTimeMillis() > tunnel.getLastMessageTime() + 2*controlLoopInterval*1000) messageTunnelManager.closeTunnel(tunnel); else tunnel.sendMessage(new TunnelControlMessage()); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index db006f50..37aa2304 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -225,7 +225,7 @@ public void onEventCalled(Event e) { if(e instanceof ChannelMessageReceivedEvent) { //A network message was received. ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent)e; NetworkMessage message = messageReceivedEvent.message; - + forwardMessage(message, messageReceivedEvent.remoteNode); } else if (e instanceof MessageTunnelEstablishedEvent) { MessageTunnelEstablishedEvent messageTunnelEstablishedEvent = (MessageTunnelEstablishedEvent)e; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 7fc301c3..2f8fcda9 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -349,4 +349,4 @@ protected void registerHandlers() { EventManager.registerHandler(this, ConnectionEstablishedEvent.class); EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); } -} +} \ No newline at end of file diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ControlIcon.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ControlIcon.java new file mode 100644 index 00000000..fef992a6 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ControlIcon.java @@ -0,0 +1,37 @@ +package me.matoosh.undernet.standalone.uix; + +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.router.RouterControlLoopEvent; + +import javax.swing.*; +import java.awt.*; + +/** + * Represents the corner control icon. + */ +public class ControlIcon extends JPanel { + + private long greenTill; + + public ControlIcon () { + this.setSize(this.getHeight(), this.getHeight()); + registerListeners(); + } + + private void registerListeners() { + EventManager.registerHandler(new EventHandler() { + @Override + public void onEventCalled(Event e) { + greenTill = System.currentTimeMillis() + 1000; + } + }, RouterControlLoopEvent.class); + } + + @Override + protected void paintComponent(Graphics g) { + g.drawRect(0,0,getWidth(),getHeight()); + g.fillOval(0,0, getWidth(), getHeight()); + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index bca43349..966e5549 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -45,6 +45,7 @@ public class MainFrame extends EventHandler { private JProgressBar progressBar; private JButton mainButton; private VisualPanel visualPanel; + private ControlIcon controlIcon1; public static final int START_HEIGHT = 600; public static final int START_WIDTH = 950; @@ -203,6 +204,7 @@ private void drawLoop() { } private void createUIComponents() { + controlIcon1 = new ControlIcon(); mainButton = new JButton(ResourceBundle.getBundle("language").getString("button_connect")); } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index a72168f1..3f8956f2 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -13,7 +13,7 @@ import me.matoosh.undernet.p2p.cache.EntryNodeCache; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.InterfaceStatus; -import me.matoosh.undernet.standalone.uix.dialog.AddNodeCacheDialog; +import me.matoosh.undernet.standalone.uix.dialog.NodeAddDialog; import javax.swing.*; import java.awt.*; @@ -31,7 +31,7 @@ public class NodePanel extends EventHandler { public NodePanel() { //add node button clicked. $$$setupUI$$$(); - addNodeButton.addActionListener(e -> new AddNodeCacheDialog(MainFrame.instance.frame).setVisible(true)); + addNodeButton.addActionListener(e -> new NodeAddDialog(MainFrame.instance.frame).setVisible(true)); //remove node button removeNodeButton.addActionListener(e -> { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form index 024d181e..7c9bf69a 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.form @@ -26,7 +26,7 @@ - + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index f90c124c..87074496 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -2,13 +2,24 @@ import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; +import me.matoosh.undernet.UnderNet; import me.matoosh.undernet.event.Event; import me.matoosh.undernet.event.EventHandler; import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferErrorEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; +import me.matoosh.undernet.p2p.router.data.resource.Resource; +import me.matoosh.undernet.standalone.uix.dialog.ResourcePublishDialog; +import me.matoosh.undernet.standalone.uix.dialog.ResourcePullDialog; import javax.swing.*; import java.awt.*; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; import java.util.ResourceBundle; public class ResourcePanel extends EventHandler { @@ -18,18 +29,39 @@ public class ResourcePanel extends EventHandler { private JButton pullButton; public ResourcePanel() { + $$$setupUI$$$(); registerListeners(); + publishButton.addActionListener(e -> { + new ResourcePublishDialog(MainFrame.instance.frame).setVisible(true); + }); + pullButton.addActionListener(e -> { + new ResourcePullDialog(MainFrame.instance.frame).setVisible(true); + }); + resourceList.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + //Res + int index = resourceList.locationToIndex(e.getPoint()); + Resource res = (Resource) resourceList.getModel().getElementAt(index); + if (res == null) return; + + //Double clicked on resource. + StringSelection stringSelection = new StringSelection(res.getNetworkID().getStringValue()); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, null); + } + } + }); + + refreshList(); } private void registerListeners() { EventManager.registerHandler(this, RouterStatusEvent.class); - } - - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); + EventManager.registerHandler(this, ResourceTransferStartedEvent.class); + EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); + EventManager.registerHandler(this, ResourceTransferErrorEvent.class); } /** @@ -40,6 +72,7 @@ private void registerListeners() { * @noinspection ALL */ private void $$$setupUI$$$() { + createUIComponents(); panel = new JPanel(); panel.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); panel.setForeground(new Color(-1)); @@ -50,7 +83,6 @@ private void registerListeners() { panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JScrollPane scrollPane1 = new JScrollPane(); panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); - resourceList = new JList(); final DefaultListModel defaultListModel1 = new DefaultListModel(); resourceList.setModel(defaultListModel1); resourceList.setSelectionMode(1); @@ -148,6 +180,10 @@ private void registerListeners() { return panel; } + private void refreshList() { + resourceList.setListData(UnderNet.router.resourceManager.getStoredFileResources().toArray()); + } + @Override public void onEventCalled(Event e) { if (e instanceof RouterStatusEvent) { @@ -171,6 +207,20 @@ public void onEventCalled(Event e) { pullButton.setEnabled(false); break; } + } else if (e instanceof ResourceTransferStartedEvent) { + publishButton.setEnabled(false); + pullButton.setEnabled(false); + } else if (e instanceof ResourceTransferFinishedEvent) { + publishButton.setEnabled(true); + pullButton.setEnabled(true); + refreshList(); + } else if (e instanceof ResourceTransferErrorEvent) { + publishButton.setEnabled(true); + pullButton.setEnabled(true); } } + + private void createUIComponents() { + resourceList = new JList(new Resource[0]); + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java similarity index 92% rename from standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java index 693db6ab..4709548b 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeCacheDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java @@ -15,13 +15,13 @@ * Created by Mateusz Rębacz on 11.09.2017. */ -public class AddNodeCacheDialog extends JDialog { +public class NodeAddDialog extends JDialog { /** * The text field with the address of the node. */ private JTextField nodeAddressField; - public AddNodeCacheDialog(JFrame parent) { + public NodeAddDialog(JFrame parent) { //Setting the title of the dialog. super(parent, "Add Node", true); @@ -64,7 +64,7 @@ private void addContent() { } //Closing the dialog. - AddNodeCacheDialog.this.dispose(); + NodeAddDialog.this.dispose(); }); if(UnderNet.router.status.equals(InterfaceStatus.STARTED) || UnderNet.router.status.equals(InterfaceStatus.STARTING)) { saveButton.setText("Connect"); @@ -76,7 +76,7 @@ private void addContent() { @Override public void actionPerformed(ActionEvent actionEvent) { //Closing the dialog. - AddNodeCacheDialog.this.dispose(); + NodeAddDialog.this.dispose(); } }); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java similarity index 78% rename from standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java index 178b3e4b..e04f3a4d 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/UploadResourceDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java @@ -16,7 +16,7 @@ * Created by Mateusz Rębacz on 20.10.2017. */ -public class UploadResourceDialog extends JDialog { +public class ResourcePublishDialog extends JDialog { /** * The result of the last file choosing the user has done. */ @@ -24,7 +24,7 @@ public class UploadResourceDialog extends JDialog { private JFrame frame; - public UploadResourceDialog(JFrame parent) { + public ResourcePublishDialog(JFrame parent) { //Setting the title of the dialog. super(parent, "Publish Resource", true); this.frame = parent; @@ -56,7 +56,7 @@ public void actionPerformed(ActionEvent actionEvent) { //Button clicked. JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); - int result = fileChooser.showOpenDialog(UploadResourceDialog.this); + int result = fileChooser.showOpenDialog(ResourcePublishDialog.this); if(result == JFileChooser.APPROVE_OPTION) { fileChooseResult = fileChooser.getSelectedFile(); } @@ -73,12 +73,12 @@ public void actionPerformed(ActionEvent actionEvent) { //Publishing resource on UnderNet. FileResource fileResource = new FileResource(UnderNet.router, fileChooseResult); if(!fileResource.copyToContent()) { - JOptionPane.showMessageDialog(UploadResourceDialog.this.frame, String.format("There was a problem accessing file: \n%s.", fileChooseResult), "Can't publish resource!", JOptionPane.ERROR_MESSAGE); - UploadResourceDialog.this.dispose(); + JOptionPane.showMessageDialog(ResourcePublishDialog.this.frame, String.format("There was a problem accessing file: \n%s.", fileChooseResult), "Can't publish resource!", JOptionPane.ERROR_MESSAGE); + ResourcePublishDialog.this.dispose(); return; } UnderNet.router.resourceManager.publish(fileResource); - UploadResourceDialog.this.dispose(); + ResourcePublishDialog.this.dispose(); //Copying the network to clipboard. StringSelection stringSelection = new StringSelection(fileResource.getNetworkID().getStringValue()); @@ -86,7 +86,7 @@ public void actionPerformed(ActionEvent actionEvent) { clipboard.setContents(stringSelection, null); //Showing the published network id. - JOptionPane.showMessageDialog(UploadResourceDialog.this.frame, String.format("Publishing %s, \nNetwork id: %s \nThe network id has been copied to your clipboard.", fileChooseResult, fileResource.getNetworkID().getStringValue()), "Publishing resource", JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showMessageDialog(ResourcePublishDialog.this.frame, String.format("Publishing %s, \nNetwork id: %s \nThe network id has been copied to your clipboard.", fileChooseResult, fileResource.getNetworkID().getStringValue()), "Publishing resource", JOptionPane.INFORMATION_MESSAGE); } } }); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java similarity index 93% rename from standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java rename to standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java index 4d318498..a11770b1 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java @@ -25,8 +25,8 @@ * Created by Mateusz Rębacz on 03.11.2017. */ -public class PullResourceDialog extends JDialog { - public PullResourceDialog(JFrame parent) { +public class ResourcePullDialog extends JDialog { + public ResourcePullDialog(JFrame parent) { //Setting the title of the dialog. super(parent, "Pull Resource", true); @@ -68,7 +68,7 @@ public void actionPerformed(ActionEvent actionEvent) { fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Choose the save directory"); - int result = fileChooser.showOpenDialog(PullResourceDialog.this); + int result = fileChooser.showOpenDialog(ResourcePullDialog.this); if(result == JFileChooser.APPROVE_OPTION) { saveFile[0] = fileChooser.getSelectedFile(); } @@ -105,11 +105,11 @@ public void onEventCalled(Event e) { e1.printStackTrace(); } finally { //File dialog. - EventQueue.invokeLater(()->JOptionPane.showMessageDialog(PullResourceDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveFile[0]),"File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); + EventQueue.invokeLater(()->JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveFile[0]),"File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); } } else { //File dialog. - EventQueue.invokeLater(()->JOptionPane.showMessageDialog(PullResourceDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); + EventQueue.invokeLater(()->JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); } } @@ -118,9 +118,9 @@ public void onEventCalled(Event e) { } }, ResourceTransferFinishedEvent.class); - PullResourceDialog.this.dispose(); + ResourcePullDialog.this.dispose(); } else { - JOptionPane.showMessageDialog(PullResourceDialog.this, "The Network ID you specified is invalid!", "Invalid Network ID", JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(ResourcePullDialog.this, "The Network ID you specified is invalid!", "Invalid Network ID", JOptionPane.ERROR_MESSAGE); } } }); From 8eb7829e553b180ce5318b4293d587815bbdb97d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 17:45:29 +0100 Subject: [PATCH 12/60] Update ResourceManager.java --- .../standalone/resource/ResourceManager.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/resource/ResourceManager.java b/standalone/src/main/java/me/matoosh/undernet/standalone/resource/ResourceManager.java index 8f38e0d1..364ca83f 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/resource/ResourceManager.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/resource/ResourceManager.java @@ -1,7 +1,10 @@ package me.matoosh.undernet.standalone.resource; import me.matoosh.undernet.file.FileManager; +import me.matoosh.undernet.p2p.router.data.resource.Resource; import me.matoosh.undernet.standalone.UnderNetStandalone; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.FileOutputStream; import java.io.InputStream; @@ -13,6 +16,11 @@ */ public class ResourceManager { + /** + * the logger of the class. + */ + public static Logger logger = LoggerFactory.getLogger(ResourceManager.class); + /** * Export a resource embedded into a Jar file to the local file path. * @@ -20,11 +28,15 @@ public class ResourceManager { * @return The path to the exported resource * @throws Exception */ - static public String exportResource(String resourceName, FileManager fileManager) throws Exception { + public static String exportResource(String resourceName, FileManager fileManager) throws Exception { + String path = fileManager.getAppFolder() + resourceName; + logger.info("Generating file: {}", path); + + InputStream stream = null; OutputStream resStreamOut = null; try { - stream = UnderNetStandalone.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree + stream = UnderNetStandalone.class.getResourceAsStream(resourceName); if(stream == null) { throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file."); } @@ -32,7 +44,7 @@ static public String exportResource(String resourceName, FileManager fileManager int readBytes; byte[] buffer = new byte[4096]; - resStreamOut = new FileOutputStream(fileManager.getAppFolder() + resourceName); + resStreamOut = new FileOutputStream(path); while ((readBytes = stream.read(buffer)) > 0) { resStreamOut.write(buffer, 0, readBytes); } From ebcc7bf86aca21af5b7b4654e76a69be14554686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:06:30 +0100 Subject: [PATCH 13/60] Improved ui performance --- .gitignore | 3 + .../matoosh/undernet/p2p/router/Router.java | 12 ++- .../undernet/standalone/uix/MainFrame.java | 12 +-- .../undernet/standalone/uix/NodePanel.java | 10 +-- .../standalone/uix/ResourcePanel.java | 88 +++++++++---------- .../undernet/standalone/uix/VisualPanel.java | 4 + 6 files changed, 71 insertions(+), 58 deletions(-) diff --git a/.gitignore b/.gitignore index 75f343ac..7f9e9969 100755 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,6 @@ standalone/random.id *.id *.resources .idea/modules.xml +cache/entry.nodes +standalone.yaml +network.yaml diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 4e367e19..f9733a03 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -101,6 +101,10 @@ public class Router extends EventHandler { * Nodes the router is connected to at the moment. */ private ArrayList connectedNodes = new ArrayList<>(); + /** + * Remote nodes that the router is connected to at the moment. + */ + private ArrayList remoteNodes = new ArrayList<>(); /** * The logger. @@ -290,15 +294,17 @@ public ArrayList getConnectedNodes() { * @return */ public ArrayList getRemoteNodes() { - ArrayList remote = new ArrayList<>(); + if(remoteNodes.size() + 2 == connectedNodes.size()) return remoteNodes; + + remoteNodes = new ArrayList<>(); for (int i = 0; i < connectedNodes.size(); i++) { Node n = connectedNodes.get(i); if (n.getAddress() != null && !Node.isLocalAddress(n.getAddress())) { - remote.add(n); + remoteNodes.add(n); } } - return remote; + return remoteNodes; } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 966e5549..34beed69 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -153,7 +153,7 @@ private void drawLoop() { sleep_time = next_game_tick - System.currentTimeMillis(); if (sleep_time >= 0) { try { - frame.repaint(); + visualPanel.getPanel().repaint(); Thread.sleep(sleep_time); } catch (InterruptedException e) { e.printStackTrace(); @@ -164,6 +164,11 @@ private void drawLoop() { } } + private void createUIComponents() { + controlIcon1 = new ControlIcon(); + mainButton = new JButton(ResourceBundle.getBundle("language").getString("button_connect")); + } + /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< @@ -202,9 +207,4 @@ private void drawLoop() { public JComponent $$$getRootComponent$$$() { return panel; } - - private void createUIComponents() { - controlIcon1 = new ControlIcon(); - mainButton = new JButton(ResourceBundle.getBundle("language").getString("button_connect")); - } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 3f8956f2..878b129b 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -127,6 +127,11 @@ private void refreshNodeList() { } } + private void createUIComponents() { + nodeList = new JList(new Node[]{}); + nodeList.setCellRenderer(new NodesListCellRenderer()); + } + /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< @@ -238,11 +243,6 @@ private void refreshNodeList() { public JComponent $$$getRootComponent$$$() { return panel; } - - private void createUIComponents() { - nodeList = new JList(new Node[]{}); - nodeList.setCellRenderer(new NodesListCellRenderer()); - } } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index 87074496..1c41d24b 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -64,6 +64,50 @@ private void registerListeners() { EventManager.registerHandler(this, ResourceTransferErrorEvent.class); } + private void refreshList() { + resourceList.setListData(UnderNet.router.resourceManager.getStoredFileResources().toArray()); + } + + @Override + public void onEventCalled(Event e) { + if (e instanceof RouterStatusEvent) { + RouterStatusEvent statusEvent = (RouterStatusEvent) e; + + switch (statusEvent.newStatus) { + case STARTED: + publishButton.setEnabled(true); + pullButton.setEnabled(true); + break; + case STOPPED: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + case STARTING: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + case STOPPING: + publishButton.setEnabled(false); + pullButton.setEnabled(false); + break; + } + } else if (e instanceof ResourceTransferStartedEvent) { + publishButton.setEnabled(false); + pullButton.setEnabled(false); + } else if (e instanceof ResourceTransferFinishedEvent) { + publishButton.setEnabled(true); + pullButton.setEnabled(true); + refreshList(); + } else if (e instanceof ResourceTransferErrorEvent) { + publishButton.setEnabled(true); + pullButton.setEnabled(true); + } + } + + private void createUIComponents() { + resourceList = new JList(new Resource[0]); + } + /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< @@ -179,48 +223,4 @@ private void registerListeners() { public JComponent $$$getRootComponent$$$() { return panel; } - - private void refreshList() { - resourceList.setListData(UnderNet.router.resourceManager.getStoredFileResources().toArray()); - } - - @Override - public void onEventCalled(Event e) { - if (e instanceof RouterStatusEvent) { - RouterStatusEvent statusEvent = (RouterStatusEvent) e; - - switch (statusEvent.newStatus) { - case STARTED: - publishButton.setEnabled(true); - pullButton.setEnabled(true); - break; - case STOPPED: - publishButton.setEnabled(false); - pullButton.setEnabled(false); - break; - case STARTING: - publishButton.setEnabled(false); - pullButton.setEnabled(false); - break; - case STOPPING: - publishButton.setEnabled(false); - pullButton.setEnabled(false); - break; - } - } else if (e instanceof ResourceTransferStartedEvent) { - publishButton.setEnabled(false); - pullButton.setEnabled(false); - } else if (e instanceof ResourceTransferFinishedEvent) { - publishButton.setEnabled(true); - pullButton.setEnabled(true); - refreshList(); - } else if (e instanceof ResourceTransferErrorEvent) { - publishButton.setEnabled(true); - pullButton.setEnabled(true); - } - } - - private void createUIComponents() { - resourceList = new JList(new Resource[0]); - } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java index 4cae3f93..66752709 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java @@ -9,6 +9,10 @@ private void createUIComponents() { panel = new VisualPanelDraw(); } + public JPanel getPanel() { + return panel; + } + { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< From ef23f367129181d2832683765e053e022b6616c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:09:15 +0100 Subject: [PATCH 14/60] Reset progress bar on file transfer finished --- .../me/matoosh/undernet/standalone/uix/MainFrame.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 34beed69..cb511269 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -9,6 +9,7 @@ import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.resource.transfer.ResourceTransferDataReceivedEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferDataSentEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.router.InterfaceStatus; import me.matoosh.undernet.p2p.router.data.resource.transfer.FileTransferHandler; @@ -135,6 +136,13 @@ public void onEventCalled(Event e) { progressBar.setValue((int) (((float) fileTransferHandler.getSent()) / ((float) fileTransferHandler.getFileLength()) * 100f)); } + } else if(e instanceof ResourceTransferFinishedEvent) { + ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; + ResourceTransferHandler transferHandler = transferFinishedEvent.transferHandler; + + if (transferHandler instanceof FileTransferHandler) { + progressBar.setValue(0); + } } } From 5790581a69953e48e687b4a17ca9ff889c8794b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:23:45 +0100 Subject: [PATCH 15/60] Better displaying of resource list --- .gitignore | 14 ++++---- .../undernet/standalone/uix/MainFrame.form | 8 +++-- .../undernet/standalone/uix/MainFrame.java | 6 ++-- .../standalone/uix/ResourcePanel.java | 32 +++++++++++++++++++ 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 7f9e9969..a8e1894a 100755 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,8 @@ Thumbs.db .DS_Store /build /captures +.idea + .externalNativeBuild /*/out /*/build @@ -31,17 +33,15 @@ Thumbs.db *.ipr *~ *.swp -.idea/runConfigurations.xml + +#Standalone test files. standalone/network.yaml standalone/standalone.yaml -standalone/cache/entry.nodes -standalone/cache/me.identity +standalone/cache/* standalone/content +standalone/build standalone/debug.log standalone/random.id -*.id -*.resources -.idea/modules.xml -cache/entry.nodes +cache standalone.yaml network.yaml diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form index 18cad055..91aca55c 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form @@ -15,12 +15,16 @@ - + + + - + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index cb511269..3899d5db 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -136,7 +136,7 @@ public void onEventCalled(Event e) { progressBar.setValue((int) (((float) fileTransferHandler.getSent()) / ((float) fileTransferHandler.getFileLength()) * 100f)); } - } else if(e instanceof ResourceTransferFinishedEvent) { + } else if (e instanceof ResourceTransferFinishedEvent) { ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; ResourceTransferHandler transferHandler = transferFinishedEvent.transferHandler; @@ -191,9 +191,9 @@ private void createUIComponents() { final Spacer spacer1 = new Spacer(); panel.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); resourcePanel = new ResourcePanel(); - panel.add(resourcePanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + panel.add(resourcePanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(200, -1), null, null, 0, false)); nodePanel = new NodePanel(); - panel.add(nodePanel.$$$getRootComponent$$$(), new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + panel.add(nodePanel.$$$getRootComponent$$$(), new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(300, -1), null, null, 0, false)); tunnelPanel = new TunnelPanel(); panel.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel.add(mainButton, new GridConstraints(4, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 50), null, 0, false)); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index 1c41d24b..c99f3be6 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -10,6 +10,9 @@ import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; +import me.matoosh.undernet.p2p.node.Node; +import me.matoosh.undernet.p2p.router.InterfaceStatus; +import me.matoosh.undernet.p2p.router.data.resource.FileResource; import me.matoosh.undernet.p2p.router.data.resource.Resource; import me.matoosh.undernet.standalone.uix.dialog.ResourcePublishDialog; import me.matoosh.undernet.standalone.uix.dialog.ResourcePullDialog; @@ -106,6 +109,7 @@ public void onEventCalled(Event e) { private void createUIComponents() { resourceList = new JList(new Resource[0]); + resourceList.setCellRenderer(new ResourceListCellRenderer()); } /** @@ -224,3 +228,31 @@ private void createUIComponents() { return panel; } } +/** + * Renders elements within the resource list. + */ +class ResourceListCellRenderer extends DefaultListCellRenderer +{ + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value instanceof Resource) { + Resource resource = (Resource) value; + + if(resource instanceof FileResource) { + FileResource file = (FileResource) resource; + setText(file.attributes.get(1)); + } else { + setText(resource.toString()); + } + + if (isSelected) { + setBackground(getBackground().darker()); + } + } else { + setText("UNKNOWN"); + } + return c; + } +} From d8d9ec8f567341aca2e811d1a780770278eef2c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:25:26 +0100 Subject: [PATCH 16/60] Update NodePanel.java --- .../main/java/me/matoosh/undernet/standalone/uix/NodePanel.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 878b129b..01425a75 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -55,6 +55,7 @@ public void mouseClicked(MouseEvent e) { //Double-click detected if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { int index = list.locationToIndex(e.getPoint()); + if(index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. @@ -66,6 +67,7 @@ public void mouseClicked(MouseEvent e) { } else if (e.getClickCount() == 1) { //Single click detected int index = list.locationToIndex(e.getPoint()); + if(index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. From 8def793c25539f541bc0e9e901e7406b8962af8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:38:14 +0100 Subject: [PATCH 17/60] Closing tunnel on transfer finished. --- .../undernet/p2p/router/data/resource/ResourceManager.java | 1 + .../java/me/matoosh/undernet/standalone/uix/MainFrame.java | 1 + .../java/me/matoosh/undernet/standalone/uix/NodePanel.java | 5 +++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 2f8fcda9..529038b7 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -316,6 +316,7 @@ else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.RE //Closing the streams. transferFinishedEvent.transferHandler.close(); + transferFinishedEvent.transferHandler.getTunnel().close(); //Removing from the list. if(transferFinishedEvent.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 3899d5db..0003965a 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -82,6 +82,7 @@ private void registerListener() { EventManager.registerHandler(this, RouterStatusEvent.class); EventManager.registerHandler(this, ResourceTransferDataReceivedEvent.class); EventManager.registerHandler(this, ResourceTransferDataSentEvent.class); + EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 01425a75..06095128 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -55,7 +55,7 @@ public void mouseClicked(MouseEvent e) { //Double-click detected if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { int index = list.locationToIndex(e.getPoint()); - if(index == -1) return; + if (index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. @@ -67,7 +67,7 @@ public void mouseClicked(MouseEvent e) { } else if (e.getClickCount() == 1) { //Single click detected int index = list.locationToIndex(e.getPoint()); - if(index == -1) return; + if (index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. @@ -245,6 +245,7 @@ private void createUIComponents() { public JComponent $$$getRootComponent$$$() { return panel; } + } /** From 4713ea5c75be0fc776e142ac168508e8e0c790be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 18:39:15 +0100 Subject: [PATCH 18/60] Update NodePanel.java --- .../java/me/matoosh/undernet/standalone/uix/NodePanel.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 01425a75..06483e01 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -55,7 +55,7 @@ public void mouseClicked(MouseEvent e) { //Double-click detected if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { int index = list.locationToIndex(e.getPoint()); - if(index == -1) return; + if (index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. @@ -67,7 +67,7 @@ public void mouseClicked(MouseEvent e) { } else if (e.getClickCount() == 1) { //Single click detected int index = list.locationToIndex(e.getPoint()); - if(index == -1) return; + if (index == -1) return; Node node = (Node) nodeList.getModel().getElementAt(index); //Checking if the node is connected. From 378765697f602bad92a01441c551ef2b52ec8361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 19:05:39 +0100 Subject: [PATCH 19/60] Update ResourceManager.java --- .../undernet/p2p/router/data/resource/ResourceManager.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 529038b7..a8cc75ee 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -15,6 +15,7 @@ import me.matoosh.undernet.p2p.router.data.NetworkID; import me.matoosh.undernet.p2p.router.data.message.*; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferType; import org.slf4j.Logger; @@ -316,7 +317,8 @@ else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.RE //Closing the streams. transferFinishedEvent.transferHandler.close(); - transferFinishedEvent.transferHandler.getTunnel().close(); + if(transferFinishedEvent.transferHandler.getTunnel().getSide() == MessageTunnelSide.ORIGIN) + transferFinishedEvent.transferHandler.getTunnel().close(); //Removing from the list. if(transferFinishedEvent.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { From d85b3f01797a497685279d35e126d7ade432b0d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 19:18:16 +0100 Subject: [PATCH 20/60] Update MessageTunnelManager.java --- .../router/data/message/tunnel/MessageTunnelManager.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 23df4b8d..0192b32e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -107,15 +107,11 @@ public void closeTunnelsOnDisconnect(Node disconnected) { */ public void closeTunnel(MessageTunnel tunnel) { logger.info("Closing tunnel: {}", tunnel); - tunnel.setPreviousNode(null); - tunnel.setNextNode(null); messageTunnels.remove(tunnel); if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { for (MessageTunnel tunn : messageTunnels) { if(tunn.getDestination().equals(Node.self)) { - tunn.setPreviousNode(null); - tunn.setNextNode(null); messageTunnels.remove(tunn); } } @@ -123,8 +119,6 @@ public void closeTunnel(MessageTunnel tunnel) { for (MessageTunnel tunn : messageTunnels) { if(tunn.getOrigin().equals(Node.self)) { - tunn.setPreviousNode(null); - tunn.setNextNode(null); messageTunnels.remove(tunn); } } From 25e77b759be063ce569ff24c8cfc178969af7b77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 19:28:07 +0100 Subject: [PATCH 21/60] Update VisualPanelDraw.java --- .../undernet/standalone/uix/VisualPanelDraw.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java index c13abe62..5e1be818 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -79,7 +79,7 @@ private void drawSelfNode(Graphics g) { private void drawOtherNodes(Graphics g) { double angle = (2 * Math.PI) / UnderNet.router.getRemoteNodes().size(); int distance = 100; - int rad = 30; + int diam = 30; double currAngle = ((double)(System.currentTimeMillis() % 5000) / 5000d) * (2 * Math.PI); for (int i = 0; i < UnderNet.router.getRemoteNodes().size(); i++) { @@ -100,9 +100,14 @@ private void drawOtherNodes(Graphics g) { //circle g.setColor(Color.CYAN); - g.fillOval( x - rad/2, y - rad/2, rad, rad); + g.fillOval( x - diam/2, y - diam/2, diam, diam); g.setColor(Color.BLACK); - g.drawOval(getWidth()/2 + x - rad/2, getHeight()/2 + y - rad/2, rad, rad); + g.drawOval(getWidth()/2 + x - diam/2, getHeight()/2 + y - diam/2, diam, diam); + + //net id + g.setColor(Color.WHITE); + String identity = n.getIdentity().getNetworkId().getStringValue().substring(0, 10) + "..."; + g.drawString(identity, x - g.getFontMetrics().stringWidth(identity)/2, y + diam/2 + g.getFontMetrics().getHeight() + 5); currAngle += angle; } From 0a846c2aa7c9377afea30939cb05f75ab8c22b46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 19:28:52 +0100 Subject: [PATCH 22/60] Update NetworkMessageManager.java --- .../p2p/router/data/message/NetworkMessageManager.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 37aa2304..f2b50554 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -154,15 +154,15 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { if(forwarder == Node.self) { if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { - logger.info("Forwarding message, ({}) -> ({}) -> (...) -> ({})", Node.self, tunnel.getNextNode(), message.getDestination()); + logger.debug("Forwarding message, ({}) -> ({}) -> (...) -> ({})", Node.self, tunnel.getNextNode(), message.getDestination()); } else { - logger.info("Forwarding message, ({}) <- (...) <- ({}) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self); + logger.debug("Forwarding message, ({}) <- (...) <- ({}) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self); } } else { if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { - logger.info("Forwarding message, ({}) -> (...) -> ({}) -> ({}) -> ({}) -> (...) -> ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, tunnel.getNextNode(), message.getDestination()); + logger.debug("Forwarding message, ({}) -> (...) -> ({}) -> ({}) -> ({}) -> (...) -> ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, tunnel.getNextNode(), message.getDestination()); } else { - logger.info("Forwarding message, ({}) <- (...) <- ({}) <- ({}) <- ({}) <- (...) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, forwarder, message.getDestination()); + logger.debug("Forwarding message, ({}) <- (...) <- ({}) <- ({}) <- ({}) <- (...) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, forwarder, message.getDestination()); } } From 01771d1c6ecc68a21085d7f947dc92d6719db15f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sat, 12 Jan 2019 19:30:25 +0100 Subject: [PATCH 23/60] Update VisualPanelDraw.java --- .../matoosh/undernet/standalone/uix/VisualPanelDraw.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java index 5e1be818..05ff2752 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -105,9 +105,11 @@ private void drawOtherNodes(Graphics g) { g.drawOval(getWidth()/2 + x - diam/2, getHeight()/2 + y - diam/2, diam, diam); //net id - g.setColor(Color.WHITE); - String identity = n.getIdentity().getNetworkId().getStringValue().substring(0, 10) + "..."; - g.drawString(identity, x - g.getFontMetrics().stringWidth(identity)/2, y + diam/2 + g.getFontMetrics().getHeight() + 5); + if(n.getIdentity() != null) { + g.setColor(Color.WHITE); + String identity = n.getIdentity().getNetworkId().getStringValue().substring(0, 10) + "..."; + g.drawString(identity, x - g.getFontMetrics().stringWidth(identity) / 2, y + diam / 2 + g.getFontMetrics().getHeight() + 5); + } currAngle += angle; } From dc7ac0917b5fe4b40317fe1bf116263641f8361b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 00:52:45 +0100 Subject: [PATCH 24/60] Tunnel improvements --- .../data/message/NetworkMessageManager.java | 14 +++- .../message/tunnel/MessageTunnelManager.java | 76 +++++-------------- .../router/data/resource/ResourceManager.java | 17 ++++- 3 files changed, 44 insertions(+), 63 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index f2b50554..a3467c47 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -47,7 +47,11 @@ public void setup() { */ public void sendMessage(MsgBase content, NetworkID recipient) { //Getting the appropriate message tunnel. - MessageTunnel messageTunnel = router.messageTunnelManager.getOrCreateTunnel(Node.self.getIdentity().getNetworkId(), recipient, MessageTunnelSide.ORIGIN); + MessageTunnel messageTunnel = router.messageTunnelManager.getTunnel(Node.self.getIdentity().getNetworkId(), recipient); + if(messageTunnel == null) { + //Creating a tunnel if doesn't exist already. + messageTunnel = router.messageTunnelManager.createTunnel(Node.self.getIdentity().getNetworkId(), recipient, MessageTunnelSide.ORIGIN); + } //Constructing the message. NetworkMessage message = constructMessage(messageTunnel, content, NetworkMessage.MessageDirection.TO_DESTINATION); @@ -136,9 +140,13 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { } //Getting the next node in the tunnel. - MessageTunnel tunnel = router.messageTunnelManager.getOrCreateTunnel(message.getOrigin(), message.getDestination()); - Node nextNode; + MessageTunnel tunnel = router.messageTunnelManager.getTunnel(message.getOrigin(), message.getDestination()); + if(tunnel == null) { + tunnel = router.messageTunnelManager.createTunnel(message.getOrigin(), message.getDestination(), MessageTunnelSide.UNDEFINED); + } + //Getting the next node. + Node nextNode; if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { //Getting the closest neighbor to forward the message to. tunnel.setPreviousNode(forwarder); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 0192b32e..221bdcd1 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -41,33 +41,13 @@ public MessageTunnelManager(Router router) { } /** - * Gets the message tunnel of a particular other. - * @param origin - * @param destination + * Creates a new message tunnel instance and adds it to the tunnel list. * @return */ - public MessageTunnel getTunnel(NetworkID origin, NetworkID destination) { - for (int i = 0; i < messageTunnels.size(); i++) { - MessageTunnel tunnel = messageTunnels.get(i); - if(tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { - return tunnel; - } - } - return null; - } - /** - * Gets the message tunnel of a particular origin. - * @param origin - * @return - */ - public MessageTunnel getTunnelByOrigin(NetworkID origin) { - for (int i = 0; i < messageTunnels.size(); i++) { - MessageTunnel tunnel = messageTunnels.get(i); - if(tunnel.getOrigin().equals(origin)) { - return tunnel; - } - } - return null; + public MessageTunnel createTunnel(NetworkID origin, NetworkID destination, MessageTunnelSide side) { + MessageTunnel tunnel = new MessageTunnel(origin, destination, side); + messageTunnels.add(tunnel); + return tunnel; } /** @@ -151,37 +131,18 @@ public void sendTunnelResponse(MessageTunnel tunnel) { * Gets or creates a message tunnel. * @return */ - public MessageTunnel getOrCreateTunnel(NetworkID origin, NetworkID destination) { + public MessageTunnel getTunnel(NetworkID nodeA, NetworkID nodeB) { //Finding an existing tunnel. for (MessageTunnel tunnel : messageTunnels) { - if (tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { + if(tunnel.getOrigin().equals(nodeA) && tunnel.getDestination().equals(nodeB)) { return tunnel; } - } - - //Creating a tunnel if doesn't exist already. - MessageTunnel tunnel = new MessageTunnel(origin, destination); - messageTunnels.add(tunnel); - return tunnel; - } - /** - * Gets or creates a message tunnel. - * @return - */ - public MessageTunnel getOrCreateTunnel(NetworkID origin, NetworkID destination, MessageTunnelSide side) { - //Finding an existing tunnel. - for (MessageTunnel tunnel : - messageTunnels) { - if (tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { + if(tunnel.getOrigin().equals(nodeB) && tunnel.getDestination().equals(nodeA)) { return tunnel; } } - - //Creating a tunnel if doesn't exist already. - MessageTunnel tunnel = new MessageTunnel(origin, destination, side); - messageTunnels.add(tunnel); - return tunnel; + return null; } @Override @@ -207,7 +168,7 @@ public void onEventCalled(Event e) { //Called on the destination of the tunnel. TunnelEstablishRequestMessage tunnelEstablishRequestMessage = (TunnelEstablishRequestMessage) messageReceivedEvent.networkMessage.getContent(); //Creating a new tunnel object. - MessageTunnel tunnel = getOrCreateTunnel(tunnelEstablishRequestMessage.getNetworkMessage().getOrigin(), tunnelEstablishRequestMessage.getNetworkMessage().getDestination()); + MessageTunnel tunnel = new MessageTunnel(tunnelEstablishRequestMessage.getNetworkMessage().getOrigin(), tunnelEstablishRequestMessage.getNetworkMessage().getDestination()); tunnel.setSide(MessageTunnelSide.DESTINATION); //Setting the other's public key. @@ -216,29 +177,30 @@ public void onEventCalled(Event e) { //Calculating the shared secret. tunnel.calcSharedSecret(); - //Calling the established event. - EventManager.callEvent(new MessageTunnelEstablishedEvent(messageReceivedEvent.networkMessage.getTunnel(), NetworkMessage.MessageDirection.TO_ORIGIN)); + messageTunnels.add(tunnel); //Sending response. sendTunnelResponse(tunnel); + + //Calling the established event. + EventManager.callEvent(new MessageTunnelEstablishedEvent(messageReceivedEvent.networkMessage.getTunnel(), NetworkMessage.MessageDirection.TO_ORIGIN)); } else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_ESTABLISH_RESPONSE) { //Called on the origin of the tunnel. TunnelEstablishResponseMessage tunnelEstablishResponseMessage = (TunnelEstablishResponseMessage) messageReceivedEvent.networkMessage.getContent(); - MessageTunnel tunnel = getOrCreateTunnel(tunnelEstablishResponseMessage.getNetworkMessage().getOrigin(), tunnelEstablishResponseMessage.getNetworkMessage().getDestination()); + MessageTunnel tunnel = getTunnel(tunnelEstablishResponseMessage.getNetworkMessage().getOrigin(), tunnelEstablishResponseMessage.getNetworkMessage().getDestination()); tunnel.setSide(MessageTunnelSide.ORIGIN); - //Setting the other's public key. try { + //Setting the other's public key. tunnel.setOtherPublicKey(KeyTools.fromUncompressedPoint(tunnelEstablishResponseMessage.publicKey)); - //Calculating the shared secret. tunnel.calcSharedSecret(); - - //Calling the event. - EventManager.callEvent(new MessageTunnelEstablishedEvent(tunnel, NetworkMessage.MessageDirection.TO_DESTINATION)); } catch (Exception e1) { logger.error("Couldn't decode the received public key for tunnel!", e1); } + + //Calling the event. + EventManager.callEvent(new MessageTunnelEstablishedEvent(tunnel, NetworkMessage.MessageDirection.TO_DESTINATION)); } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_CLOSE_REQUEST) { TunnelCloseRequestMessage closeRequestMessage = (TunnelCloseRequestMessage) messageReceivedEvent.networkMessage.getContent(); closeTunnel(closeRequestMessage.getNetworkMessage().getTunnel()); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index a8cc75ee..52816a8e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -81,7 +81,8 @@ public void publish(Resource resource) { logger.info("Publishing resource: {}...", resource); //Sending the resource info message. - startPush(resource, router.messageTunnelManager.getOrCreateTunnel(Node.self.getIdentity().getNetworkId(), resource.getNetworkID())); + MessageTunnel tunnel = router.messageTunnelManager.createTunnel(Node.self.getIdentity().getNetworkId(), resource.getNetworkID(), MessageTunnelSide.ORIGIN); + startPush(resource, tunnel); } /** @@ -157,6 +158,16 @@ public ArrayList getStoredFileResources() { return resources; } + /** + * Starts a push of a resource. + * @param resource + */ + private void startPush(Resource resource) { + //Creating push tunnel + MessageTunnel tunnel = router.messageTunnelManager.createTunnel(Node.self.getIdentity().getNetworkId(), resource.getNetworkID(), MessageTunnelSide.ORIGIN); + startPush(resource, tunnel); + } + /** * Starts a push of a resource. * @param resource @@ -303,13 +314,13 @@ else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.RE for (FileResource file : getStoredFileResources()) { if(router.neighborNodesManager.getClosestTo(file.getNetworkID()) != Node.self) { - startPush(file, router.messageTunnelManager.getOrCreateTunnel(Node.self.getIdentity().getNetworkId(), file.getNetworkID())); + startPush(file); } } for (FlagResource flag : flagResources) { if(router.neighborNodesManager.getClosestTo(flag.getNetworkID()) != Node.self) { - startPush(flag, router.messageTunnelManager.getOrCreateTunnel(Node.self.getIdentity().getNetworkId(), flag.getNetworkID())); + startPush(flag); } } } else if(e instanceof ResourceTransferFinishedEvent) { From 35da025e8e60116bad869f40ec30739068a7e6d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:08:25 +0100 Subject: [PATCH 25/60] a --- .../me/matoosh/undernet/p2p/router/Router.java | 5 +++++ .../undernet/standalone/uix/TunnelPanel.java | 16 +++++++++++++++- .../undernet/standalone/uix/VisualPanelDraw.java | 13 ++++++++++--- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index f9733a03..df02d9e9 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -256,6 +256,11 @@ public void stop() { if(server != null) { server.stop(); } + + //Closes all remaining tunnels. + for (int i = 0; i < messageTunnelManager.messageTunnels.size(); i++) { + messageTunnelManager.closeTunnel(messageTunnelManager.messageTunnels.get(i)); + } } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java index 25aefae1..6555ddb0 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java @@ -11,6 +11,7 @@ import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.router.InterfaceStatus; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; +import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelState; import javax.swing.*; import java.awt.*; @@ -93,7 +94,20 @@ public Component getListCellRendererComponent(JList list, Object value, int inde if (value instanceof MessageTunnel) { MessageTunnel tunnel = (MessageTunnel) value; setText(tunnel.toString()); - setBackground(Color.GREEN); + switch(tunnel.getTunnelState()) { + case ESTABLISHED: + setBackground(Color.GREEN); + break; + case HOSTED: + setBackground(Color.GRAY); + break; + case ESTABLISHING: + setBackground(Color.ORANGE); + break; + case NOT_ESTABLISHED: + setBackground(Color.RED); + break; + } if (isSelected) { setBackground(getBackground().darker()); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java index 05ff2752..21622516 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanelDraw.java @@ -66,11 +66,18 @@ private void drawSelfNode(Graphics g) { } } - int rad = 40; + int diam = 40; g.setColor(fill); - g.fillOval(getWidth()/2 - rad/2, getHeight()/2 - rad/2, rad, rad); + g.fillOval(getWidth()/2 - diam/2, getHeight()/2 - diam/2, diam, diam); g.setColor(Color.BLACK); - g.drawOval(getWidth()/2 - rad/2, getHeight()/2 - rad/2, rad, rad); } + g.drawOval(getWidth()/2 - diam/2, getHeight()/2 - diam/2, diam, diam); + + if(Node.self.getIdentity() != null) { + g.setColor(Color.WHITE); + String identity = Node.self.getIdentity().getNetworkId().getStringValue().substring(0, 12) + "..."; + g.drawString(identity, getWidth()/2 - g.getFontMetrics().stringWidth(identity) / 2, getHeight()/2 + diam / 2 + g.getFontMetrics().getHeight() + 5); + } + } /** * Draws representations of other nodes. From 9cdf60ce47e41e4ce8f0efa290d9072e32b53e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:13:06 +0100 Subject: [PATCH 26/60] b --- .../p2p/router/data/message/tunnel/MessageTunnelManager.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 221bdcd1..9e01e233 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -168,7 +168,7 @@ public void onEventCalled(Event e) { //Called on the destination of the tunnel. TunnelEstablishRequestMessage tunnelEstablishRequestMessage = (TunnelEstablishRequestMessage) messageReceivedEvent.networkMessage.getContent(); //Creating a new tunnel object. - MessageTunnel tunnel = new MessageTunnel(tunnelEstablishRequestMessage.getNetworkMessage().getOrigin(), tunnelEstablishRequestMessage.getNetworkMessage().getDestination()); + MessageTunnel tunnel = getTunnel(tunnelEstablishRequestMessage.getNetworkMessage().getOrigin(), tunnelEstablishRequestMessage.getNetworkMessage().getDestination()); tunnel.setSide(MessageTunnelSide.DESTINATION); //Setting the other's public key. @@ -177,8 +177,6 @@ public void onEventCalled(Event e) { //Calculating the shared secret. tunnel.calcSharedSecret(); - messageTunnels.add(tunnel); - //Sending response. sendTunnelResponse(tunnel); From dc5d0abaa90af905a4fca023e075e6ce5f9ad6a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:17:30 +0100 Subject: [PATCH 27/60] Update TunnelPanel.java --- .../java/me/matoosh/undernet/standalone/uix/TunnelPanel.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java index 6555ddb0..131dac7d 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java @@ -8,6 +8,7 @@ import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelClosedEvent; import me.matoosh.undernet.event.channel.message.tunnel.MessageTunnelEstablishedEvent; +import me.matoosh.undernet.event.router.RouterControlLoopEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.router.InterfaceStatus; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; @@ -36,6 +37,7 @@ private void registerListeners() { EventManager.registerHandler(this, MessageTunnelEstablishedEvent.class); EventManager.registerHandler(this, MessageTunnelClosedEvent.class); EventManager.registerHandler(this, RouterStatusEvent.class); + EventManager.registerHandler(this, RouterControlLoopEvent.class); } private void createUIComponents() { From c2cc5cf40cc7e18d2f88ce94def1212218f42aea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:24:51 +0100 Subject: [PATCH 28/60] Update MessageTunnelManager.java --- .../p2p/router/data/message/tunnel/MessageTunnelManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 9e01e233..db13fc5e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -124,6 +124,7 @@ public void sendTunnelRequest(MessageTunnel tunnel) { */ public void sendTunnelResponse(MessageTunnel tunnel) { //Sending a tunnel request. + System.out.println("Sending tunnel response"); NetworkMessage tunnelRequest = router.networkMessageManager.constructMessage(tunnel, new TunnelEstablishResponseMessage(Node.self.getIdentity().getPublicKey()), NetworkMessage.MessageDirection.TO_ORIGIN); router.networkMessageManager.forwardMessage(tunnelRequest, Node.self); } From 17597be108c5ac39d06cf2a5d737d1cd2d2bb2c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:40:36 +0100 Subject: [PATCH 29/60] a --- .../data/message/tunnel/MessageTunnel.java | 21 +++++++------------ .../message/tunnel/MessageTunnelManager.java | 11 ++++------ 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 623f387f..6b6b8756 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -269,23 +269,16 @@ public void decryptMsgSharedSecret(NetworkMessage message) { * @return */ public MessageTunnelState getTunnelState() { - if(nextNode == null && previousNode == null) { - return MessageTunnelState.NOT_ESTABLISHED; - } - if(nextNode != Node.self && previousNode != Node.self) { - return MessageTunnelState.HOSTED; - } - if(origin.equals(Node.self.getIdentity().getNetworkId())) { - if(getSymmetricKey() != null) { - return MessageTunnelState.ESTABLISHED; - } else { - return MessageTunnelState.ESTABLISHING; - } - } if(getSymmetricKey() != null) { return MessageTunnelState.ESTABLISHED; } - return MessageTunnelState.NOT_ESTABLISHED; + else if(side != MessageTunnelSide.UNDEFINED) { + return MessageTunnelState.ESTABLISHING; + } else if(previousNode != null && nextNode != null) { + return MessageTunnelState.HOSTED; + } else { + return MessageTunnelState.NOT_ESTABLISHED; + } } public MessageTunnelSide getSide() { diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index db13fc5e..90b7ad20 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -132,14 +132,11 @@ public void sendTunnelResponse(MessageTunnel tunnel) { * Gets or creates a message tunnel. * @return */ - public MessageTunnel getTunnel(NetworkID nodeA, NetworkID nodeB) { + public MessageTunnel getTunnel(NetworkID origin, NetworkID destination) { //Finding an existing tunnel. - for (MessageTunnel tunnel : - messageTunnels) { - if(tunnel.getOrigin().equals(nodeA) && tunnel.getDestination().equals(nodeB)) { - return tunnel; - } - if(tunnel.getOrigin().equals(nodeB) && tunnel.getDestination().equals(nodeA)) { + for (int i = 0; i < messageTunnels.size(); i++) { + MessageTunnel tunnel = messageTunnels.get(i); + if(tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { return tunnel; } } From 39190fda48cad860b2e2e33a182f2a6d42f7d2e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:48:00 +0100 Subject: [PATCH 30/60] Update NetworkMessageManager.java --- .../p2p/router/data/message/NetworkMessageManager.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index a3467c47..3458336d 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -142,6 +142,7 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { //Getting the next node in the tunnel. MessageTunnel tunnel = router.messageTunnelManager.getTunnel(message.getOrigin(), message.getDestination()); if(tunnel == null) { + logger.info("Tunnel for message: {} not found, creating one..."); tunnel = router.messageTunnelManager.createTunnel(message.getOrigin(), message.getDestination(), MessageTunnelSide.UNDEFINED); } @@ -240,8 +241,7 @@ public void onEventCalled(Event e) { MessageTunnel tunnel = messageTunnelEstablishedEvent.messageTunnel; if(messageTunnelEstablishedEvent.establishDirection == NetworkMessage.MessageDirection.TO_DESTINATION) { - logger.info("Sending {} queued messages through the established tunnel: \n{}", tunnel.messageQueue.size(), - NetworkID.getStringValue(tunnel.getOtherPublicKey().getEncoded())); + logger.info("Sending {} queued messages through the established tunnel: \n{}", tunnel.messageQueue.size(), tunnel); //Sending messages through the tunnel. for (NetworkMessage msg : From 022e74145654deb2328fa690ea413a1fe451adb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 01:49:06 +0100 Subject: [PATCH 31/60] Update NetworkMessageManager.java --- .../undernet/p2p/router/data/message/NetworkMessageManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 3458336d..6fd5786d 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -142,7 +142,7 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { //Getting the next node in the tunnel. MessageTunnel tunnel = router.messageTunnelManager.getTunnel(message.getOrigin(), message.getDestination()); if(tunnel == null) { - logger.info("Tunnel for message: {} not found, creating one..."); + logger.info("Tunnel for message: {} not found, creating one...", message); tunnel = router.messageTunnelManager.createTunnel(message.getOrigin(), message.getDestination(), MessageTunnelSide.UNDEFINED); } From 610b36370af8e349f9dbe4233076d736418a6e26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 02:04:10 +0100 Subject: [PATCH 32/60] g --- .../me/matoosh/undernet/p2p/router/Router.java | 17 ++++++++++++----- .../data/message/NetworkMessageManager.java | 9 +++++++++ .../data/message/tunnel/MessageTunnel.java | 2 +- .../message/tunnel/MessageTunnelManager.java | 15 --------------- 4 files changed, 22 insertions(+), 21 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index df02d9e9..3de4cdb8 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -300,13 +300,20 @@ public ArrayList getConnectedNodes() { */ public ArrayList getRemoteNodes() { if(remoteNodes.size() + 2 == connectedNodes.size()) return remoteNodes; + remoteNodes.clear(); - remoteNodes = new ArrayList<>(); - for (int i = 0; i < connectedNodes.size(); i++) { - Node n = connectedNodes.get(i); - + for (Node n : getConnectedNodes()) { if (n.getAddress() != null && !Node.isLocalAddress(n.getAddress())) { - remoteNodes.add(n); + boolean duplicate = false; + for (Node no : + remoteNodes) { + if(no.getAddress().equals(n.getAddress())) { + duplicate = true; + } + } + if(!duplicate) { + remoteNodes.add(n); + } } } return remoteNodes; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 6fd5786d..30117a53 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -52,7 +52,16 @@ public void sendMessage(MsgBase content, NetworkID recipient) { //Creating a tunnel if doesn't exist already. messageTunnel = router.messageTunnelManager.createTunnel(Node.self.getIdentity().getNetworkId(), recipient, MessageTunnelSide.ORIGIN); } + sendMessage(content, messageTunnel); + } + /** + * Constructs a message and starts the sending process to the other node. + * Uses the specified message tunnel. + * @param content + * @param messageTunnel + */ + public void sendMessage(MsgBase content, MessageTunnel messageTunnel) { //Constructing the message. NetworkMessage message = constructMessage(messageTunnel, content, NetworkMessage.MessageDirection.TO_DESTINATION); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 6b6b8756..1289dd3e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -309,7 +309,7 @@ public void sendMessage(MsgBase content) { logger.info("Sending message, tunnel side {}", this.side); if(side == MessageTunnelSide.ORIGIN || side == MessageTunnelSide.UNDEFINED) { //TO_DESTINATION - UnderNet.router.networkMessageManager.sendMessage(content, getDestination()); + UnderNet.router.networkMessageManager.sendMessage(content, this); } else if (side == MessageTunnelSide.DESTINATION){ //TO_ORIGIN UnderNet.router.networkMessageManager.sendResponse(content, this); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 90b7ad20..6f15f598 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -88,21 +88,6 @@ public void closeTunnelsOnDisconnect(Node disconnected) { public void closeTunnel(MessageTunnel tunnel) { logger.info("Closing tunnel: {}", tunnel); messageTunnels.remove(tunnel); - if(tunnel.getSide() == MessageTunnelSide.ORIGIN) { - for (MessageTunnel tunn : - messageTunnels) { - if(tunn.getDestination().equals(Node.self)) { - messageTunnels.remove(tunn); - } - } - } else if(tunnel.getSide() == MessageTunnelSide.DESTINATION) { - for (MessageTunnel tunn : - messageTunnels) { - if(tunn.getOrigin().equals(Node.self)) { - messageTunnels.remove(tunn); - } - } - } EventManager.callEvent(new MessageTunnelClosedEvent(tunnel)); } From c02b2410852745180e615aef98870e4b473d3491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 02:10:15 +0100 Subject: [PATCH 33/60] Update ResourceManager.java --- .../undernet/p2p/router/data/resource/ResourceManager.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 52816a8e..6c2bcb89 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -328,8 +328,7 @@ else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.RE //Closing the streams. transferFinishedEvent.transferHandler.close(); - if(transferFinishedEvent.transferHandler.getTunnel().getSide() == MessageTunnelSide.ORIGIN) - transferFinishedEvent.transferHandler.getTunnel().close(); + router.messageTunnelManager.closeTunnel(transferFinishedEvent.transferHandler.getTunnel()); //Removing from the list. if(transferFinishedEvent.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { From 73f2a4b5d470ea848630b6c2a55f2a6c5162765d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 02:22:48 +0100 Subject: [PATCH 34/60] ss --- .../src/main/java/me/matoosh/undernet/p2p/router/Router.java | 5 +++-- .../p2p/router/data/message/tunnel/MessageTunnel.java | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 3de4cdb8..56a482b7 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -221,8 +221,9 @@ private void controlLoop() { } //Sending control message to tunnels. - for (MessageTunnel tunnel : - messageTunnelManager.messageTunnels) { + for (int i = 0; i < messageTunnelManager.messageTunnels.size(); i++) { + MessageTunnel tunnel = messageTunnelManager.messageTunnels.get(i); + if(tunnel.getSide() == MessageTunnelSide.ORIGIN && tunnel.getNextNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); else if(tunnel.getSide() == MessageTunnelSide.DESTINATION && tunnel.getPreviousNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); else if(System.currentTimeMillis() > tunnel.getLastMessageTime() + 2*controlLoopInterval*1000) messageTunnelManager.closeTunnel(tunnel); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 1289dd3e..d6908704 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -186,6 +186,7 @@ public NetworkID getDestination() { * @return */ public Node getPreviousNode() {return this.previousNode; } + /** * Gets the next node. * @return From 42506ac66311e3a62faa552646229e6a1745d942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 13:27:32 +0100 Subject: [PATCH 35/60] Keep alive feature for tunnels. --- .../matoosh/undernet/p2p/router/Router.java | 131 ++++++++-------- .../data/message/tunnel/MessageTunnel.java | 143 +++++++++++++----- .../message/tunnel/MessageTunnelManager.java | 28 ++-- 3 files changed, 191 insertions(+), 111 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 56a482b7..25b62f6d 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -46,6 +46,14 @@ */ public class Router extends EventHandler { + /** + * The interval of the control loop. + */ + public static final int controlLoopInterval = 30; + /** + * The logger. + */ + public static Logger logger = LoggerFactory.getLogger(Router.class); /** * The client of this router. * Used for establishing connections with other nodes. @@ -60,8 +68,6 @@ public class Router extends EventHandler { * The timer used for periodically running the control function. */ public ScheduledExecutorService timer; - private ScheduledFuture timerHandle; - /** * The current status of the router. */ @@ -86,17 +92,11 @@ public class Router extends EventHandler { * The message tunnel manager. */ public MessageTunnelManager messageTunnelManager; - + private ScheduledFuture timerHandle; /** * The number of reconnect attempts, the router attempted. */ private int reconnectNum = 0; - - /** - * The interval of the control loop. - */ - public static final int controlLoopInterval = 30; - /** * Nodes the router is connected to at the moment. */ @@ -106,17 +106,12 @@ public class Router extends EventHandler { */ private ArrayList remoteNodes = new ArrayList<>(); - /** - * The logger. - */ - public static Logger logger = LoggerFactory.getLogger(Router.class); - /** * Sets up the router. */ public void setup() { //Checking if the router is not running. - if(status != InterfaceStatus.STOPPED) { + if (status != InterfaceStatus.STOPPED) { logger.warn("Can't setup the router, while it's running!"); return; } @@ -182,7 +177,7 @@ private void setupSecurity() { */ public void start(NetworkIdentity networkIdentity) { //Checking whether the router is already running. - if(status != InterfaceStatus.STOPPED) { + if (status != InterfaceStatus.STOPPED) { logger.warn("Can't start, because the router is already running!"); return; } @@ -191,7 +186,7 @@ public void start(NetworkIdentity networkIdentity) { Node.self.setIdentity(networkIdentity); //Checking whether the setup needs to be ran. - if(server == null || client == null) { + if (server == null || client == null) { setup(); } @@ -200,7 +195,7 @@ public void start(NetworkIdentity networkIdentity) { //Starting the client. Using a separate thread for blocking api. new Thread(() -> client.start()).start(); - + //Starting the server. Using a separate thread for blocking api. new Thread(() -> server.start()).start(); } @@ -224,10 +219,13 @@ private void controlLoop() { for (int i = 0; i < messageTunnelManager.messageTunnels.size(); i++) { MessageTunnel tunnel = messageTunnelManager.messageTunnels.get(i); - if(tunnel.getSide() == MessageTunnelSide.ORIGIN && tunnel.getNextNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); - else if(tunnel.getSide() == MessageTunnelSide.DESTINATION && tunnel.getPreviousNode() == Node.self) messageTunnelManager.closeTunnel(tunnel); - else if(System.currentTimeMillis() > tunnel.getLastMessageTime() + 2*controlLoopInterval*1000) messageTunnelManager.closeTunnel(tunnel); - else tunnel.sendMessage(new TunnelControlMessage()); + if (tunnel.getSide() == MessageTunnelSide.ORIGIN && tunnel.getNextNode() == Node.self) + messageTunnelManager.closeTunnel(tunnel); + else if (tunnel.getSide() == MessageTunnelSide.DESTINATION && tunnel.getPreviousNode() == Node.self) + messageTunnelManager.closeTunnel(tunnel); + else if (System.currentTimeMillis() > tunnel.getLastMessageTime() + 2 * controlLoopInterval * 1000) + messageTunnelManager.closeTunnel(tunnel); + else if (tunnel.isKeepAlive()) tunnel.sendMessage(new TunnelControlMessage()); } EventManager.callEvent(new RouterControlLoopEvent(this)); @@ -238,7 +236,7 @@ private void controlLoop() { */ public void stop() { //Checking if the server is running. - if(status == InterfaceStatus.STOPPED) { + if (status == InterfaceStatus.STOPPED) { logger.warn("Can't stop the router, as it is not running!"); return; } @@ -250,11 +248,11 @@ public void stop() { timerHandle.cancel(true); //Stops the client. - if(client != null) { + if (client != null) { client.stop(); } //Stops the server. - if(server != null) { + if (server != null) { server.stop(); } @@ -266,6 +264,7 @@ public void stop() { /** * Connects directly to a node. + * * @param node */ public void connectNode(Node node) { @@ -274,13 +273,14 @@ public void connectNode(Node node) { /** * Disconnects from a node. + * * @param node */ public void disconnectNode(Node node) { - for (Channel channel: - client.channels) { + for (Channel channel : + client.channels) { Node channelNode = channel.attr(ClientNetworkMessageHandler.ATTRIBUTE_KEY_SERVER_NODE).get(); - if(channelNode != null && channelNode == node) { + if (channelNode != null && channelNode == node) { channel.close(); } } @@ -288,6 +288,7 @@ public void disconnectNode(Node node) { /** * Gets all of the connected nodes. + * * @return */ public ArrayList getConnectedNodes() { @@ -297,10 +298,11 @@ public ArrayList getConnectedNodes() { /** * Gets all of the remote connected nodes. * Omits all of the local nodes. + * * @return */ public ArrayList getRemoteNodes() { - if(remoteNodes.size() + 2 == connectedNodes.size()) return remoteNodes; + if (remoteNodes.size() + 2 == connectedNodes.size()) return remoteNodes; remoteNodes.clear(); for (Node n : getConnectedNodes()) { @@ -308,11 +310,11 @@ public ArrayList getRemoteNodes() { boolean duplicate = false; for (Node no : remoteNodes) { - if(no.getAddress().equals(n.getAddress())) { + if (no.getAddress().equals(n.getAddress())) { duplicate = true; } } - if(!duplicate) { + if (!duplicate) { remoteNodes.add(n); } } @@ -354,6 +356,7 @@ private void registerHandlers() { } //EVENTS + /** * Called when the handled event is called. * @@ -362,21 +365,21 @@ private void registerHandlers() { @Override public void onEventCalled(Event e) { //Connection established. - if(e.getClass() == ChannelCreatedEvent.class) { - ChannelCreatedEvent establishedEvent = (ChannelCreatedEvent)e; + if (e.getClass() == ChannelCreatedEvent.class) { + ChannelCreatedEvent establishedEvent = (ChannelCreatedEvent) e; logger.debug("New connection established with: " + establishedEvent.other); } //Connection dropped. - else if(e.getClass() == ChannelClosedEvent.class) { - ChannelClosedEvent droppedEvent = (ChannelClosedEvent)e; + else if (e.getClass() == ChannelClosedEvent.class) { + ChannelClosedEvent droppedEvent = (ChannelClosedEvent) e; } //Connection error. - else if(e.getClass() == ChannelErrorEvent.class) { - ChannelErrorEvent errorEvent = (ChannelErrorEvent)e; + else if (e.getClass() == ChannelErrorEvent.class) { + ChannelErrorEvent errorEvent = (ChannelErrorEvent) e; //TODO: Handle the error. - } else if(e.getClass() == RouterStatusEvent.class) { - RouterStatusEvent statusEvent = (RouterStatusEvent)e; - switch(statusEvent.newStatus) { + } else if (e.getClass() == RouterStatusEvent.class) { + RouterStatusEvent statusEvent = (RouterStatusEvent) e; + switch (statusEvent.newStatus) { case STOPPED: onConnectionEnded(); break; @@ -389,59 +392,61 @@ else if(e.getClass() == ChannelErrorEvent.class) { case STOPPING: break; } - } else if(e.getClass() == RouterErrorEvent.class) { + } else if (e.getClass() == RouterErrorEvent.class) { onRouterError((RouterErrorEvent) e); - } else if(e.getClass() == ServerStatusEvent.class) { - ServerStatusEvent statusEvent = (ServerStatusEvent)e; - if(statusEvent.newStatus.equals(InterfaceStatus.STARTED)) { + } else if (e.getClass() == ServerStatusEvent.class) { + ServerStatusEvent statusEvent = (ServerStatusEvent) e; + if (statusEvent.newStatus.equals(InterfaceStatus.STARTED)) { //In this case client doesn't yet have to be started. - if(client.status.equals(InterfaceStatus.STARTED)) { + if (client.status.equals(InterfaceStatus.STARTED)) { //Both parts of the router started successfully. onRouterStarted(); } - } else if(statusEvent.newStatus.equals(InterfaceStatus.STOPPED)) { - if(client.status.equals(InterfaceStatus.STOPPED)) { + } else if (statusEvent.newStatus.equals(InterfaceStatus.STOPPED)) { + if (client.status.equals(InterfaceStatus.STOPPED)) { //Both parts of the router stopped successfully. onRouterStopped(); } } - } else if(e.getClass() == ClientStatusEvent.class) { + } else if (e.getClass() == ClientStatusEvent.class) { ClientStatusEvent statusEvent = (ClientStatusEvent) e; - if(statusEvent.newStatus.equals(InterfaceStatus.STARTED)) { - if(server.status.equals(InterfaceStatus.STARTED)) { + if (statusEvent.newStatus.equals(InterfaceStatus.STARTED)) { + if (server.status.equals(InterfaceStatus.STARTED)) { //Both parts of the router started succesfully. onRouterStarted(); } - } else if(statusEvent.newStatus.equals(InterfaceStatus.STOPPED)) { - if(server.status.equals(InterfaceStatus.STOPPED)) { + } else if (statusEvent.newStatus.equals(InterfaceStatus.STOPPED)) { + if (server.status.equals(InterfaceStatus.STOPPED)) { //Both parts of the router stopped successfully. onRouterStopped(); } } } else if (e.getClass() == ClientExceptionEvent.class) { - ClientExceptionEvent exceptionEvent = (ClientExceptionEvent)e; + ClientExceptionEvent exceptionEvent = (ClientExceptionEvent) e; logger.error("Exception occurred with the client!", exceptionEvent.exception); - if(!UnderNet.networkConfig.ignoreExceptions()) { + if (!UnderNet.networkConfig.ignoreExceptions()) { this.stop(); } - } else if(e.getClass() == ServerExceptionEvent.class) { - ServerExceptionEvent exceptionEvent = (ServerExceptionEvent)e; + } else if (e.getClass() == ServerExceptionEvent.class) { + ServerExceptionEvent exceptionEvent = (ServerExceptionEvent) e; logger.error("Exception occurred with the server!", exceptionEvent.exception); - if(!UnderNet.networkConfig.ignoreExceptions()) { + if (!UnderNet.networkConfig.ignoreExceptions()) { this.stop(); } } } + /** * Called when a router error occurs. * This means we can't continue and have to restart the connection. + * * @param e */ private void onRouterError(RouterErrorEvent e) { //Printing the error. - if(e.exception.getMessage() != null) { + if (e.exception.getMessage() != null) { logger.error("There was a problem with the UnderNet router: " + e.exception.getMessage()); } e.exception.printStackTrace(); @@ -450,7 +455,7 @@ private void onRouterError(RouterErrorEvent e) { e.router.stop(); //Reconnecting if possible. - if(e.router.status != InterfaceStatus.STOPPED && e.shouldReconnect) { + if (e.router.status != InterfaceStatus.STOPPED && e.shouldReconnect) { reconnectNum++; //Checking if we should reconnect. if (reconnectNum > UnderNet.networkConfig.maxReconnectCount()) { @@ -467,16 +472,17 @@ private void onRouterError(RouterErrorEvent e) { */ private void onRouterStarted() { //Setting the status to started. - if(status != InterfaceStatus.STARTED) { - EventManager.callEvent(new RouterStatusEvent(this, InterfaceStatus.STARTED)); + if (status != InterfaceStatus.STARTED) { + EventManager.callEvent(new RouterStatusEvent(this, InterfaceStatus.STARTED)); } } + /** * Called when the router stops. */ private void onRouterStopped() { //Setting the status to stopped. - if(status != InterfaceStatus.STOPPED) { + if (status != InterfaceStatus.STOPPED) { EventManager.callEvent(new RouterStatusEvent(this, InterfaceStatus.STOPPED)); //GC @@ -484,6 +490,7 @@ private void onRouterStopped() { System.gc(); } } + /** * Called when the connection to the network ends. */ diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index d6908704..7a02a28d 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -28,15 +28,28 @@ */ public class MessageTunnel { //This part is present on all the part taking nodes. Identifies the tunnel. + /** + * The logger of the class. + */ + public static Logger logger = LoggerFactory.getLogger(MessageTunnel.class); + /** + * The secure random generator. + */ + private static SecureRandom secureRandom = new SecureRandom(); + /** + * The list of messages awaiting sending. + */ + public ArrayList messageQueue = new ArrayList(); /** * The network id of the origin node. */ private NetworkID origin; + + //This part is present only on the receiving ends of the tunnel. /** * The network id of the other. */ private NetworkID destination; - /** * The next neighboring node to the destination. */ @@ -45,54 +58,39 @@ public class MessageTunnel { * The next neighboring node to the origin. */ private Node previousNode; - - //This part is present only on the receiving ends of the tunnel. /** * The public key of the other. * Used by self to encrypt messages for the other side of the tunnel. */ private PublicKey otherPublicKey; - /** * The shared secret. * Calculated after the public keys are exchanged. */ private byte[] sharedSecret; - /** * The shared symmetric key used to encrypt messages. * Derived from the shared secret and self and other public keys. */ private SecretKeySpec derivedSymmetricKey; + //Messages /** * The side of the tunnel. */ private MessageTunnelSide side; - /** * The time that the last message was received from the tunnel. */ private long lastMessageTime; - - //Messages - /** - * The list of messages awaiting sending. - */ - public ArrayList messageQueue = new ArrayList(); - /** - * The secure random generator. + * Whether the tunnel should be kept alive. */ - private static SecureRandom secureRandom = new SecureRandom(); - - /** - * The logger of the class. - */ - public static Logger logger = LoggerFactory.getLogger(MessageTunnel.class); + private boolean keepAlive = false; /** * Creates a hosted message tunnel. + * * @param destination * @param origin */ @@ -102,8 +100,10 @@ public MessageTunnel(NetworkID origin, NetworkID destination) { this.side = MessageTunnelSide.UNDEFINED; this.lastMessageTime = System.currentTimeMillis() + 2 * Router.controlLoopInterval; } + /** * Creates a message tunnel. + * * @param destination * @param origin */ @@ -117,10 +117,12 @@ public MessageTunnel(NetworkID origin, NetworkID destination, MessageTunnelSide public PublicKey getOtherPublicKey() { return otherPublicKey; } + public void setOtherPublicKey(PublicKey publicKey) { logger.info("Set the other public key to: {}", publicKey); this.otherPublicKey = publicKey; } + /** * Calculates the shared secret key of the tunnel. */ @@ -162,6 +164,7 @@ public void close() { /** * Returns the shared secret of the tunnel. + * * @return */ public SecretKeySpec getSymmetricKey() { @@ -170,37 +173,77 @@ public SecretKeySpec getSymmetricKey() { /** * Gets the other. + * * @return */ public NetworkID getDestination() { return this.destination; } + /** * Gets the origin. + * * @return */ - public NetworkID getOrigin() {return this.origin;} + public NetworkID getOrigin() { + return this.origin; + } /** * Gets the previous node. + * * @return */ - public Node getPreviousNode() {return this.previousNode; } + public Node getPreviousNode() { + return this.previousNode; + } /** - * Gets the next node. - * @return + * Sets the previous node. + * + * @param previousNode */ - public Node getNextNode() {return this.nextNode; } public void setPreviousNode(Node previousNode) { this.previousNode = previousNode; } + + /** + * Gets the next node. + * + * @return + */ + public Node getNextNode() { + return this.nextNode; + } + + /** + * Sets the next node. + * + * @param nextNode + */ public void setNextNode(Node nextNode) { this.nextNode = nextNode; } + /** + * Returns whether the tunnel should be kept alive. + * @return + */ + public boolean isKeepAlive() { + return keepAlive; + } + + /** + * Sets whether the tunnel should be kept alive. + * @param keepAlive + */ + public void setKeepAlive(boolean keepAlive) { + this.keepAlive = keepAlive; + } + /** * Encrypts bytes with the shared symmetric key. + * * @param message */ public void encryptMsgSymmetric(NetworkMessage message) { @@ -231,11 +274,12 @@ public void encryptMsgSymmetric(NetworkMessage message) { /** * Decrypts bytes with the shared symmetric key. + * * @param message */ public void decryptMsgSharedSecret(NetworkMessage message) { //Checking if the symmetric key exists. - if(getSymmetricKey() == null) { + if (getSymmetricKey() == null) { logger.warn("Missing symmetric key for tunnel: {}", this); return; } @@ -267,51 +311,72 @@ public void decryptMsgSharedSecret(NetworkMessage message) { /** * Gets the current tunnel state. + * * @return */ public MessageTunnelState getTunnelState() { - if(getSymmetricKey() != null) { + if (getSymmetricKey() != null) { return MessageTunnelState.ESTABLISHED; - } - else if(side != MessageTunnelSide.UNDEFINED) { + } else if (side != MessageTunnelSide.UNDEFINED) { return MessageTunnelState.ESTABLISHING; - } else if(previousNode != null && nextNode != null) { + } else if (previousNode != null && nextNode != null) { return MessageTunnelState.HOSTED; } else { return MessageTunnelState.NOT_ESTABLISHED; } } + /** + * Gets the current side of the tunnel. + * + * @return + */ public MessageTunnelSide getSide() { return side; } + /** + * Sets the current side of the tunnel. + * + * @param side + */ public void setSide(MessageTunnelSide side) { this.side = side; } + /** + * Gets the time the last message was received on the tunnel. + * + * @return + */ public long getLastMessageTime() { return this.lastMessageTime; } + /** + * Sets the time the last message was received on the tunnel. + * + * @param currentTimeMillis + */ public void setLastMessageTime(long currentTimeMillis) { this.lastMessageTime = currentTimeMillis; } /** * Sends the specified message. + * * @param content */ public void sendMessage(MsgBase content) { - if(getTunnelState() == MessageTunnelState.HOSTED) { + if (getTunnelState() == MessageTunnelState.HOSTED) { logger.warn("Can't send messages through hosted tunnels!"); return; } logger.info("Sending message, tunnel side {}", this.side); - if(side == MessageTunnelSide.ORIGIN || side == MessageTunnelSide.UNDEFINED) { + if (side == MessageTunnelSide.ORIGIN || side == MessageTunnelSide.UNDEFINED) { //TO_DESTINATION UnderNet.router.networkMessageManager.sendMessage(content, this); - } else if (side == MessageTunnelSide.DESTINATION){ + } else if (side == MessageTunnelSide.DESTINATION) { //TO_ORIGIN UnderNet.router.networkMessageManager.sendResponse(content, this); } @@ -319,21 +384,21 @@ public void sendMessage(MsgBase content) { @Override public String toString() { - if(getTunnelState() == MessageTunnelState.HOSTED) { + if (getTunnelState() == MessageTunnelState.HOSTED) { return String.format("{(%1$s) <-> (%2$s) <-> (%3$s)}", getOrigin(), Node.self, getDestination()); } - if(getSide() == MessageTunnelSide.ORIGIN) { - if(getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { + if (getSide() == MessageTunnelSide.ORIGIN) { + if (getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { return String.format("{(%1$s) (%2$s)}", Node.self, getDestination()); } - if(getTunnelState() == MessageTunnelState.ESTABLISHED) { + if (getTunnelState() == MessageTunnelState.ESTABLISHED) { return String.format("{(%1$s) <-> (%2$s)}", Node.self, getDestination()); } } else { - if(getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { + if (getTunnelState() == MessageTunnelState.NOT_ESTABLISHED || getTunnelState() == MessageTunnelState.ESTABLISHING) { return String.format("{(%1$s) (%2$s)}", getOrigin(), Node.self); } - if(getTunnelState() == MessageTunnelState.ESTABLISHED) { + if (getTunnelState() == MessageTunnelState.ESTABLISHED) { return String.format("{(%1$s) <-> (%2$s)}", getOrigin(), Node.self); } } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 6f15f598..ae9ce855 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -21,15 +21,14 @@ * Manages message tunnels. */ public class MessageTunnelManager extends Manager { - /** - * The currently active message tunnels. - */ - public ArrayList messageTunnels = new ArrayList<>(); - /** * The class logger. */ public static final Logger logger = LoggerFactory.getLogger(MessageTunnelManager.class); + /** + * The currently active message tunnels. + */ + public ArrayList messageTunnels = new ArrayList<>(); /** * Router specification is mandatory. @@ -42,6 +41,7 @@ public MessageTunnelManager(Router router) { /** * Creates a new message tunnel instance and adds it to the tunnel list. + * * @return */ public MessageTunnel createTunnel(NetworkID origin, NetworkID destination, MessageTunnelSide side) { @@ -52,6 +52,7 @@ public MessageTunnel createTunnel(NetworkID origin, NetworkID destination, Messa /** * Establishes a tunnel. + * * @param tunnel */ public void establishTunnel(MessageTunnel tunnel) { @@ -63,6 +64,7 @@ public void establishTunnel(MessageTunnel tunnel) { /** * Closes tunnels when a node disconnects. + * * @param disconnected */ public void closeTunnelsOnDisconnect(Node disconnected) { @@ -83,6 +85,7 @@ public void closeTunnelsOnDisconnect(Node disconnected) { /** * Closes the given message tunnel. * Doesn't send the close message, for that use the tunnel close() message. + * * @param tunnel */ public void closeTunnel(MessageTunnel tunnel) { @@ -95,6 +98,7 @@ public void closeTunnel(MessageTunnel tunnel) { /** * Sends a tunnel creation request to the destination of the tunnel. + * * @param tunnel */ public void sendTunnelRequest(MessageTunnel tunnel) { @@ -105,6 +109,7 @@ public void sendTunnelRequest(MessageTunnel tunnel) { /** * Sends a tunnel creation response to the origin of the tunnel. + * * @param tunnel */ public void sendTunnelResponse(MessageTunnel tunnel) { @@ -113,15 +118,17 @@ public void sendTunnelResponse(MessageTunnel tunnel) { NetworkMessage tunnelRequest = router.networkMessageManager.constructMessage(tunnel, new TunnelEstablishResponseMessage(Node.self.getIdentity().getPublicKey()), NetworkMessage.MessageDirection.TO_ORIGIN); router.networkMessageManager.forwardMessage(tunnelRequest, Node.self); } + /** * Gets or creates a message tunnel. + * * @return */ public MessageTunnel getTunnel(NetworkID origin, NetworkID destination) { //Finding an existing tunnel. for (int i = 0; i < messageTunnels.size(); i++) { MessageTunnel tunnel = messageTunnels.get(i); - if(tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { + if (tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { return tunnel; } } @@ -141,13 +148,14 @@ protected void registerHandlers() { /** * Handles events. + * * @param e */ @Override public void onEventCalled(Event e) { - if(e instanceof MessageReceivedEvent) { - MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent)e; - if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_ESTABLISH_REQUEST) { + if (e instanceof MessageReceivedEvent) { + MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) e; + if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_ESTABLISH_REQUEST) { //Called on the destination of the tunnel. TunnelEstablishRequestMessage tunnelEstablishRequestMessage = (TunnelEstablishRequestMessage) messageReceivedEvent.networkMessage.getContent(); //Creating a new tunnel object. @@ -165,7 +173,7 @@ public void onEventCalled(Event e) { //Calling the established event. EventManager.callEvent(new MessageTunnelEstablishedEvent(messageReceivedEvent.networkMessage.getTunnel(), NetworkMessage.MessageDirection.TO_ORIGIN)); - } else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_ESTABLISH_RESPONSE) { + } else if (messageReceivedEvent.networkMessage.getContent().getType() == MsgType.TUNNEL_ESTABLISH_RESPONSE) { //Called on the origin of the tunnel. TunnelEstablishResponseMessage tunnelEstablishResponseMessage = (TunnelEstablishResponseMessage) messageReceivedEvent.networkMessage.getContent(); MessageTunnel tunnel = getTunnel(tunnelEstablishResponseMessage.getNetworkMessage().getOrigin(), tunnelEstablishResponseMessage.getNetworkMessage().getDestination()); From 67174fb8b9d1f893ca1291cf3da98cf6074c16b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 13:57:48 +0100 Subject: [PATCH 36/60] Transfer id improvements --- .../matoosh/undernet/p2p/router/data/message/MsgType.java | 2 +- .../p2p/router/data/message/ResourceDataChunkRequest.java | 6 +++--- .../p2p/router/data/message/ResourceDataMessage.java | 6 +++--- .../p2p/router/data/message/ResourceInfoMessage.java | 6 +++--- .../undernet/p2p/router/data/resource/FileResource.java | 4 ++-- .../matoosh/undernet/p2p/router/data/resource/Resource.java | 4 ++-- .../undernet/p2p/router/data/resource/ResourceManager.java | 3 ++- .../router/data/resource/transfer/FileTransferHandler.java | 2 +- .../data/resource/transfer/ResourceTransferHandler.java | 6 +++--- 9 files changed, 20 insertions(+), 19 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java index ee6b4b6a..06596a17 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/MsgType.java @@ -17,7 +17,7 @@ public enum MsgType { RES_INFO((short) 6), //Info about a transferred resource. RES_PULL((short) 7), //Contains the Network id of the pulled resource. RES_DATA((short) 8), //Data of a resource. - RES_DATA_REQUEST((short) 9), //Confirm data of a resource. + RES_DATA_REQUEST((short) 9), //Request data of a resource. TUNNEL_CONTROL((short) 10), //Check if a tunnel is alive. TUNNEL_CLOSE_REQUEST((short) 11), //Request closure of a tunnel. UNKNOWN((short)-1); //Unknown msg type. diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataChunkRequest.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataChunkRequest.java index 99efe095..6a46bc82 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataChunkRequest.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataChunkRequest.java @@ -7,14 +7,14 @@ public class ResourceDataChunkRequest extends MsgBase { /** * The transfer id of the data. */ - private byte transferId; + private int transferId; /** * The id of the chunk requested. */ private int chunkId; - public ResourceDataChunkRequest(byte transferId, int chunkId) { + public ResourceDataChunkRequest(int transferId, int chunkId) { this.transferId = transferId; this.chunkId = chunkId; } @@ -24,7 +24,7 @@ public MsgType getType() { return MsgType.RES_DATA_REQUEST; } - public byte getTransferId() { + public int getTransferId() { return transferId; } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataMessage.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataMessage.java index 1148751a..488704f0 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataMessage.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceDataMessage.java @@ -14,7 +14,7 @@ public class ResourceDataMessage extends MsgBase { /** * The transfer id of the data. */ - private byte transferId; + private int transferId; /** * The id of the file chunk @@ -25,7 +25,7 @@ public class ResourceDataMessage extends MsgBase { * Creates a new resource message given the resource. * @param data */ - public ResourceDataMessage(byte[] data, byte transferId, int chunkId) { + public ResourceDataMessage(byte[] data, int transferId, int chunkId) { this.resourceData = data; this.transferId = transferId; this.chunkId = chunkId; @@ -40,7 +40,7 @@ public byte[] getResourceData() { return resourceData; } - public byte getTransferId() { + public int getTransferId() { return transferId; } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceInfoMessage.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceInfoMessage.java index 41f98301..7388c13c 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceInfoMessage.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/ResourceInfoMessage.java @@ -14,9 +14,9 @@ public class ResourceInfoMessage extends MsgBase { /** * The transfer id. */ - private byte transferId; + private int transferId; - public ResourceInfoMessage(ResourceInfo resourceInfo, byte transferId) { + public ResourceInfoMessage(ResourceInfo resourceInfo, int transferId) { this.resourceInfo = resourceInfo; this.transferId = transferId; } @@ -30,7 +30,7 @@ public ResourceInfo getResourceInfo() { return resourceInfo; } - public byte getTransferId() { + public int getTransferId() { return transferId; } } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java index dd0cb455..323e098b 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java @@ -133,9 +133,9 @@ void updateAttributes() { * @return */ @Override - public ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, byte transferId, Router router) { + public ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, int transferId, Router router) { if (resourceTransferType == ResourceTransferType.OUTBOUND) { - transferId = (byte) router.resourceManager.outboundHandlers.size(); + transferId = router.resourceManager.outboundHandlers.size(); } return new FileTransferHandler(this, resourceTransferType, tunnel, transferId, router); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/Resource.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/Resource.java index c90dacb7..b2f17c51 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/Resource.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/Resource.java @@ -120,7 +120,7 @@ public String toString() { /** * Gets the resource transfer handler. */ - public abstract ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, byte transferId, Router router); + public abstract ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, int transferId, Router router); /** * Gets the router. @@ -146,7 +146,7 @@ public ResourceInfo getInfo() { * @param tunnel * @param transferId */ - public void sendInfo(MessageTunnel tunnel, byte transferId) { + public void sendInfo(MessageTunnel tunnel, int transferId) { tunnel.sendMessage(new ResourceInfoMessage(getInfo(), transferId)); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 6c2bcb89..4dfebc2b 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -175,7 +175,7 @@ private void startPush(Resource resource) { */ private void startPush(Resource resource, MessageTunnel tunnel) { //Getting the transfer handler. - ResourceTransferHandler transferHandler = resource.getTransferHandler(ResourceTransferType.OUTBOUND, tunnel, (byte)0, this.router); + ResourceTransferHandler transferHandler = resource.getTransferHandler(ResourceTransferType.OUTBOUND, tunnel, -1, this.router); logger.info("Outbound {} resource transfer, transfer id: {}", resource.getResourceType(), transferHandler.getTransferId()); outboundHandlers.add(transferHandler); @@ -253,6 +253,7 @@ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { //Sending next chunk from handler. for (ResourceTransferHandler transferHandler : outboundHandlers) { + System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && transferHandler.getTransferId() == message.getTransferId()) { logger.info("Sending chunk: {}, of file transfer {}", message.getChunkId(), transferHandler.getResource().getNetworkID()); transferHandler.sendChunk(message.getChunkId()); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index c0a1faed..ddd90d9d 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -53,7 +53,7 @@ public class FileTransferHandler extends ResourceTransferHandler { */ public static Logger logger = LoggerFactory.getLogger(FileTransferHandler.class); - public FileTransferHandler(FileResource resource, ResourceTransferType fileTransferType, MessageTunnel tunnel, byte transferId, Router router) { + public FileTransferHandler(FileResource resource, ResourceTransferType fileTransferType, MessageTunnel tunnel, int transferId, Router router) { super(resource, fileTransferType, tunnel, transferId, router); this.fileLength = Long.parseLong(resource.getInfo().attributes.get(0)); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index b5f12049..fb340af1 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -33,10 +33,10 @@ public abstract class ResourceTransferHandler { /** * The transfer id of the transfer. */ - private byte transferId; + private int transferId; - public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, byte transferId, Router router) { + public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, int transferId, Router router) { this.resource = resource; this.transferType = transferType; this.tunnel = tunnel; @@ -86,7 +86,7 @@ public void setTunnel(MessageTunnel tunnel) { this.tunnel = tunnel; } - public byte getTransferId() { + public int getTransferId() { return transferId; } } From 074295f8b0cb643f7f83e3a0635cfa9f5ca23a4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 14:00:18 +0100 Subject: [PATCH 37/60] Update Router.java --- shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 25b62f6d..9ae5f0de 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -306,6 +306,7 @@ public ArrayList getRemoteNodes() { remoteNodes.clear(); for (Node n : getConnectedNodes()) { + if(n == null) continue; if (n.getAddress() != null && !Node.isLocalAddress(n.getAddress())) { boolean duplicate = false; for (Node no : From f9083c28e5167020514019b53cf541d52c1c1d6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 14:06:13 +0100 Subject: [PATCH 38/60] Update ResourceManager.java --- .../undernet/p2p/router/data/resource/ResourceManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 4dfebc2b..dc870292 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -250,6 +250,7 @@ private void handleResourcePullRequest(ResourcePullMessage message) { * @param message */ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { + logger.info("Handling resource data request, transId: {}", message.getTransferId()); //Sending next chunk from handler. for (ResourceTransferHandler transferHandler : outboundHandlers) { From 5e42dd071cfe79b156725d5a2afcf60d858bbc27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 14:19:22 +0100 Subject: [PATCH 39/60] Update ResourceTransferHandler.java --- .../router/data/resource/transfer/ResourceTransferHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index fb340af1..4d9cfbfd 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -37,6 +37,7 @@ public abstract class ResourceTransferHandler { public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, int transferId, Router router) { + System.out.println("Creeating resource transfer handler: " + transferId); this.resource = resource; this.transferType = transferType; this.tunnel = tunnel; From 97e53c4903109b75552410e3a580729a1d47b580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 14:31:29 +0100 Subject: [PATCH 40/60] Transfer id improvement --- .../undernet/p2p/router/data/resource/FileResource.java | 3 ++- .../undernet/p2p/router/data/resource/ResourceManager.java | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java index 323e098b..06b0e724 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java @@ -135,7 +135,8 @@ void updateAttributes() { @Override public ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, int transferId, Router router) { if (resourceTransferType == ResourceTransferType.OUTBOUND) { - transferId = router.resourceManager.outboundHandlers.size(); + router.resourceManager.lastTransferId++; + transferId = router.resourceManager.lastTransferId; } return new FileTransferHandler(this, resourceTransferType, tunnel, transferId, router); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index dc870292..dea3ce37 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -44,6 +44,11 @@ public class ResourceManager extends Manager { */ public ArrayList inboundHandlers = new ArrayList<>(); + /** + * The last transfer id. + */ + public int lastTransferId = -1; + /** * The logger of the class. */ From ebb6d96e61cfad28451d414e041d98da2a6310ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 14:37:12 +0100 Subject: [PATCH 41/60] a --- .../p2p/router/data/message/NetworkMessageManager.java | 6 +++++- .../undernet/p2p/router/data/resource/ResourceManager.java | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index 30117a53..eb20e6df 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -151,7 +151,11 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { //Getting the next node in the tunnel. MessageTunnel tunnel = router.messageTunnelManager.getTunnel(message.getOrigin(), message.getDestination()); if(tunnel == null) { - logger.info("Tunnel for message: {} not found, creating one...", message); + if(message.getContent() != null) + logger.info("Tunnel for message: {} not found, creating one... {}", message, message.getContent().getType()); + else + logger.info("Tunnel for message: {} not found, creating one...", message); + tunnel = router.messageTunnelManager.createTunnel(message.getOrigin(), message.getDestination(), MessageTunnelSide.UNDEFINED); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index dea3ce37..dd733e0f 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -47,7 +47,7 @@ public class ResourceManager extends Manager { /** * The last transfer id. */ - public int lastTransferId = -1; + public int lastTransferId; /** * The logger of the class. @@ -61,6 +61,7 @@ public class ResourceManager extends Manager { */ public ResourceManager(Router router) { super(router); + this.lastTransferId = -1; } /** From 7dd09af2c02f9be8a26ca743a88148dc8830bc78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 15:24:15 +0100 Subject: [PATCH 42/60] Resource transfer stability improvements --- .../transfer/ResourceTransferErrorEvent.java | 12 ++-- .../transfer/ResourceTransferEvent.java | 6 +- .../ResourceTransferFinishedEvent.java | 20 ++----- .../ResourceTransferStartedEvent.java | 6 +- .../me/matoosh/undernet/p2p/node/Node.java | 6 +- .../data/message/NetworkMessageManager.java | 57 ++++++++++--------- .../message/tunnel/MessageTunnelManager.java | 1 + .../router/data/resource/ResourceManager.java | 15 +---- .../transfer/FileTransferHandler.java | 44 +++++++------- .../transfer/ResourceTransferHandler.java | 46 ++++++++++++++- .../undernet/standalone/uix/MainFrame.java | 6 +- .../uix/dialog/ResourcePullDialog.java | 18 +++--- 12 files changed, 131 insertions(+), 106 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferErrorEvent.java b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferErrorEvent.java index cdc50abe..d7a07d51 100644 --- a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferErrorEvent.java +++ b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferErrorEvent.java @@ -1,6 +1,5 @@ package me.matoosh.undernet.event.resource.transfer; -import me.matoosh.undernet.p2p.router.data.resource.FileResource; import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; /** @@ -12,7 +11,7 @@ public class ResourceTransferErrorEvent extends ResourceTransferEvent { /** * The exception. */ - public Exception exception; + private Exception exception; public ResourceTransferErrorEvent(ResourceTransferHandler transferHandler, Exception exception) { super(transferHandler); @@ -21,11 +20,10 @@ public ResourceTransferErrorEvent(ResourceTransferHandler transferHandler, Excep @Override public void onCalled() { - logger.error("Error occurred transferring resource: " + transferHandler.getResource(), exception); - - //Deleting the remainders of the transferred file. - if(this.transferHandler.getResource() instanceof FileResource) { + logger.error("Error occurred transferring resource: " + getTransferHandler().getResource(), exception); + } - } + public Exception getException() { + return exception; } } diff --git a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferEvent.java b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferEvent.java index af82265a..b04d82e2 100644 --- a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferEvent.java +++ b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferEvent.java @@ -12,9 +12,13 @@ public abstract class ResourceTransferEvent extends Event { /** * The file transfer. */ - public ResourceTransferHandler transferHandler; + private ResourceTransferHandler transferHandler; public ResourceTransferEvent(ResourceTransferHandler transferHandler) { this.transferHandler = transferHandler; } + + public ResourceTransferHandler getTransferHandler() { + return transferHandler; + } } diff --git a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferFinishedEvent.java b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferFinishedEvent.java index e19dc277..096bf4ca 100644 --- a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferFinishedEvent.java +++ b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferFinishedEvent.java @@ -7,28 +7,16 @@ * Called when a resource transfer finishes. */ public class ResourceTransferFinishedEvent extends ResourceTransferEvent { - - private String reason; - - public ResourceTransferFinishedEvent(ResourceTransferHandler transferHandler, String reason) { + public ResourceTransferFinishedEvent(ResourceTransferHandler transferHandler) { super(transferHandler); - this.reason = reason; } @Override public void onCalled() { - if(this.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { - logger.info("Transfer of resource {}, from {}, finished!, {}", this.transferHandler.getResource(), this.transferHandler.getTunnel().getDestination(), this.reason); + if(this.getTransferHandler().getTransferType() == ResourceTransferType.INBOUND) { + logger.info("Transfer of resource {}, from {}, finished!", this.getTransferHandler().getResource(), this.getTransferHandler().getTunnel().getDestination()); } else { - logger.info("Transfer of resource {}, to {}, finished!, {}", this.transferHandler.getResource(), this.transferHandler.getTunnel().getDestination(), this.reason); + logger.info("Transfer of resource {}, to {}, finished!", this.getTransferHandler().getResource(), this.getTransferHandler().getTunnel().getDestination()); } } - - public void setReason(String reason) { - this.reason = reason; - } - - public String getReason() { - return reason; - } } diff --git a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferStartedEvent.java b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferStartedEvent.java index ab81258f..77817b27 100644 --- a/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferStartedEvent.java +++ b/shared/src/main/java/me/matoosh/undernet/event/resource/transfer/ResourceTransferStartedEvent.java @@ -13,10 +13,10 @@ public ResourceTransferStartedEvent(ResourceTransferHandler transferHandler) { @Override public void onCalled() { - if(this.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { - logger.info("Transfer of resource {}, from {}, started!", this.transferHandler.getResource(), this.transferHandler.getTunnel().getDestination()); + if(this.getTransferHandler().getTransferType() == ResourceTransferType.INBOUND) { + logger.info("Transfer of resource {}, from {}, started!", this.getTransferHandler().getResource(), this.getTransferHandler().getTunnel().getDestination()); } else { - logger.info("Transfer of resource {}, to {}, started!", this.transferHandler.getResource(), this.transferHandler.getTunnel().getDestination()); + logger.info("Transfer of resource {}, to {}, started!", this.getTransferHandler().getResource(), this.getTransferHandler().getTunnel().getDestination()); } } } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/node/Node.java b/shared/src/main/java/me/matoosh/undernet/p2p/node/Node.java index d5398590..c98fe1cc 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/node/Node.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/node/Node.java @@ -95,7 +95,11 @@ public boolean isConnected() { * @param msg */ public void sendRaw(NetworkMessage msg) { - logger.info("Sending a {} message to: {}", msg.getContent().getType(), address); + if(msg.getContent() != null) + logger.info("Sending a {} message to: {}", msg.getContent().getType(), address); + else + logger.info("Sending a message to: {}", address); + if(channel == null) { logger.error("Node {} is not a neighboring node, can't send the message!", this); } else { diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java index eb20e6df..180119eb 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/NetworkMessageManager.java @@ -42,13 +42,14 @@ public void setup() { * Constructs a message and starts the sending process to the other node. * If a tunnel is not yet established with the other node, it will be established now. * If a tunnel is already active with the other node, the message will be sent through it. + * * @param content * @param recipient */ public void sendMessage(MsgBase content, NetworkID recipient) { //Getting the appropriate message tunnel. MessageTunnel messageTunnel = router.messageTunnelManager.getTunnel(Node.self.getIdentity().getNetworkId(), recipient); - if(messageTunnel == null) { + if (messageTunnel == null) { //Creating a tunnel if doesn't exist already. messageTunnel = router.messageTunnelManager.createTunnel(Node.self.getIdentity().getNetworkId(), recipient, MessageTunnelSide.ORIGIN); } @@ -58,6 +59,7 @@ public void sendMessage(MsgBase content, NetworkID recipient) { /** * Constructs a message and starts the sending process to the other node. * Uses the specified message tunnel. + * * @param content * @param messageTunnel */ @@ -66,7 +68,7 @@ public void sendMessage(MsgBase content, MessageTunnel messageTunnel) { NetworkMessage message = constructMessage(messageTunnel, content, NetworkMessage.MessageDirection.TO_DESTINATION); //Checking if the tunnel has been created. - switch(messageTunnel.getTunnelState()) { + switch (messageTunnel.getTunnelState()) { case ESTABLISHED: //Using an existing tunnel. messageTunnel.encryptMsgSymmetric(message); @@ -78,7 +80,7 @@ public void sendMessage(MsgBase content, MessageTunnel messageTunnel) { default: //Adding message to the queue. messageTunnel.messageQueue.add(message); - if(messageTunnel.messageQueue.size() == 1) { + if (messageTunnel.messageQueue.size() == 1) { //Establishing the tunnel. router.messageTunnelManager.establishTunnel(messageTunnel); } @@ -90,16 +92,17 @@ public void sendMessage(MsgBase content, MessageTunnel messageTunnel) { * Constructs a response message and starts the sending process to the origin node. * The response can only be sent as a response to the previously received message. * A message tunnel is needed for the message to be delivered. + * * @param content */ public void sendResponse(MsgBase content, MessageTunnel tunnel) { - if(tunnel == null) { + if (tunnel == null) { logger.warn("Can't send a response, the tunnel is null!"); return; } //Checking if the tunnel has been created. - switch(tunnel.getTunnelState()) { + switch (tunnel.getTunnelState()) { case ESTABLISHED: //Using an existing tunnel. NetworkMessage message = constructMessage(tunnel, content, NetworkMessage.MessageDirection.TO_ORIGIN); @@ -117,9 +120,10 @@ public void sendResponse(MsgBase content, MessageTunnel tunnel) { /** * Constructs a new network message. + * * @param direction the direction in which the message should be routed. - * @param content the content of the network message. - * @param tunnel the message tunnel of the message. Has the origin and destination parameters. + * @param content the content of the network message. + * @param tunnel the message tunnel of the message. Has the origin and destination parameters. */ public NetworkMessage constructMessage(MessageTunnel tunnel, MsgBase content, NetworkMessage.MessageDirection direction) { NetworkMessage message; @@ -132,36 +136,32 @@ public NetworkMessage constructMessage(MessageTunnel tunnel, MsgBase content, Ne } - /** * Forwards a message to the next closest node. + * * @param message the message to be forwarded. */ public void forwardMessage(NetworkMessage message, Node forwarder) { //Ignore node info. - if(message.getContent() != null && message.getContent().getType() == MsgType.NODE_INFO) { + if (message.getContent() != null && message.getContent().getType() == MsgType.NODE_INFO) { return; } - if(!message.isValid()) { + if (!message.isValid()) { logger.warn("Message: {} is invalid, the message won't be forwarded!", message); return; } //Getting the next node in the tunnel. MessageTunnel tunnel = router.messageTunnelManager.getTunnel(message.getOrigin(), message.getDestination()); - if(tunnel == null) { - if(message.getContent() != null) - logger.info("Tunnel for message: {} not found, creating one... {}", message, message.getContent().getType()); - else - logger.info("Tunnel for message: {} not found, creating one...", message); - + if (tunnel == null) { + logger.info("Tunnel for message: {} not found, creating one...", message); tunnel = router.messageTunnelManager.createTunnel(message.getOrigin(), message.getDestination(), MessageTunnelSide.UNDEFINED); } //Getting the next node. Node nextNode; - if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { + if (message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { //Getting the closest neighbor to forward the message to. tunnel.setPreviousNode(forwarder); tunnel.setNextNode(router.neighborNodesManager.getClosestTo(message.getDestination())); @@ -169,19 +169,19 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { } else { nextNode = tunnel.getPreviousNode(); } - if(nextNode == null) { + if (nextNode == null) { logger.warn("Couldn't forward message: {}, next node unknown!", message); return; } - if(forwarder == Node.self) { - if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { + if (forwarder == Node.self) { + if (message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { logger.debug("Forwarding message, ({}) -> ({}) -> (...) -> ({})", Node.self, tunnel.getNextNode(), message.getDestination()); } else { logger.debug("Forwarding message, ({}) <- (...) <- ({}) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self); } } else { - if(message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { + if (message.getDirection() == NetworkMessage.MessageDirection.TO_DESTINATION) { logger.debug("Forwarding message, ({}) -> (...) -> ({}) -> ({}) -> ({}) -> (...) -> ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, tunnel.getNextNode(), message.getDestination()); } else { logger.debug("Forwarding message, ({}) <- (...) <- ({}) <- ({}) <- ({}) <- (...) <- ({})", message.getOrigin(), tunnel.getPreviousNode(), Node.self, forwarder, message.getDestination()); @@ -190,12 +190,12 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { } //Checking if we are the last stop. - if(nextNode == Node.self) { + if (nextNode == Node.self) { //Decrypting the message. //Checking if the message can be read by our node. //If can be read, call message received event. //If can't be read, ignore. - if(decryptMessage(message, tunnel)) { + if (decryptMessage(message, tunnel)) { //Message can be read. message.deserialize(); @@ -216,11 +216,12 @@ public void forwardMessage(NetworkMessage message, Node forwarder) { /** * Decrypts the received message. + * * @param message */ private boolean decryptMessage(NetworkMessage message, MessageTunnel messageTunnel) { //Checking whether the message was encrypted at all. - if(message.verify()) { + if (message.verify()) { logger.info("Message: {}, doesn't need to be decrypted...", message); return true; } @@ -244,16 +245,16 @@ protected void registerHandlers() { @Override public void onEventCalled(Event e) { - if(e instanceof ChannelMessageReceivedEvent) { //A network message was received. - ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent)e; + if (e instanceof ChannelMessageReceivedEvent) { //A network message was received. + ChannelMessageReceivedEvent messageReceivedEvent = (ChannelMessageReceivedEvent) e; NetworkMessage message = messageReceivedEvent.message; forwardMessage(message, messageReceivedEvent.remoteNode); } else if (e instanceof MessageTunnelEstablishedEvent) { - MessageTunnelEstablishedEvent messageTunnelEstablishedEvent = (MessageTunnelEstablishedEvent)e; + MessageTunnelEstablishedEvent messageTunnelEstablishedEvent = (MessageTunnelEstablishedEvent) e; MessageTunnel tunnel = messageTunnelEstablishedEvent.messageTunnel; - if(messageTunnelEstablishedEvent.establishDirection == NetworkMessage.MessageDirection.TO_DESTINATION) { + if (messageTunnelEstablishedEvent.establishDirection == NetworkMessage.MessageDirection.TO_DESTINATION) { logger.info("Sending {} queued messages through the established tunnel: \n{}", tunnel.messageQueue.size(), tunnel); //Sending messages through the tunnel. diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index ae9ce855..f70fd16e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -12,6 +12,7 @@ import me.matoosh.undernet.p2p.router.data.NetworkID; import me.matoosh.undernet.p2p.router.data.message.MsgType; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; +import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index dd733e0f..471e2c11 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -5,6 +5,7 @@ import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.channel.ConnectionEstablishedEvent; import me.matoosh.undernet.event.channel.message.MessageReceivedEvent; +import me.matoosh.undernet.event.resource.ResourceErrorEvent; import me.matoosh.undernet.event.resource.pull.ResourcePullReceivedEvent; import me.matoosh.undernet.event.resource.pull.ResourcePullSentEvent; import me.matoosh.undernet.event.resource.transfer.*; @@ -331,19 +332,6 @@ else if(messageReceivedEvent.networkMessage.getContent().getType() == MsgType.RE startPush(flag); } } - } else if(e instanceof ResourceTransferFinishedEvent) { - ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent)e; - - //Closing the streams. - transferFinishedEvent.transferHandler.close(); - router.messageTunnelManager.closeTunnel(transferFinishedEvent.transferHandler.getTunnel()); - - //Removing from the list. - if(transferFinishedEvent.transferHandler.getTransferType() == ResourceTransferType.INBOUND) { - inboundHandlers.remove(transferFinishedEvent.transferHandler); - } else { - outboundHandlers.remove(transferFinishedEvent.transferHandler); - } } } @@ -368,6 +356,5 @@ protected void registerEvents() { protected void registerHandlers() { EventManager.registerHandler(this, MessageReceivedEvent.class); EventManager.registerHandler(this, ConnectionEstablishedEvent.class); - EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); } } \ No newline at end of file diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index ddd90d9d..38ea2d90 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -82,8 +82,8 @@ public void prepare() { getResource().calcNetworkId(); if(getResource().getNetworkID().equals(getTunnel().getDestination())) { //The file is already stored locally. - EventManager.callEvent(new ResourceTransferFinishedEvent(this, "File exists already!")); getTunnel().sendMessage(new ResourceDataChunkRequest(this.getTransferId(), -2)); + return; } } @@ -110,7 +110,7 @@ public void prepare() { * Closes the file streams. */ @Override - public void close() { + public void onClose() { logger.info("Closing {} streams for file {}", this.getTransferType(), ((FileResource)this.getResource()).file); try { if (inputStream != null) { @@ -134,14 +134,9 @@ public void sendChunk(int chunkId) { if(getTransferType().equals(ResourceTransferType.OUTBOUND) && inputStream != null) { //Stopping on request. if(chunkId < 0) { - if(chunkId == -1) { - //File sent or error. - EventManager.callEvent(new ResourceTransferFinishedEvent(FileTransferHandler.this, "File transfer complete!")); - return; - } if(chunkId == -2) { //File sent or error. - EventManager.callEvent(new ResourceTransferFinishedEvent(FileTransferHandler.this, "File transfer interrupted by destination!")); + this.close(); return; } } @@ -164,19 +159,23 @@ public void sendChunk(int chunkId) { //Finish if no more bytes available! if(inputStream.available() <= 0) { //File sent fully. - EventManager.callEvent(new ResourceTransferFinishedEvent(FileTransferHandler.this, "File transfer complete!")); - return; + this.close(); } } else { //The file has no data. Sending an empty chunk. sendData(new byte[0], chunkId); } } catch (IOException e) { - EventManager.callEvent(new ResourceTransferErrorEvent(FileTransferHandler.this, e)); + callError(e); } } } + /** + * Sends file chunk. + * @param data + * @param chunkId + */ private void sendData(byte[] data, int chunkId) { ResourceDataMessage message = new ResourceDataMessage(data, getTransferId(), chunkId); getTunnel().sendMessage(message); @@ -204,32 +203,31 @@ public void onDataReceived(ResourceDataMessage dataMessage) { logger.info("File chunk received for: {} | {}%", this.getResource().getNetworkID(), ((float)written/(float)fileLength)*100f); if(written >= fileLength) { //File fully received. - getTunnel().sendMessage(new ResourceDataChunkRequest(this.getTransferId(), -1)); - EventManager.callEvent(new ResourceTransferFinishedEvent(this, "File transfer complete!")); + this.close(); } else { getTunnel().sendMessage(new ResourceDataChunkRequest(this.getTransferId(), dataMessage.getChunkId() + 1)); } } catch (IOException e) { - //Error - EventManager.callEvent(new ResourceTransferErrorEvent(this, e)); - - //Closing the input stream. - try { - this.outputStream.close(); - } catch (IOException f) { - f.printStackTrace(); - } + callError(e); } } else { //Empty chunk, ending the transfer and closing the file. logger.info("Empty chunk received for: {}, ending the transfer..."); //File fully received. - EventManager.callEvent(new ResourceTransferFinishedEvent(this, "Empty file transfer!")); + this.close(); } } } + @Override + public void onError(Exception e) { + //Removing file. + if(((FileResource)this.getResource()).file != null) { + ((FileResource)this.getResource()).file.delete(); + } + } + public long getFileLength() { return fileLength; } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index 4d9cfbfd..07b31854 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -1,5 +1,9 @@ package me.matoosh.undernet.p2p.router.data.resource.transfer; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.resource.ResourceErrorEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferErrorEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; import me.matoosh.undernet.p2p.router.Router; import me.matoosh.undernet.p2p.router.data.message.ResourceDataMessage; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; @@ -52,6 +56,7 @@ public ResourceTransferHandler(Resource resource, ResourceTransferType transferT /** * Sends chunk with id chunk id. + * * @param chunkId */ public abstract void sendChunk(int chunkId); @@ -59,14 +64,53 @@ public ResourceTransferHandler(Resource resource, ResourceTransferType transferT /** * Releases all the resources associated with the handler. */ - public abstract void close(); + public void close() { + //Handling close. + onClose(); + + //Closing tunnel. + router.messageTunnelManager.closeTunnel(this.getTunnel()); + + //Removing from the list. + if (this.getTransferType() == ResourceTransferType.INBOUND) { + router.resourceManager.inboundHandlers.remove(this); + } else { + router.resourceManager.outboundHandlers.remove(this); + } + + EventManager.callEvent(new ResourceTransferFinishedEvent(this )); + } + + /** + * Called when the transfer handler is closed. + */ + public abstract void onClose(); /** * Called when a resource data message is sent. + * * @param dataMessage */ public abstract void onDataReceived(ResourceDataMessage dataMessage); + /** + * Calls error for the handler. + */ + public void callError(Exception e) { + //Handling error. + onError(e); + + EventManager.callEvent(new ResourceTransferErrorEvent(this , e)); + + //Closing the streams. + this.close(); + } + + /** + * Called when a resource transfer error occurs. + */ + public abstract void onError(Exception e); + public Router getRouter() { return router; } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index 0003965a..b8961131 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -121,7 +121,7 @@ public void onEventCalled(Event e) { } } else if (e instanceof ResourceTransferDataReceivedEvent) { ResourceTransferDataReceivedEvent dataReceivedEvent = (ResourceTransferDataReceivedEvent) e; - ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; + ResourceTransferHandler transferHandler = dataReceivedEvent.getTransferHandler(); if (transferHandler instanceof FileTransferHandler) { FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; @@ -130,7 +130,7 @@ public void onEventCalled(Event e) { } } else if (e instanceof ResourceTransferDataSentEvent) { ResourceTransferDataSentEvent dataReceivedEvent = (ResourceTransferDataSentEvent) e; - ResourceTransferHandler transferHandler = dataReceivedEvent.transferHandler; + ResourceTransferHandler transferHandler = dataReceivedEvent.getTransferHandler(); if (transferHandler instanceof FileTransferHandler) { FileTransferHandler fileTransferHandler = (FileTransferHandler) transferHandler; @@ -139,7 +139,7 @@ public void onEventCalled(Event e) { } } else if (e instanceof ResourceTransferFinishedEvent) { ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; - ResourceTransferHandler transferHandler = transferFinishedEvent.transferHandler; + ResourceTransferHandler transferHandler = transferFinishedEvent.getTransferHandler(); if (transferHandler instanceof FileTransferHandler) { progressBar.setValue(0); diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java index a11770b1..23d562ec 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java @@ -69,7 +69,7 @@ public void actionPerformed(ActionEvent actionEvent) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Choose the save directory"); int result = fileChooser.showOpenDialog(ResourcePullDialog.this); - if(result == JFileChooser.APPROVE_OPTION) { + if (result == JFileChooser.APPROVE_OPTION) { saveFile[0] = fileChooser.getSelectedFile(); } } @@ -83,8 +83,8 @@ public void actionPerformed(ActionEvent actionEvent) { pullButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { - final NetworkID netId = new NetworkID(networkIdField.getText().replaceAll("\\s+","")); - if(netId.isValid()) { + final NetworkID netId = new NetworkID(networkIdField.getText().replaceAll("\\s+", "")); + if (netId.isValid()) { //Starting the pull. UnderNet.router.resourceManager.pull(netId); //Use inputted network id. @@ -94,22 +94,22 @@ public void actionPerformed(ActionEvent actionEvent) { public void onEventCalled(Event e) { ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; - if(transferFinishedEvent.transferHandler.getTransferType() == ResourceTransferType.INBOUND && transferFinishedEvent.transferHandler.getResource().getNetworkID().equals(netId) && transferFinishedEvent.transferHandler.getResource().getInfo().resourceType == ResourceType.FILE) { - FileResource fileResource = (FileResource)transferFinishedEvent.transferHandler.getResource(); + if (transferFinishedEvent.getTransferHandler().getTransferType() == ResourceTransferType.INBOUND && transferFinishedEvent.getTransferHandler().getResource().getNetworkID().equals(netId) && transferFinishedEvent.getTransferHandler().getResource().getInfo().resourceType == ResourceType.FILE) { + FileResource fileResource = (FileResource) transferFinishedEvent.getTransferHandler().getResource(); //Copying the received file to dest. - if(saveFile[0] != null) { + if (saveFile[0] != null) { try { Files.copy(Paths.get(fileResource.file.getAbsolutePath()), Paths.get(saveFile[0].getAbsolutePath() + "/" + fileResource.file.getName()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e1) { e1.printStackTrace(); } finally { //File dialog. - EventQueue.invokeLater(()->JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveFile[0]),"File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); + EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveFile[0]), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); } } else { //File dialog. - EventQueue.invokeLater(()->JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); + EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); } } @@ -132,6 +132,6 @@ public void onEventCalled(Event e) { */ private void centerDialogOnMouse() { Point mousePoint = MouseInfo.getPointerInfo().getLocation(); - setLocation(mousePoint.x - getSize().width/2, mousePoint.y - getSize().height/2); + setLocation(mousePoint.x - getSize().width / 2, mousePoint.y - getSize().height / 2); } } From 70afc0fee76d69365ad78ce96b131c56dc22d393 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 15:35:17 +0100 Subject: [PATCH 43/60] Update ResourceManager.java --- .../undernet/p2p/router/data/resource/ResourceManager.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 471e2c11..f73995a4 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -275,9 +275,11 @@ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { * @param message */ private void handleResourceRetrieve(ResourceDataMessage message) { + logger.info("Handling resource data retrieve, transId: {}", message.getTransferId()); //Checking if the resource push is already being received. for (ResourceTransferHandler transferHandler : inboundHandlers) { + System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && message.getTransferId() == transferHandler.getTransferId()) { transferHandler.onDataReceived(message); } From 7775b3106036825b2742d670c2e77ca81fcd62c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 15:47:51 +0100 Subject: [PATCH 44/60] Transfer id generation --- .../undernet/p2p/router/data/resource/FileResource.java | 3 +-- .../router/data/resource/transfer/ResourceTransferHandler.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java index 06b0e724..7b54b940 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/FileResource.java @@ -135,8 +135,7 @@ void updateAttributes() { @Override public ResourceTransferHandler getTransferHandler(ResourceTransferType resourceTransferType, MessageTunnel tunnel, int transferId, Router router) { if (resourceTransferType == ResourceTransferType.OUTBOUND) { - router.resourceManager.lastTransferId++; - transferId = router.resourceManager.lastTransferId; + transferId = UnderNet.secureRandom.nextInt(); } return new FileTransferHandler(this, resourceTransferType, tunnel, transferId, router); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index 07b31854..f48589c5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -41,7 +41,7 @@ public abstract class ResourceTransferHandler { public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, int transferId, Router router) { - System.out.println("Creeating resource transfer handler: " + transferId); + System.out.println("Creating resource transfer handler: " + transferId); this.resource = resource; this.transferType = transferType; this.tunnel = tunnel; From a65e7e01ed0d5c37707046a2bcc48a8bcd60ef6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 16:24:42 +0100 Subject: [PATCH 45/60] Stability improvements --- .../p2p/router/data/resource/ResourceManager.java | 2 -- .../data/resource/transfer/FileTransferHandler.java | 8 ++++---- .../data/resource/transfer/ResourceTransferHandler.java | 6 ++++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index f73995a4..32d89e38 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -184,7 +184,6 @@ private void startPush(Resource resource, MessageTunnel tunnel) { //Getting the transfer handler. ResourceTransferHandler transferHandler = resource.getTransferHandler(ResourceTransferType.OUTBOUND, tunnel, -1, this.router); logger.info("Outbound {} resource transfer, transfer id: {}", resource.getResourceType(), transferHandler.getTransferId()); - outboundHandlers.add(transferHandler); //Sending the resource info message. transferHandler.prepare(); @@ -227,7 +226,6 @@ private void handleResourceInfo(ResourceInfoMessage message) { //Getting a new resource handler. ResourceTransferHandler transferHandler = resource.getTransferHandler(ResourceTransferType.INBOUND, message.getNetworkMessage().getTunnel(), message.getTransferId(), this.router); logger.info("Inbound {} resource transfer, transfer id: {}", message.getResourceInfo().resourceType, transferHandler.getTransferId()); - inboundHandlers.add(transferHandler); //Preparing for incoming resource. transferHandler.prepare(); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index 38ea2d90..53d7b7b4 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -73,7 +73,7 @@ public void prepare() { inputStream = new FileInputStream(saveFile); } catch (FileNotFoundException e) { //File doesn't exist. //Calling a transfer error. - EventManager.callEvent(new ResourceTransferErrorEvent(this, e)); + callError(e); return; } } else { //Receiving @@ -83,7 +83,7 @@ public void prepare() { if(getResource().getNetworkID().equals(getTunnel().getDestination())) { //The file is already stored locally. getTunnel().sendMessage(new ResourceDataChunkRequest(this.getTransferId(), -2)); - + this.close(); return; } } @@ -97,8 +97,8 @@ public void prepare() { outputStream = new FileOutputStream(saveFile); } catch (IOException e) { //Calling a transfer error. - EventManager.callEvent(new ResourceTransferErrorEvent(this, e)); - return; + callError(e); + return; } //Requesting the first chunk. diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index f48589c5..bf814331 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -47,6 +47,12 @@ public ResourceTransferHandler(Resource resource, ResourceTransferType transferT this.tunnel = tunnel; this.router = router; this.transferId = transferId; + + if(transferType == ResourceTransferType.OUTBOUND) { + router.resourceManager.outboundHandlers.add(this); + } else { + router.resourceManager.inboundHandlers.add(this); + } } /** From efecccedd151fb9a9e1a1d0070c3238d7df4f0ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 17:33:15 +0100 Subject: [PATCH 46/60] New active transfers panel --- .../transfer/ResourceTransferHandler.java | 9 +- .../undernet/standalone/uix/MainFrame.form | 27 +++-- .../undernet/standalone/uix/MainFrame.java | 10 +- .../standalone/uix/TransferPanel.form | 34 ++++++ .../standalone/uix/TransferPanel.java | 101 ++++++++++++++++++ .../undernet/standalone/uix/TunnelPanel.form | 12 ++- .../undernet/standalone/uix/TunnelPanel.java | 36 ++++++- .../src/main/resources/language.properties | 1 + 8 files changed, 216 insertions(+), 14 deletions(-) create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.java diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index bf814331..2512f6a5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -4,6 +4,7 @@ import me.matoosh.undernet.event.resource.ResourceErrorEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferErrorEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; import me.matoosh.undernet.p2p.router.Router; import me.matoosh.undernet.p2p.router.data.message.ResourceDataMessage; import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnel; @@ -41,7 +42,6 @@ public abstract class ResourceTransferHandler { public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, int transferId, Router router) { - System.out.println("Creating resource transfer handler: " + transferId); this.resource = resource; this.transferType = transferType; this.tunnel = tunnel; @@ -53,6 +53,8 @@ public ResourceTransferHandler(Resource resource, ResourceTransferType transferT } else { router.resourceManager.inboundHandlers.add(this); } + + EventManager.callEvent(new ResourceTransferStartedEvent(this)); } /** @@ -140,4 +142,9 @@ public void setTunnel(MessageTunnel tunnel) { public int getTransferId() { return transferId; } + + @Override + public String toString() { + return transferType + " transfer (" + transferId + ") -> " + getResource().getNetworkID().getStringValue(); + } } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form index 91aca55c..f3a7935c 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.form @@ -3,7 +3,7 @@ - + @@ -27,11 +27,6 @@ - - - - - @@ -68,6 +63,26 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index b8961131..dbf0a54e 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -46,6 +46,7 @@ public class MainFrame extends EventHandler { private JProgressBar progressBar; private JButton mainButton; private VisualPanel visualPanel; + private TransferPanel transferPanel; private ControlIcon controlIcon1; public static final int START_HEIGHT = 600; @@ -195,8 +196,6 @@ private void createUIComponents() { panel.add(resourcePanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(200, -1), null, null, 0, false)); nodePanel = new NodePanel(); panel.add(nodePanel.$$$getRootComponent$$$(), new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(300, -1), null, null, 0, false)); - tunnelPanel = new TunnelPanel(); - panel.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel.add(mainButton, new GridConstraints(4, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 50), null, 0, false)); final Spacer spacer2 = new Spacer(); panel.add(spacer2, new GridConstraints(3, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); @@ -208,6 +207,13 @@ private void createUIComponents() { panel.add(spacer4, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); visualPanel = new VisualPanel(); panel.add(visualPanel.$$$getRootComponent$$$(), new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(350, -1), null, 0, false)); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 5, 0, 5), -1, -1)); + panel.add(panel1, new GridConstraints(2, 0, 1, 5, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + transferPanel = new TransferPanel(); + panel1.add(transferPanel.$$$getRootComponent$$$(), new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + tunnelPanel = new TunnelPanel(); + panel1.add(tunnelPanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); } /** diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.form new file mode 100644 index 00000000..7c3c10d7 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.form @@ -0,0 +1,34 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.java new file mode 100644 index 00000000..6d0188fe --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TransferPanel.java @@ -0,0 +1,101 @@ +package me.matoosh.undernet.standalone.uix; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; +import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; + +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.ResourceBundle; + +public class TransferPanel extends EventHandler { + private JPanel panel; + private JList transferList; + + private void createUIComponents() { + transferList = new JList<>(new ResourceTransferHandler[0]); + } + + public TransferPanel() { + $$$setupUI$$$(); + registerListeners(); + } + + private void registerListeners() { + EventManager.registerHandler(this, ResourceTransferStartedEvent.class); + EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); + } + + @Override + public void onEventCalled(Event e) { + refreshList(); + } + + private void refreshList() { + ArrayList handlers = new ArrayList<>(); + handlers.addAll(UnderNet.router.resourceManager.inboundHandlers); + handlers.addAll(UnderNet.router.resourceManager.outboundHandlers); + + this.transferList.setListData(handlers.toArray()); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + createUIComponents(); + panel = new JPanel(); + panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + final JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("title_transfers")); + panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JScrollPane scrollPane1 = new JScrollPane(); + panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + scrollPane1.setViewportView(transferList); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return panel; + } +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form index 2188b640..45711f06 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.form @@ -1,6 +1,6 @@
- + @@ -13,7 +13,7 @@ - + @@ -24,6 +24,14 @@ + + + + + + + + diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java index 131dac7d..5e4b1dbe 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/TunnelPanel.java @@ -16,6 +16,7 @@ import javax.swing.*; import java.awt.*; +import java.util.ResourceBundle; /** * Represents a message tunnel panel. @@ -68,12 +69,42 @@ private void refreshTunnelList() { private void $$$setupUI$$$() { createUIComponents(); panel = new JPanel(); - panel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); + panel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); panel.setEnabled(true); panel.setForeground(new Color(-1)); final JScrollPane scrollPane1 = new JScrollPane(); - panel.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + panel.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); scrollPane1.setViewportView(tunnelList); + final JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("title_tunnels")); + panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } } /** @@ -82,7 +113,6 @@ private void refreshTunnelList() { public JComponent $$$getRootComponent$$$() { return panel; } - } /** * Renders elements within the nodes list. diff --git a/standalone/src/main/resources/language.properties b/standalone/src/main/resources/language.properties index 02b1dc25..b1827bd9 100644 --- a/standalone/src/main/resources/language.properties +++ b/standalone/src/main/resources/language.properties @@ -7,4 +7,5 @@ button_pullResource=Pull button_removeNode=Remove Node title_nodes=Nodes title_resources=Resources +title_transfers=Active Transfers title_tunnels=Active Tunnels \ No newline at end of file From 05d7f5d933834fb5528bcfbf66261afac32b95ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 17:51:01 +0100 Subject: [PATCH 47/60] Autoclosing of resource transfers --- .../matoosh/undernet/p2p/router/Router.java | 26 ++++++++------ .../router/data/resource/ResourceManager.java | 4 +-- .../transfer/ResourceTransferHandler.java | 35 +++++++++++++++++-- 3 files changed, 51 insertions(+), 14 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index 9ae5f0de..bd1e5611 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -28,6 +28,7 @@ import me.matoosh.undernet.p2p.router.data.message.tunnel.MessageTunnelSide; import me.matoosh.undernet.p2p.router.data.message.tunnel.TunnelControlMessage; import me.matoosh.undernet.p2p.router.data.resource.ResourceManager; +import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; import me.matoosh.undernet.p2p.router.server.Server; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; @@ -35,10 +36,7 @@ import java.security.Security; import java.util.ArrayList; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; /** * The network router. @@ -215,15 +213,23 @@ private void controlLoop() { this.networkMessageManager.sendMessage(new NodeNeighborsRequest(), neighbor.getIdentity().getNetworkId()); } - //Sending control message to tunnels. + //Checking resource transfer activity. + for (int i = 0; i < resourceManager.inboundHandlers.size(); i++) { + ResourceTransferHandler transferHandler = resourceManager.inboundHandlers.get(i); + if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + 2 * controlLoopInterval * 1000) + transferHandler.callError(new TimeoutException()); + } + for (int i = 0; i < resourceManager.outboundHandlers.size(); i++) { + ResourceTransferHandler transferHandler = resourceManager.outboundHandlers.get(i); + if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + 2 * controlLoopInterval * 1000) + transferHandler.callError(new TimeoutException()); + } + + //Checking tunnel activity. for (int i = 0; i < messageTunnelManager.messageTunnels.size(); i++) { MessageTunnel tunnel = messageTunnelManager.messageTunnels.get(i); - if (tunnel.getSide() == MessageTunnelSide.ORIGIN && tunnel.getNextNode() == Node.self) - messageTunnelManager.closeTunnel(tunnel); - else if (tunnel.getSide() == MessageTunnelSide.DESTINATION && tunnel.getPreviousNode() == Node.self) - messageTunnelManager.closeTunnel(tunnel); - else if (System.currentTimeMillis() > tunnel.getLastMessageTime() + 2 * controlLoopInterval * 1000) + if (System.currentTimeMillis() > tunnel.getLastMessageTime() + 2 * controlLoopInterval * 1000) messageTunnelManager.closeTunnel(tunnel); else if (tunnel.isKeepAlive()) tunnel.sendMessage(new TunnelControlMessage()); } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 32d89e38..c0c9ac88 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -262,7 +262,7 @@ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && transferHandler.getTransferId() == message.getTransferId()) { logger.info("Sending chunk: {}, of file transfer {}", message.getChunkId(), transferHandler.getResource().getNetworkID()); - transferHandler.sendChunk(message.getChunkId()); + transferHandler.callSendChunk(message.getChunkId()); } return; } @@ -279,7 +279,7 @@ private void handleResourceRetrieve(ResourceDataMessage message) { inboundHandlers) { System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && message.getTransferId() == transferHandler.getTransferId()) { - transferHandler.onDataReceived(message); + transferHandler.callDataReceived(message); } return; } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java index 2512f6a5..771a2a02 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/ResourceTransferHandler.java @@ -1,7 +1,6 @@ package me.matoosh.undernet.p2p.router.data.resource.transfer; import me.matoosh.undernet.event.EventManager; -import me.matoosh.undernet.event.resource.ResourceErrorEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferErrorEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; @@ -40,6 +39,11 @@ public abstract class ResourceTransferHandler { */ private int transferId; + /** + * Time of the last message. + */ + private long lastMessageTime; + public ResourceTransferHandler(Resource resource, ResourceTransferType transferType, MessageTunnel tunnel, int transferId, Router router) { this.resource = resource; @@ -62,6 +66,16 @@ public ResourceTransferHandler(Resource resource, ResourceTransferType transferT */ public abstract void prepare(); + /** + * Sends chunk with id chunk id. + * + * @param chunkId + */ + public void callSendChunk(int chunkId) { + lastMessageTime = System.currentTimeMillis(); + sendChunk(chunkId); + } + /** * Sends chunk with id chunk id. * @@ -95,7 +109,16 @@ public void close() { public abstract void onClose(); /** - * Called when a resource data message is sent. + * Called when a resource data message is received. + * @param dataMessage + */ + public void callDataReceived(ResourceDataMessage dataMessage) { + lastMessageTime = System.currentTimeMillis(); + onDataReceived(dataMessage); + } + + /** + * Called when a resource data message is received. * * @param dataMessage */ @@ -143,6 +166,14 @@ public int getTransferId() { return transferId; } + public long getLastMessageTime() { + return lastMessageTime; + } + + public void setLastMessageTime(long lastMessageTime) { + this.lastMessageTime = lastMessageTime; + } + @Override public String toString() { return transferType + " transfer (" + transferId + ") -> " + getResource().getNetworkID().getStringValue(); From 3c393166d4652a9fe01a5668c7c9730e845709c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:11:37 +0100 Subject: [PATCH 48/60] a --- .../java/me/matoosh/undernet/p2p/router/Router.java | 12 ++++++++++-- .../p2p/router/data/resource/ResourceManager.java | 6 ++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java index bd1e5611..a1136d94 100755 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/Router.java @@ -216,12 +216,12 @@ private void controlLoop() { //Checking resource transfer activity. for (int i = 0; i < resourceManager.inboundHandlers.size(); i++) { ResourceTransferHandler transferHandler = resourceManager.inboundHandlers.get(i); - if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + 2 * controlLoopInterval * 1000) + if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + controlLoopInterval * 1000) transferHandler.callError(new TimeoutException()); } for (int i = 0; i < resourceManager.outboundHandlers.size(); i++) { ResourceTransferHandler transferHandler = resourceManager.outboundHandlers.get(i); - if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + 2 * controlLoopInterval * 1000) + if (System.currentTimeMillis() > transferHandler.getLastMessageTime() + controlLoopInterval * 1000) transferHandler.callError(new TimeoutException()); } @@ -262,6 +262,14 @@ public void stop() { server.stop(); } + //Closes all remaining transfers. + for (int i = 0; i < resourceManager.inboundHandlers.size(); i++) { + resourceManager.inboundHandlers.get(i).close(); + } + for (int i = 0; i < resourceManager.outboundHandlers.size(); i++) { + resourceManager.outboundHandlers.get(i).close(); + } + //Closes all remaining tunnels. for (int i = 0; i < messageTunnelManager.messageTunnels.size(); i++) { messageTunnelManager.closeTunnel(messageTunnelManager.messageTunnels.get(i)); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index c0c9ac88..30483ee5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -259,8 +259,7 @@ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { //Sending next chunk from handler. for (ResourceTransferHandler transferHandler : outboundHandlers) { - System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); - if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && transferHandler.getTransferId() == message.getTransferId()) { + if(transferHandler.getTransferId() == message.getTransferId()) { logger.info("Sending chunk: {}, of file transfer {}", message.getChunkId(), transferHandler.getResource().getNetworkID()); transferHandler.callSendChunk(message.getChunkId()); } @@ -277,8 +276,7 @@ private void handleResourceRetrieve(ResourceDataMessage message) { //Checking if the resource push is already being received. for (ResourceTransferHandler transferHandler : inboundHandlers) { - System.out.println("TRANS: " + transferHandler.getTransferId() + ", " + transferHandler.getTunnel()); - if(transferHandler.getTunnel() == message.getNetworkMessage().getTunnel() && message.getTransferId() == transferHandler.getTransferId()) { + if(message.getTransferId() == transferHandler.getTransferId()) { transferHandler.callDataReceived(message); } return; From f8d353b4a92ac8cd07472bd2439376bb3068d1c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:14:34 +0100 Subject: [PATCH 49/60] Removing files on transfer error --- .../data/resource/transfer/FileTransferHandler.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index 53d7b7b4..05c2be80 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -14,6 +14,7 @@ import org.slf4j.LoggerFactory; import java.io.*; +import java.nio.file.Files; /** * Handles file transfers. @@ -223,8 +224,11 @@ public void onDataReceived(ResourceDataMessage dataMessage) { @Override public void onError(Exception e) { //Removing file. - if(((FileResource)this.getResource()).file != null) { - ((FileResource)this.getResource()).file.delete(); + File f = ((FileResource)this.getResource()).file; + if(f != null && f.exists()) { + try { + Files.delete(f.toPath()); + } catch (IOException e1) {} } } From d29d187dc4d1ce3d35fbfe552a26fd4535f8975e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:15:53 +0100 Subject: [PATCH 50/60] Update MessageTunnelManager.java --- .../p2p/router/data/message/tunnel/MessageTunnelManager.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index f70fd16e..08046a65 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -12,7 +12,6 @@ import me.matoosh.undernet.p2p.router.data.NetworkID; import me.matoosh.undernet.p2p.router.data.message.MsgType; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; -import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -129,7 +128,7 @@ public MessageTunnel getTunnel(NetworkID origin, NetworkID destination) { //Finding an existing tunnel. for (int i = 0; i < messageTunnels.size(); i++) { MessageTunnel tunnel = messageTunnels.get(i); - if (tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { + if (tunnel != null && tunnel.getOrigin().equals(origin) && tunnel.getDestination().equals(destination)) { return tunnel; } } From 1d10794fbb8f6daea9623f852f2bc2179a281d9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:18:07 +0100 Subject: [PATCH 51/60] Update FileTransferHandler.java --- .../data/resource/transfer/FileTransferHandler.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java index 05c2be80..8f3d3bcb 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/transfer/FileTransferHandler.java @@ -224,11 +224,14 @@ public void onDataReceived(ResourceDataMessage dataMessage) { @Override public void onError(Exception e) { //Removing file. - File f = ((FileResource)this.getResource()).file; - if(f != null && f.exists()) { - try { - Files.delete(f.toPath()); - } catch (IOException e1) {} + if(getTransferType() == ResourceTransferType.INBOUND) { + File f = ((FileResource) this.getResource()).file; + if (f != null && f.exists()) { + try { + Files.delete(f.toPath()); + } catch (IOException e1) { + } + } } } From ea1260dd3c4ff112b70c27372919ab1cacd9e9c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:26:37 +0100 Subject: [PATCH 52/60] Update ResourcePanel.java --- .../me/matoosh/undernet/standalone/uix/ResourcePanel.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index c99f3be6..84488b45 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -9,6 +9,7 @@ import me.matoosh.undernet.event.resource.transfer.ResourceTransferErrorEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; +import me.matoosh.undernet.event.router.RouterControlLoopEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.InterfaceStatus; @@ -65,6 +66,7 @@ private void registerListeners() { EventManager.registerHandler(this, ResourceTransferStartedEvent.class); EventManager.registerHandler(this, ResourceTransferFinishedEvent.class); EventManager.registerHandler(this, ResourceTransferErrorEvent.class); + EventManager.registerHandler(this, RouterControlLoopEvent.class); } private void refreshList() { @@ -104,6 +106,8 @@ public void onEventCalled(Event e) { } else if (e instanceof ResourceTransferErrorEvent) { publishButton.setEnabled(true); pullButton.setEnabled(true); + } else if (e instanceof RouterControlLoopEvent) { + refreshList(); } } From 41f8f2b4c923d0bc735071f4da263cff5337fb2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:38:23 +0100 Subject: [PATCH 53/60] Update network.yaml --- standalone/src/main/resources/network.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/standalone/src/main/resources/network.yaml b/standalone/src/main/resources/network.yaml index af1414e3..7d18684a 100644 --- a/standalone/src/main/resources/network.yaml +++ b/standalone/src/main/resources/network.yaml @@ -2,6 +2,6 @@ network: listeningPort: 2017 backlogCapacity: 16 ignoreExceptions: false - maxNeighbors: 20 - optNeighbors: 13 + maxNeighbors: 8 + optNeighbors: 5 maxReconnectCount: 5 \ No newline at end of file From 8ce49e5cf85cae75c78381a85aaa91c2508951a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 18:44:04 +0100 Subject: [PATCH 54/60] Update ResourceManager.java --- .../undernet/p2p/router/data/resource/ResourceManager.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 30483ee5..57217030 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -255,16 +255,16 @@ private void handleResourcePullRequest(ResourcePullMessage message) { * @param message */ private void handlerResourceDataRequest(ResourceDataChunkRequest message) { - logger.info("Handling resource data request, transId: {}", message.getTransferId()); //Sending next chunk from handler. for (ResourceTransferHandler transferHandler : outboundHandlers) { if(transferHandler.getTransferId() == message.getTransferId()) { logger.info("Sending chunk: {}, of file transfer {}", message.getChunkId(), transferHandler.getResource().getNetworkID()); transferHandler.callSendChunk(message.getChunkId()); + return; } - return; } + } /** @@ -278,8 +278,8 @@ private void handleResourceRetrieve(ResourceDataMessage message) { inboundHandlers) { if(message.getTransferId() == transferHandler.getTransferId()) { transferHandler.callDataReceived(message); + return; } - return; } } From 6c0c8b67cebdcbbb2ac2dbb826d94951713e05f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 19:10:05 +0100 Subject: [PATCH 55/60] Disconnect duplicate nodes. --- .../p2p/router/client/ClientNetworkMessageHandler.java | 9 +++++++++ .../p2p/router/server/ServerNetworkMessageHandler.java | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java index 54876cf5..6a5082a5 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/client/ClientNetworkMessageHandler.java @@ -50,6 +50,15 @@ public ClientNetworkMessageHandler(Client client) { */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { + //Checking if connected already. + for (Node n : + client.router.getRemoteNodes()) { + if (n.getAddress().equals(ctx.channel().remoteAddress())) { + ctx.disconnect(); + return; + } + } + //Adding the channel to the client list. client.channels.add(ctx.channel()); diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java index c0357e11..d1f7eca1 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/server/ServerNetworkMessageHandler.java @@ -48,6 +48,15 @@ public ServerNetworkMessageHandler(Server server) { */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { + //Checking if connected already. + for (Node n : + server.router.getRemoteNodes()) { + if (n.getAddress().equals(ctx.channel().remoteAddress())) { + ctx.disconnect(); + return; + } + } + //Adding the channel to the server list. server.channels.add(ctx.channel()); From ab79ee9be0c1b9014cd5ad690aab244d2cea8e74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 19:21:42 +0100 Subject: [PATCH 56/60] s --- .../p2p/router/data/message/tunnel/MessageTunnel.java | 4 ++++ .../p2p/router/data/message/tunnel/MessageTunnelManager.java | 1 + 2 files changed, 5 insertions(+) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 7a02a28d..613dbbc4 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -128,11 +128,13 @@ public void setOtherPublicKey(PublicKey publicKey) { */ public void calcSharedSecret() { try { + logger.info("Calculating the shared secret for tunnel: {}", this); KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", KeyTools.KEYGEN_ALGORITHM_PROVIDER); keyAgreement.init(Node.self.getIdentity().getPrivateKey()); //Self private key. keyAgreement.doPhase(getOtherPublicKey(), true); sharedSecret = keyAgreement.generateSecret(); + logger.info("Calculating the symmetric key for tunnel: {}", this); // Derive a key from the shared secret and both public keys MessageDigest hash = MessageDigest.getInstance("SHA-256"); hash.update(sharedSecret); @@ -145,6 +147,8 @@ public void calcSharedSecret() { byte[] derivedKey = hash.digest(); derivedSymmetricKey = new SecretKeySpec(derivedKey, 0, 16, "AES"); + if(derivedSymmetricKey != null && sharedSecret != null) + logger.info("Shared secret calculated for tunnel: {}", this); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java index 08046a65..5edc8f6c 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelManager.java @@ -182,6 +182,7 @@ public void onEventCalled(Event e) { try { //Setting the other's public key. tunnel.setOtherPublicKey(KeyTools.fromUncompressedPoint(tunnelEstablishResponseMessage.publicKey)); + //Calculating the shared secret. tunnel.calcSharedSecret(); } catch (Exception e1) { From 57cf7b4e3920b115cb6ca777f94faffd4d85eecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 19:50:12 +0100 Subject: [PATCH 57/60] Update MessageTunnel.java --- .../p2p/router/data/message/tunnel/MessageTunnel.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index 613dbbc4..fa4d023e 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -147,8 +147,10 @@ public void calcSharedSecret() { byte[] derivedKey = hash.digest(); derivedSymmetricKey = new SecretKeySpec(derivedKey, 0, 16, "AES"); - if(derivedSymmetricKey != null && sharedSecret != null) - logger.info("Shared secret calculated for tunnel: {}", this); + if(sharedSecret == null) + logger.info("Shared secret couldn't be calculated for tunnel: {}", this); + if(derivedSymmetricKey == null) + logger.info("Symmetric key couldn't be calculated for tunnel: {}", this); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { From 2f7dd7ddd61daf96b81428d7144a8a3e028f71d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Sun, 13 Jan 2019 23:22:09 +0100 Subject: [PATCH 58/60] a --- .idea/modules.xml | 2 ++ build.gradle | 8 +++---- shared/build.gradle | 8 +++---- .../data/message/tunnel/MessageTunnel.java | 23 ++++++++++++++----- 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/.idea/modules.xml b/.idea/modules.xml index fd33326f..575e37c7 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -3,6 +3,8 @@ + + diff --git a/build.gradle b/build.gradle index f521ef3b..266a7d2d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,13 @@ allprojects { - -} -subprojects { apply plugin: "java" sourceCompatibility = "1.8" targetCompatibility = "1.8" group 'me.matoosh.undernet' version '0.3' - +} +subprojects { repositories { - mavenCentral() + jcenter() } dependencies { diff --git a/shared/build.gradle b/shared/build.gradle index 4fabf987..1d9ccd1a 100644 --- a/shared/build.gradle +++ b/shared/build.gradle @@ -1,7 +1,5 @@ dependencies { - // https://mvnrepository.com/artifact/io.netty/netty-all - compile group: 'io.netty', name: 'netty-all', version: '4.1.22.Final' - compile group: 'org.apache.commons', name: 'commons-crypto', version: '1.0.0' - // https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 - compile group: 'org.bouncycastle', name: 'bcprov-jdk16', version: '1.45' + implementation group: 'io.netty', name: 'netty-all', version: '4.1.22.Final' + implementation group: 'org.apache.commons', name: 'commons-crypto', version: '1.0.0' + compileClasspath group: 'org.bouncycastle', name: 'bcprov-jdk16', version: '1.45' } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java index fa4d023e..207b24d2 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnel.java @@ -7,8 +7,10 @@ import me.matoosh.undernet.p2p.router.data.NetworkID; import me.matoosh.undernet.p2p.router.data.message.MsgBase; import me.matoosh.undernet.p2p.router.data.message.NetworkMessage; +import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import sun.security.util.KeyUtil; import javax.crypto.Cipher; import javax.crypto.KeyAgreement; @@ -129,7 +131,18 @@ public void setOtherPublicKey(PublicKey publicKey) { public void calcSharedSecret() { try { logger.info("Calculating the shared secret for tunnel: {}", this); - KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", KeyTools.KEYGEN_ALGORITHM_PROVIDER); + KeyAgreement keyAgreement; + try { + keyAgreement = KeyAgreement.getInstance("ECDH", KeyTools.KEYGEN_ALGORITHM_PROVIDER ); + } catch (NoSuchAlgorithmException e) { + logger.error("Problem getting key agreement instance!", e); + UnderNet.router.messageTunnelManager.closeTunnel(this); + return; + } catch (NoSuchProviderException e) { + logger.error("Problem getting key agreement instance!", e); + UnderNet.router.messageTunnelManager.closeTunnel(this); + return; + } keyAgreement.init(Node.self.getIdentity().getPrivateKey()); //Self private key. keyAgreement.doPhase(getOtherPublicKey(), true); sharedSecret = keyAgreement.generateSecret(); @@ -148,14 +161,12 @@ public void calcSharedSecret() { derivedSymmetricKey = new SecretKeySpec(derivedKey, 0, 16, "AES"); if(sharedSecret == null) - logger.info("Shared secret couldn't be calculated for tunnel: {}", this); + logger.warn("Shared secret couldn't be calculated for tunnel: {}", this); if(derivedSymmetricKey == null) - logger.info("Symmetric key couldn't be calculated for tunnel: {}", this); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); + logger.warn("Symmetric key couldn't be calculated for tunnel: {}", this); } catch (InvalidKeyException e) { e.printStackTrace(); - } catch (NoSuchProviderException e) { + } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } From 71c992951667935bdc93b2c1c84d1e1b74e63a5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Mon, 14 Jan 2019 13:29:16 +0100 Subject: [PATCH 59/60] a --- .idea/modules.xml | 2 ++ shared/build.gradle | 2 +- .../p2p/router/data/resource/ResourceManager.java | 1 - standalone/build.gradle | 14 +++++++++----- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/.idea/modules.xml b/.idea/modules.xml index 575e37c7..25e54d2b 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -4,6 +4,8 @@ + + diff --git a/shared/build.gradle b/shared/build.gradle index 1d9ccd1a..5ef468a5 100644 --- a/shared/build.gradle +++ b/shared/build.gradle @@ -1,5 +1,5 @@ dependencies { implementation group: 'io.netty', name: 'netty-all', version: '4.1.22.Final' implementation group: 'org.apache.commons', name: 'commons-crypto', version: '1.0.0' - compileClasspath group: 'org.bouncycastle', name: 'bcprov-jdk16', version: '1.45' + implementation group: 'org.bouncycastle', name: 'bcprov-jdk16', version: '1.45' } diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java index 57217030..1f6dfdb3 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/router/data/resource/ResourceManager.java @@ -5,7 +5,6 @@ import me.matoosh.undernet.event.EventManager; import me.matoosh.undernet.event.channel.ConnectionEstablishedEvent; import me.matoosh.undernet.event.channel.message.MessageReceivedEvent; -import me.matoosh.undernet.event.resource.ResourceErrorEvent; import me.matoosh.undernet.event.resource.pull.ResourcePullReceivedEvent; import me.matoosh.undernet.event.resource.pull.ResourcePullSentEvent; import me.matoosh.undernet.event.resource.transfer.*; diff --git a/standalone/build.gradle b/standalone/build.gradle index 6639153d..0c0bc370 100644 --- a/standalone/build.gradle +++ b/standalone/build.gradle @@ -1,4 +1,5 @@ apply plugin: 'application' +apply plugin: 'java-library-distribution' dependencies { compile project(path: ':shared') @@ -10,15 +11,18 @@ dependencies { // Include dependent libraries in archive. mainClassName = "me.matoosh.undernet.standalone.UnderNetStandalone" +// Task "distZip" added by plugin "java-library-distribution": +distZip.shouldRunAfter(build) + jar { // Keep jar clean: exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF' manifest { - attributes "Main-Class": "$mainClassName" - } - - from { - configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } + attributes 'Main-Class': 'me.matoosh.undernet.standalone.UnderNetStandalone', + 'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' ') } + // How-to add class path: + // http://stackoverflow.com/questions/22659463/add-classpath-in-manifest-using-gradle + // https://gist.github.com/simon04/6865179 } \ No newline at end of file From 50b2c4fc65351e980926ba563c20e7dde19686a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20R=C4=99bacz?= Date: Tue, 15 Jan 2019 13:27:36 +0100 Subject: [PATCH 60/60] Redone dialogs --- .idea/resourceBundles.xml | 8 - .../undernet/p2p/cache/EntryNodeCache.java | 5 +- .../undernet/standalone/uix/MainFrame.java | 2 - .../undernet/standalone/uix/NodePanel.java | 4 +- .../standalone/uix/ResourcePanel.java | 14 +- .../undernet/standalone/uix/VisualPanel.form | 4 +- .../undernet/standalone/uix/VisualPanel.java | 2 + .../standalone/uix/dialog/AddNodeDialog.form | 82 +++++ .../standalone/uix/dialog/AddNodeDialog.java | 199 ++++++++++++ .../standalone/uix/dialog/NodeAddDialog.java | 87 ------ .../uix/dialog/PublishResourceDialog.form | 104 +++++++ .../uix/dialog/PublishResourceDialog.java | 234 ++++++++++++++ .../uix/dialog/PullResourceDialog.form | 120 ++++++++ .../uix/dialog/PullResourceDialog.java | 285 ++++++++++++++++++ .../uix/dialog/ResourcePublishDialog.java | 95 ------ .../uix/dialog/ResourcePullDialog.java | 137 --------- .../src/main/resources/language.properties | 16 +- .../main/resources/language_Polish.properties | 0 .../resources/language_Russian.properties | 0 .../main/resources/language_pl_PL.properties | 25 ++ 20 files changed, 1077 insertions(+), 346 deletions(-) create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.java create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.form create mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java delete mode 100644 standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java delete mode 100644 standalone/src/main/resources/language_Polish.properties delete mode 100644 standalone/src/main/resources/language_Russian.properties create mode 100644 standalone/src/main/resources/language_pl_PL.properties diff --git a/.idea/resourceBundles.xml b/.idea/resourceBundles.xml index e0845a6e..83d61e99 100644 --- a/.idea/resourceBundles.xml +++ b/.idea/resourceBundles.xml @@ -2,13 +2,5 @@ - - - - - - - language - \ No newline at end of file diff --git a/shared/src/main/java/me/matoosh/undernet/p2p/cache/EntryNodeCache.java b/shared/src/main/java/me/matoosh/undernet/p2p/cache/EntryNodeCache.java index ac62f8fb..ebc64ae9 100644 --- a/shared/src/main/java/me/matoosh/undernet/p2p/cache/EntryNodeCache.java +++ b/shared/src/main/java/me/matoosh/undernet/p2p/cache/EntryNodeCache.java @@ -9,8 +9,6 @@ import java.io.*; import java.net.InetSocketAddress; -import java.net.NetworkInterface; -import java.net.SocketException; import java.util.ArrayList; /** @@ -95,6 +93,7 @@ public static Node addNode(String host) { } } node.setAddress(new InetSocketAddress(addressSplit[0], port)); + if(node.getAddress() == null || node.getAddress().getAddress() == null) return null; //Adding the node to the cache. EntryNodeCache.addNode(node); @@ -106,7 +105,7 @@ public static Node addNode(String host) { * @param node */ public static void addNode(Node node) { - if(Node.isLocalAddress(node.getAddress())) { + if(node == null || Node.isLocalAddress(node.getAddress())) { logger.warn("Can't add a local address to Node Cache!"); return; } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java index dbf0a54e..cd8e3b15 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/MainFrame.java @@ -47,7 +47,6 @@ public class MainFrame extends EventHandler { private JButton mainButton; private VisualPanel visualPanel; private TransferPanel transferPanel; - private ControlIcon controlIcon1; public static final int START_HEIGHT = 600; public static final int START_WIDTH = 950; @@ -175,7 +174,6 @@ private void drawLoop() { } private void createUIComponents() { - controlIcon1 = new ControlIcon(); mainButton = new JButton(ResourceBundle.getBundle("language").getString("button_connect")); } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java index 06095128..54746f4d 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/NodePanel.java @@ -13,7 +13,7 @@ import me.matoosh.undernet.p2p.cache.EntryNodeCache; import me.matoosh.undernet.p2p.node.Node; import me.matoosh.undernet.p2p.router.InterfaceStatus; -import me.matoosh.undernet.standalone.uix.dialog.NodeAddDialog; +import me.matoosh.undernet.standalone.uix.dialog.AddNodeDialog; import javax.swing.*; import java.awt.*; @@ -31,7 +31,7 @@ public class NodePanel extends EventHandler { public NodePanel() { //add node button clicked. $$$setupUI$$$(); - addNodeButton.addActionListener(e -> new NodeAddDialog(MainFrame.instance.frame).setVisible(true)); + addNodeButton.addActionListener(e -> AddNodeDialog.newInstance()); //remove node button removeNodeButton.addActionListener(e -> { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java index 84488b45..5c61349f 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/ResourcePanel.java @@ -11,12 +11,10 @@ import me.matoosh.undernet.event.resource.transfer.ResourceTransferStartedEvent; import me.matoosh.undernet.event.router.RouterControlLoopEvent; import me.matoosh.undernet.event.router.RouterStatusEvent; -import me.matoosh.undernet.p2p.node.Node; -import me.matoosh.undernet.p2p.router.InterfaceStatus; import me.matoosh.undernet.p2p.router.data.resource.FileResource; import me.matoosh.undernet.p2p.router.data.resource.Resource; -import me.matoosh.undernet.standalone.uix.dialog.ResourcePublishDialog; -import me.matoosh.undernet.standalone.uix.dialog.ResourcePullDialog; +import me.matoosh.undernet.standalone.uix.dialog.PublishResourceDialog; +import me.matoosh.undernet.standalone.uix.dialog.PullResourceDialog; import javax.swing.*; import java.awt.*; @@ -35,12 +33,8 @@ public class ResourcePanel extends EventHandler { public ResourcePanel() { $$$setupUI$$$(); registerListeners(); - publishButton.addActionListener(e -> { - new ResourcePublishDialog(MainFrame.instance.frame).setVisible(true); - }); - pullButton.addActionListener(e -> { - new ResourcePullDialog(MainFrame.instance.frame).setVisible(true); - }); + publishButton.addActionListener(e -> PublishResourceDialog.newInstance()); + pullButton.addActionListener(e -> PullResourceDialog.newInstance()); resourceList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form index d8054edc..b9309727 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.form @@ -5,7 +5,9 @@ - + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java index 66752709..41ea272b 100644 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/VisualPanel.java @@ -29,6 +29,7 @@ public JPanel getPanel() { */ private void $$$setupUI$$$() { createUIComponents(); + panel.setDoubleBuffered(true); } /** @@ -37,4 +38,5 @@ public JPanel getPanel() { public JComponent $$$getRootComponent$$$() { return panel; } + } diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.form new file mode 100644 index 00000000..29116ce9 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.form @@ -0,0 +1,82 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.java new file mode 100644 index 00000000..ba0faf8f --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/AddNodeDialog.java @@ -0,0 +1,199 @@ +package me.matoosh.undernet.standalone.uix.dialog; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.p2p.cache.EntryNodeCache; +import me.matoosh.undernet.p2p.node.Node; +import me.matoosh.undernet.p2p.router.InterfaceStatus; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ResourceBundle; + +/** + * Add node dialog. + */ +public class AddNodeDialog extends JDialog { + private JPanel contentPane; + private JButton buttonSave; + private JButton buttonCancel; + private JTextField addressField; + + public AddNodeDialog() { + setContentPane(contentPane); + setModal(true); + getRootPane().setDefaultButton(buttonSave); + setTitle(ResourceBundle.getBundle("language").getString("dialog_addNode")); + centerDialogOnMouse(); + + buttonSave.addActionListener(e -> onSave()); + buttonCancel.addActionListener(e -> onCancel()); + + // call onCancel() when cross is clicked + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + onCancel(); + } + }); + + if (UnderNet.router.status.equals(InterfaceStatus.STARTED)) { + buttonSave.setText(ResourceBundle.getBundle("language").getString("button_connect")); + } else { + buttonSave.setText(ResourceBundle.getBundle("language").getString("button_save")); + } + + // call onCancel() on ESCAPE + contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + // call onSave() on ENTER + contentPane.registerKeyboardAction(e -> onSave(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + } + + private void onSave() { + //Adds node to the cache. + Node saved; + if (addressField.getText() == null || addressField.getText().trim().equals("")) { + saved = null; + } else { + saved = EntryNodeCache.addNode(addressField.getText()); + } + + //Connecting if started. + if (saved != null) { + if (UnderNet.router.status.equals(InterfaceStatus.STARTED) || UnderNet.router.status.equals(InterfaceStatus.STARTING)) { + UnderNet.router.connectNode(saved); + } + dispose(); + } else { + Toolkit.getDefaultToolkit().beep(); + } + } + + private void onCancel() { + dispose(); + } + + /** + * Centers the window on mouse. + */ + private void centerDialogOnMouse() { + Point mousePoint = MouseInfo.getPointerInfo().getLocation(); + setLocation(mousePoint.x - getWidth() / 2, mousePoint.y - getHeight() / 2); + } + + public static void newInstance() { + AddNodeDialog dialog = new AddNodeDialog(); + dialog.pack(); + dialog.setVisible(true); + } + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + contentPane = new JPanel(); + contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1)); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); + final Spacer spacer1 = new Spacer(); + panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); + panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + buttonSave = new JButton(); + buttonSave.setText("OK"); + panel2.add(buttonSave, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + buttonCancel = new JButton(); + buttonCancel.setAutoscrolls(false); + this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("language").getString("button_cancel")); + panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JPanel panel3 = new JPanel(); + panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + addressField = new JTextField(); + panel3.add(addressField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); + final JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("dialog_addNode_nodeAddress")); + panel3.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + label1.setLabelFor(addressField); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return contentPane; + } + +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java deleted file mode 100644 index 4709548b..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/NodeAddDialog.java +++ /dev/null @@ -1,87 +0,0 @@ -package me.matoosh.undernet.standalone.uix.dialog; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.p2p.cache.EntryNodeCache; -import me.matoosh.undernet.p2p.node.Node; -import me.matoosh.undernet.p2p.router.InterfaceStatus; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * A dialog for adding new node to the node cache. - * Created by Mateusz Rębacz on 11.09.2017. - */ - -public class NodeAddDialog extends JDialog { - /** - * The text field with the address of the node. - */ - private JTextField nodeAddressField; - - public NodeAddDialog(JFrame parent) { - //Setting the title of the dialog. - super(parent, "Add Node", true); - - //Setting the content. - setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); - setSize(300, 120); - centerDialogOnMouse(); - addContent(); - setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - } - - /** - * Centers the window on mouse. - */ - private void centerDialogOnMouse() { - Point mousePoint = MouseInfo.getPointerInfo().getLocation(); - setLocation(mousePoint.x - getSize().width/2, mousePoint.y - getSize().height/2); - } - /** - * Adds content to the dialog. - */ - private void addContent() { - add(new JLabel("IP Address")); - nodeAddressField = new JTextField(); - add(nodeAddressField); - - add(new JPanel()); - - JPanel buttonDrawer = new JPanel(); - buttonDrawer.setLayout(new BoxLayout(buttonDrawer, BoxLayout.X_AXIS)); - - final JButton saveButton = new JButton("Save"); - saveButton.addActionListener(actionEvent -> { - //Adds node to the cache. - Node saved = EntryNodeCache.addNode(nodeAddressField.getText()); - - //Connecting if started. - if (UnderNet.router.status.equals(InterfaceStatus.STARTED) || UnderNet.router.status.equals(InterfaceStatus.STARTING)) { - UnderNet.router.connectNode(saved); - } - - //Closing the dialog. - NodeAddDialog.this.dispose(); - }); - if(UnderNet.router.status.equals(InterfaceStatus.STARTED) || UnderNet.router.status.equals(InterfaceStatus.STARTING)) { - saveButton.setText("Connect"); - } - buttonDrawer.add(saveButton); - - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Closing the dialog. - NodeAddDialog.this.dispose(); - } - }); - - buttonDrawer.add(cancelButton); - - add(buttonDrawer); - } -} \ No newline at end of file diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.form new file mode 100644 index 00000000..19f8dcbf --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.form @@ -0,0 +1,104 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.java new file mode 100644 index 00000000..70e214d4 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PublishResourceDialog.java @@ -0,0 +1,234 @@ +package me.matoosh.undernet.standalone.uix.dialog; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.p2p.router.data.resource.FileResource; +import me.matoosh.undernet.standalone.uix.MainFrame; + +import javax.swing.*; +import java.awt.*; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.*; +import java.io.File; +import java.util.ResourceBundle; + +/** + * The publish resource dialog. + */ +public class PublishResourceDialog extends JDialog { + private JPanel contentPane; + private JButton buttonPublish; + private JButton buttonCancel; + private JTextField filePathField; + private JButton chooseFileButton; + + public PublishResourceDialog() { + setContentPane(contentPane); + setModal(true); + getRootPane().setDefaultButton(buttonPublish); + centerDialogOnMouse(); + onFileChosen(); + + chooseFileButton.addActionListener(e -> onChooseFile()); + buttonPublish.addActionListener(e -> onPublish()); + buttonCancel.addActionListener(e -> onCancel()); + + // call onCancel() when cross is clicked + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + onCancel(); + } + }); + + // call onCancel() on ESCAPE + contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + // call onPublish() on ENTER + contentPane.registerKeyboardAction(e -> onPublish(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + filePathField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + onFileChosen(); + } + }); + } + + private void onPublish() { + //Button clicked. Checking whether a correct path has been chosen. + if (filePathField.getText() != null && !filePathField.getText().trim().equals("")) { + //Publishing resource on UnderNet. + FileResource fileResource = new FileResource(UnderNet.router, new File(filePathField.getText())); + if (!fileResource.copyToContent()) { + JOptionPane.showMessageDialog(MainFrame.instance.frame, String.format(ResourceBundle.getBundle("language").getString("dialog_publishResource_cantPublishMessage"), fileResource.file), ResourceBundle.getBundle("language").getString("dialog_publishResource_cantPublishTitle"), JOptionPane.ERROR_MESSAGE); + return; + } + UnderNet.router.resourceManager.publish(fileResource); + + //Copying the network to clipboard. + StringSelection stringSelection = new StringSelection(fileResource.getNetworkID().getStringValue()); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, null); + + //Showing the published network id. + JOptionPane.showMessageDialog(MainFrame.instance.frame, String.format(ResourceBundle.getBundle("language").getString("dialog_publishResource_publishingMessage"), fileResource.file, fileResource.getNetworkID().getStringValue()), ResourceBundle.getBundle("language").getString("dialog_publishResource_publishingTitle"), JOptionPane.INFORMATION_MESSAGE); + + dispose(); + } else { + getToolkit().beep(); + } + } + + private void onCancel() { + dispose(); + } + + private void onChooseFile() { + //Open file choose dialog + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); + int result = fileChooser.showOpenDialog(this); + if (result == JFileChooser.APPROVE_OPTION) { + filePathField.setText(fileChooser.getSelectedFile().getPath()); + onFileChosen(); + } + } + + /** + * Called when the file field is modified. + */ + private void onFileChosen() { + if (filePathField.getText() != null && filePathField.getText().trim() != "") { + buttonPublish.setEnabled(true); + } else { + buttonPublish.setEnabled(false); + } + } + + /** + * Centers the window on mouse. + */ + private void centerDialogOnMouse() { + Point mousePoint = MouseInfo.getPointerInfo().getLocation(); + setLocation(mousePoint.x - getWidth() / 2, mousePoint.y - getHeight() / 2); + } + + public static void newInstance() { + PublishResourceDialog dialog = new PublishResourceDialog(); + dialog.pack(); + dialog.setVisible(true); + } + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + contentPane = new JPanel(); + contentPane.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1)); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); + final Spacer spacer1 = new Spacer(); + panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); + panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + buttonPublish = new JButton(); + this.$$$loadButtonText$$$(buttonPublish, ResourceBundle.getBundle("language").getString("button_publishResource")); + panel2.add(buttonPublish, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + buttonCancel = new JButton(); + this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("language").getString("button_cancel")); + panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JPanel panel3 = new JPanel(); + panel3.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + final JPanel panel4 = new JPanel(); + panel4.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); + panel3.add(panel4, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + filePathField = new JTextField(); + panel4.add(filePathField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); + chooseFileButton = new JButton(); + this.$$$loadButtonText$$$(chooseFileButton, ResourceBundle.getBundle("language").getString("dialog_publishResource_chooseFile")); + panel4.add(chooseFileButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("dialog_publishResource_file")); + panel4.add(label1, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JSeparator separator1 = new JSeparator(); + contentPane.add(separator1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return contentPane; + } + +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.form b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.form new file mode 100644 index 00000000..b29dcd11 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.form @@ -0,0 +1,120 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java new file mode 100644 index 00000000..68ad1d51 --- /dev/null +++ b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/PullResourceDialog.java @@ -0,0 +1,285 @@ +package me.matoosh.undernet.standalone.uix.dialog; + +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; +import me.matoosh.undernet.UnderNet; +import me.matoosh.undernet.event.Event; +import me.matoosh.undernet.event.EventHandler; +import me.matoosh.undernet.event.EventManager; +import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; +import me.matoosh.undernet.p2p.router.data.NetworkID; +import me.matoosh.undernet.p2p.router.data.resource.FileResource; +import me.matoosh.undernet.p2p.router.data.resource.ResourceType; +import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferType; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.ResourceBundle; + +/** + * A pull resource dialog. + */ +public class PullResourceDialog extends JDialog { + private JPanel contentPane; + private JButton buttonPull; + private JButton buttonCancel; + private JTextField filePathField; + private JButton chooseFileButton; + private JTextField networkIdField; + + public PullResourceDialog() { + setContentPane(contentPane); + setModal(true); + getRootPane().setDefaultButton(buttonPull); + centerDialogOnMouse(); + + buttonPull.addActionListener(e -> onPull()); + buttonCancel.addActionListener(e -> onCancel()); + chooseFileButton.addActionListener(e -> onChooseSaveDir()); + + // call onCancel() when cross is clicked + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + onCancel(); + } + }); + + // call onCancel() on ESCAPE + contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + // call onOK() on ENTER + contentPane.registerKeyboardAction(e -> onPull(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + + filePathField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + verifyFields(); + } + }); + networkIdField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + verifyFields(); + } + }); + } + + private void onPull() { + if (!verifyFields()) { + getToolkit().beep(); + return; + } + + NetworkID netId = new NetworkID(networkIdField.getText().replaceAll("\\s+", "")); + UnderNet.router.resourceManager.pull(netId); //Use inputted network id. + String saveDir = filePathField.getText(); + + //Registering the pull event. + EventManager.registerHandler(new EventHandler() { + @Override + public void onEventCalled(Event e) { + ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; + + if (transferFinishedEvent.getTransferHandler().getTransferType() == ResourceTransferType.INBOUND && transferFinishedEvent.getTransferHandler().getResource().getNetworkID().equals(netId) && transferFinishedEvent.getTransferHandler().getResource().getInfo().resourceType == ResourceType.FILE) { + FileResource fileResource = (FileResource) transferFinishedEvent.getTransferHandler().getResource(); + + //Copying the received file to dest. + if (saveDir != null) { + try { + Files.copy(Paths.get(fileResource.file.getAbsolutePath()), Paths.get(saveDir + "/" + fileResource.file.getName()), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e1) { + e1.printStackTrace(); + } finally { + //File dialog. + EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(PullResourceDialog.this, String.format(ResourceBundle.getBundle("language").getString("dialog_pullResource_transferFinished_message"), fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveDir), ResourceBundle.getBundle("language").getString("dialog_pullResource_transferFinished_title"), JOptionPane.INFORMATION_MESSAGE)); + } + } else { + //File dialog. + EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(PullResourceDialog.this, String.format(ResourceBundle.getBundle("language").getString("dialog_pullResource_transferFinished_message"), fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), ResourceBundle.getBundle("language").getString("dialog_pullResource_transferFinished_title"), JOptionPane.INFORMATION_MESSAGE)); + } + } + + //Unregistering the handler. + EventManager.unregisterHandler(this, ResourceTransferFinishedEvent.class); + } + }, ResourceTransferFinishedEvent.class); + + dispose(); + } + + private void onCancel() { + // add your code here if necessary + dispose(); + } + + private void onChooseSaveDir() { + //Open file choose dialog + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileChooser.setDialogTitle("Choose the save directory"); + int result = fileChooser.showOpenDialog(this); + if (result == JFileChooser.APPROVE_OPTION) { + filePathField.setText(fileChooser.getSelectedFile().getPath()); + verifyFields(); + } + } + + private boolean verifyFields() { + boolean correct; + + //network id + if (networkIdField.getText() != null && !networkIdField.getText().trim().equals("")) { + correct = new NetworkID(networkIdField.getText().replaceAll("\\s+", "")).isValid(); + } else { + correct = false; + } + + //file + if (filePathField.getText() == null || filePathField.getText().trim().equals("")) + correct = false; + + buttonPull.setEnabled(correct); + return correct; + } + + public static void newInstance() { + PullResourceDialog dialog = new PullResourceDialog(); + dialog.pack(); + dialog.setVisible(true); + } + + /** + * Centers the window on mouse. + */ + private void centerDialogOnMouse() { + Point mousePoint = MouseInfo.getPointerInfo().getLocation(); + setLocation(mousePoint.x - getSize().width / 2, mousePoint.y - getSize().height / 2); + } + + { +// GUI initializer generated by IntelliJ IDEA GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + contentPane = new JPanel(); + contentPane.setLayout(new GridLayoutManager(4, 1, new Insets(10, 10, 10, 10), -1, -1)); + final JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + filePathField = new JTextField(); + panel1.add(filePathField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); + chooseFileButton = new JButton(); + this.$$$loadButtonText$$$(chooseFileButton, ResourceBundle.getBundle("language").getString("dialog_publishResource_chooseFile")); + panel1.add(chooseFileButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("language").getString("dialog_pullResource_saveTo")); + panel1.add(label1, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel2, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); + final Spacer spacer1 = new Spacer(); + panel2.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); + final JPanel panel3 = new JPanel(); + panel3.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); + panel2.add(panel3, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + buttonPull = new JButton(); + this.$$$loadButtonText$$$(buttonPull, ResourceBundle.getBundle("language").getString("button_pullResource")); + panel3.add(buttonPull, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + buttonCancel = new JButton(); + this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("language").getString("button_cancel")); + panel3.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + final JPanel panel4 = new JPanel(); + panel4.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); + contentPane.add(panel4, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); + final JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, ResourceBundle.getBundle("language").getString("dialog_pullResource_networkID")); + panel4.add(label2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); + networkIdField = new JTextField(); + panel4.add(networkIdField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); + final JSeparator separator1 = new JSeparator(); + contentPane.add(separator1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); + } + + /** + * @noinspection ALL + */ + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuffer result = new StringBuffer(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) break; + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + /** + * @noinspection ALL + */ + public JComponent $$$getRootComponent$$$() { + return contentPane; + } + +} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java deleted file mode 100644 index e04f3a4d..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePublishDialog.java +++ /dev/null @@ -1,95 +0,0 @@ -package me.matoosh.undernet.standalone.uix.dialog; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.p2p.router.data.resource.FileResource; - -import javax.swing.*; -import java.awt.*; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.StringSelection; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -/** - * Dialog for uploading resources to the network. - * Created by Mateusz Rębacz on 20.10.2017. - */ - -public class ResourcePublishDialog extends JDialog { - /** - * The result of the last file choosing the user has done. - */ - private File fileChooseResult; - - private JFrame frame; - - public ResourcePublishDialog(JFrame parent) { - //Setting the title of the dialog. - super(parent, "Publish Resource", true); - this.frame = parent; - - //Setting the content. - setLayout(new GridBagLayout()); - setSize(220, 110); - centerDialogOnMouse(); - addContent(); - setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - } - - /** - * Centers the window on mouse. - */ - private void centerDialogOnMouse() { - Point mousePoint = MouseInfo.getPointerInfo().getLocation(); - setLocation(mousePoint.x - getSize().width/2, mousePoint.y - getSize().height/2); - } - - /** - * Adds content to the dialog. - */ - private void addContent() { - JButton chooseFileButton = new JButton("Select file..."); - chooseFileButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Button clicked. - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); - int result = fileChooser.showOpenDialog(ResourcePublishDialog.this); - if(result == JFileChooser.APPROVE_OPTION) { - fileChooseResult = fileChooser.getSelectedFile(); - } - } - }); - add(chooseFileButton, new GridBagConstraints()); - - JButton uploadButton = new JButton("Publish!"); - uploadButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Button clicked. Checking whether a correct path has been chosen. - if(fileChooseResult != null) { - //Publishing resource on UnderNet. - FileResource fileResource = new FileResource(UnderNet.router, fileChooseResult); - if(!fileResource.copyToContent()) { - JOptionPane.showMessageDialog(ResourcePublishDialog.this.frame, String.format("There was a problem accessing file: \n%s.", fileChooseResult), "Can't publish resource!", JOptionPane.ERROR_MESSAGE); - ResourcePublishDialog.this.dispose(); - return; - } - UnderNet.router.resourceManager.publish(fileResource); - ResourcePublishDialog.this.dispose(); - - //Copying the network to clipboard. - StringSelection stringSelection = new StringSelection(fileResource.getNetworkID().getStringValue()); - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(stringSelection, null); - - //Showing the published network id. - JOptionPane.showMessageDialog(ResourcePublishDialog.this.frame, String.format("Publishing %s, \nNetwork id: %s \nThe network id has been copied to your clipboard.", fileChooseResult, fileResource.getNetworkID().getStringValue()), "Publishing resource", JOptionPane.INFORMATION_MESSAGE); - } - } - }); - add(uploadButton, new GridBagConstraints()); - } -} diff --git a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java b/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java deleted file mode 100644 index 23d562ec..00000000 --- a/standalone/src/main/java/me/matoosh/undernet/standalone/uix/dialog/ResourcePullDialog.java +++ /dev/null @@ -1,137 +0,0 @@ -package me.matoosh.undernet.standalone.uix.dialog; - -import me.matoosh.undernet.UnderNet; -import me.matoosh.undernet.event.Event; -import me.matoosh.undernet.event.EventHandler; -import me.matoosh.undernet.event.EventManager; -import me.matoosh.undernet.event.resource.transfer.ResourceTransferFinishedEvent; -import me.matoosh.undernet.p2p.router.data.NetworkID; -import me.matoosh.undernet.p2p.router.data.resource.FileResource; -import me.matoosh.undernet.p2p.router.data.resource.ResourceType; -import me.matoosh.undernet.p2p.router.data.resource.transfer.ResourceTransferType; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; - -/** - * Dialog for pulling resources from the network. - * Created by Mateusz Rębacz on 03.11.2017. - */ - -public class ResourcePullDialog extends JDialog { - public ResourcePullDialog(JFrame parent) { - //Setting the title of the dialog. - super(parent, "Pull Resource", true); - - //Setting the content. - setLayout(new GridBagLayout()); - setSize(270, 110); - centerDialogOnMouse(); - addContent(); - setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - } - - /** - * Adds content to the frame. - */ - private void addContent() { - GridBagConstraints constraints0 = new GridBagConstraints(); - constraints0.gridx = 0; - constraints0.gridy = 0; - add(new JLabel("NetworkID:"), constraints0); - - GridBagConstraints constraints1 = new GridBagConstraints(); - constraints1.gridx = 1; - constraints1.gridy = 0; - constraints1.gridwidth = 30; - final JTextField networkIdField = new JTextField(); - networkIdField.setPreferredSize(new Dimension(150, 20)); - add(networkIdField, constraints1); - - GridBagConstraints constraints2 = new GridBagConstraints(); - constraints2.gridx = 0; - constraints2.gridy = 1; - JButton fileChooser = new JButton("Save to..."); - final File[] saveFile = {null}; - fileChooser.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - //Button clicked. - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); - fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileChooser.setDialogTitle("Choose the save directory"); - int result = fileChooser.showOpenDialog(ResourcePullDialog.this); - if (result == JFileChooser.APPROVE_OPTION) { - saveFile[0] = fileChooser.getSelectedFile(); - } - } - }); - add(fileChooser, constraints2); - - GridBagConstraints constraints3 = new GridBagConstraints(); - constraints3.gridx = 0; - constraints3.gridy = 2; - JButton pullButton = new JButton("Pull!"); - pullButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - final NetworkID netId = new NetworkID(networkIdField.getText().replaceAll("\\s+", "")); - if (netId.isValid()) { - //Starting the pull. - UnderNet.router.resourceManager.pull(netId); //Use inputted network id. - - //Registering the pull event. - EventManager.registerHandler(new EventHandler() { - @Override - public void onEventCalled(Event e) { - ResourceTransferFinishedEvent transferFinishedEvent = (ResourceTransferFinishedEvent) e; - - if (transferFinishedEvent.getTransferHandler().getTransferType() == ResourceTransferType.INBOUND && transferFinishedEvent.getTransferHandler().getResource().getNetworkID().equals(netId) && transferFinishedEvent.getTransferHandler().getResource().getInfo().resourceType == ResourceType.FILE) { - FileResource fileResource = (FileResource) transferFinishedEvent.getTransferHandler().getResource(); - - //Copying the received file to dest. - if (saveFile[0] != null) { - try { - Files.copy(Paths.get(fileResource.file.getAbsolutePath()), Paths.get(saveFile[0].getAbsolutePath() + "/" + fileResource.file.getName()), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e1) { - e1.printStackTrace(); - } finally { - //File dialog. - EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), saveFile[0]), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); - } - } else { - //File dialog. - EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(ResourcePullDialog.this, String.format("Retrieved file %s! \nNetwork id: %s \nSaved to: %s", fileResource.file.getName(), fileResource.getNetworkID().getStringValue(), UnderNet.fileManager.getContentFolder()), "File Retrieved!", JOptionPane.INFORMATION_MESSAGE)); - } - } - - //Unregistering the handler. - EventManager.unregisterHandler(this, ResourceTransferFinishedEvent.class); - } - }, ResourceTransferFinishedEvent.class); - - ResourcePullDialog.this.dispose(); - } else { - JOptionPane.showMessageDialog(ResourcePullDialog.this, "The Network ID you specified is invalid!", "Invalid Network ID", JOptionPane.ERROR_MESSAGE); - } - } - }); - add(pullButton, constraints3); - } - - /** - * Centers the window on mouse. - */ - private void centerDialogOnMouse() { - Point mousePoint = MouseInfo.getPointerInfo().getLocation(); - setLocation(mousePoint.x - getSize().width / 2, mousePoint.y - getSize().height / 2); - } -} diff --git a/standalone/src/main/resources/language.properties b/standalone/src/main/resources/language.properties index b1827bd9..4d4c06d4 100644 --- a/standalone/src/main/resources/language.properties +++ b/standalone/src/main/resources/language.properties @@ -5,7 +5,21 @@ button_disconnectNode=Disconnect Node button_publishResource=Publish button_pullResource=Pull button_removeNode=Remove Node +button_cancel=Cancel +dialog_addNode=Add Node +button_save=Save +dialog_addNode_nodeAddress=Node Address: title_nodes=Nodes title_resources=Resources title_transfers=Active Transfers -title_tunnels=Active Tunnels \ No newline at end of file +title_tunnels=Active Tunnels +dialog_publishResource_publishingTitle=Publishing resource +dialog_publishResource_publishingMessage=Publishing %s\nNetwork ID: %s\nThe Network ID has been copied to your clipboard. +dialog_publishResource_cantPublishTitle=Can't publish resource! +dialog_publishResource_cantPublishMessage=There was a problem accessing file:\n%s. +dialog_publishResource_chooseFile=Choose... +dialog_publishResource_file=File: +dialog_pullResource_transferFinished_title=File Retrieved! +dialog_pullResource_transferFinished_message=Retrieved file %s!\nNetwork id: %s\nSaved to: %s +dialog_pullResource_saveTo=Save to: +dialog_pullResource_networkID=Network ID: \ No newline at end of file diff --git a/standalone/src/main/resources/language_Polish.properties b/standalone/src/main/resources/language_Polish.properties deleted file mode 100644 index e69de29b..00000000 diff --git a/standalone/src/main/resources/language_Russian.properties b/standalone/src/main/resources/language_Russian.properties deleted file mode 100644 index e69de29b..00000000 diff --git a/standalone/src/main/resources/language_pl_PL.properties b/standalone/src/main/resources/language_pl_PL.properties new file mode 100644 index 00000000..e4ed4c60 --- /dev/null +++ b/standalone/src/main/resources/language_pl_PL.properties @@ -0,0 +1,25 @@ +button_addNode=Dodaj W\u0119ze\u0142 +button_connect=Po\u0142\u0105cz +button_disconnect=Roz\u0142\u0105cz +button_disconnectNode=Roz\u0142\u0105cz W\u0119ze\u0142 +button_publishResource=Opublikuj +button_pullResource=Pobierz +button_removeNode=Usu\u0144 W\u0119ze\u0142 +button_cancel=Anuluj +dialog_addNode=Dodaj W\u0119ze\u0142 +button_save=Zapisz +dialog_addNode_nodeAddress=Adres W\u0119z\u0142a: +title_nodes=W\u0119z\u0142y +title_resources=Zasoby +title_transfers=Aktywne Transfery +title_tunnels=Aktywne Tunele +dialog_publishResource_publishingTitle=Publikowanie zasobu +dialog_publishResource_publishingMessage=Publikowanie %s\nIdentyfikator: %s\nIdentyfikator zosta\u0142 skopiowany do schowka. +dialog_publishResource_cantPublishTitle=Nie mo\u017cna opublikowa\u0107 zasobu! +dialog_publishResource_cantPublishMessage=Wystapi\u0142 problem przy pr\u00f3bie odczytu pliku:\n%s. +dialog_publishResource_chooseFile=Wybierz... +dialog_publishResource_file=Plik: +dialog_pullResource_transferFinished_title=Plik Odebrany! +dialog_pullResource_transferFinished_message=Odebrano plik %s!\nIdentyfikator: %s\nZapisano w: %s +dialog_pullResource_saveTo=Zapisz w: +dialog_pullResource_networkID=Identyfikator: \ No newline at end of file