Skip to content
Snippets Groups Projects
Unverified Commit bad4f1de authored by MessadiSaidAbdesslem's avatar MessadiSaidAbdesslem Committed by GitHub
Browse files

Merge pull request #1 from MessadiSaidAbdesslem/circularElectionAlgorithm

added circular election algorithm
parents 5c08a851 44b036f6
No related branches found
No related tags found
No related merge requests found
Showing
with 595 additions and 0 deletions
......@@ -30,3 +30,5 @@ gradle-app.setting
# Cache of project
.gradletasknamecache
/bin/
\ No newline at end of file
/*
BSD 3-Clause License
Copyright (c) 2007-2013, Distributed Computing Group (DCG)
ETH Zurich
Switzerland
dcg.ethz.ch
2017-2018, André Brait
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package projects.circularSimpleElection;
import sinalgo.nodes.Node;
import sinalgo.runtime.AbstractCustomGlobal;
import sinalgo.tools.Tools;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
/**
* This class holds customized global state and methods for the framework. The
* only mandatory method to overwrite is <code>hasTerminated</code> <br>
* Optional methods to override are
* <ul>
* <li><code>customPaint</code></li>
* <li><code>handleEmptyEventQueue</code></li>
* <li><code>onExit</code></li>
* <li><code>preRun</code></li>
* <li><code>preRound</code></li>
* <li><code>postRound</code></li>
* <li><code>checkProjectRequirements</code></li>
* </ul>
*
* @see sinalgo.runtime.AbstractCustomGlobal for more details. <br>
* In addition, this class also provides the possibility to extend the
* framework with custom methods that can be called either through the menu
* or via a button that is added to the GUI.
*/
public class CustomGlobal extends AbstractCustomGlobal {
@Override
public boolean hasTerminated() {
return false;
}
/**
* An example of a method that will be available through the menu of the GUI.
*/
@AbstractCustomGlobal.GlobalMethod(menuText = "Echo")
public void echo() {
// Query the user for an input
String answer = JOptionPane.showInputDialog(null, "This is an example.\nType in any text to echo.");
// Show an information message
JOptionPane.showMessageDialog(null, "You typed '" + answer + "'", "Example Echo",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* An example to add a button to the user interface. In this sample, the button
* is labeled with a text 'GO'. Alternatively, you can specify an icon that is
* shown on the button. See AbstractCustomGlobal.CustomButton for more details.
*/
@AbstractCustomGlobal.CustomButton(buttonText = "GO", toolTipText = "A sample button")
public void sampleButton() {
JOptionPane.showMessageDialog(null, "You Pressed the 'GO' button.");
}
/**
* Function for linking each 2 successive nodes together
*/
@AbstractCustomGlobal.GlobalMethod(menuText = "Link circular")
public void linkCircular() {
if (Tools.getNodeList().size() > 2) {
List<Node> nodeList = new ArrayList<>();
Tools.getNodeList().iterator().forEachRemaining(nodeList::add);
for (int i = 0; i < nodeList.size(); i++) {
nodeList.get(i).addConnectionTo(nodeList.get((i + 1) % nodeList.size()));
}
Tools.repaintGUI();
} else {
JOptionPane.showMessageDialog(null, "You need at least 3 nodes to make a circular linking", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
/*
BSD 3-Clause License
Copyright (c) 2007-2013, Distributed Computing Group (DCG)
ETH Zurich
Switzerland
dcg.ethz.ch
2017-2018, André Brait
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package projects.circularSimpleElection;
/**
* Enumerates the log-levels. Levels above THRESHOLD will be included in the
* log-file. The levels below (with a higher enumeration value) not.
*/
public class LogL extends sinalgo.tools.logging.LogL {
}
Place all your custom connectivity models in this folder.
\ No newline at end of file
Place all your custom distribution models in this folder.
\ No newline at end of file
Place all your custom interference models in this folder.
\ No newline at end of file
Place all your custom message transmission models in this folder.
\ No newline at end of file
Place all your custom mobility models in this folder.
\ No newline at end of file
Place all your custom reliability models in this folder.
\ No newline at end of file
Place all your custom edge implementations in this folder.
\ No newline at end of file
package projects.circularSimpleElection.nodes.messages;
import lombok.Getter;
import sinalgo.nodes.messages.Message;
public class ElectedMessage extends Message {
@Getter
private long id;
public ElectedMessage(long id) {
this.id = id;
}
@Override
public Message clone() {
return new ElectedMessage(this.id);
}
}
package projects.circularSimpleElection.nodes.messages;
import lombok.Getter;
import sinalgo.nodes.messages.Message;
public class ElectionMessage extends Message {
@Getter
private long id;
public ElectionMessage(long id) {
this.id = id;
}
@Override
public Message clone() {
return new ElectionMessage(this.id);
}
}
Place all your custom message implementations in this folder.
\ No newline at end of file
package projects.circularSimpleElection.nodes.nodeImplementations;
import java.awt.Color;
import lombok.Getter;
import lombok.Setter;
import projects.circularSimpleElection.nodes.messages.ElectedMessage;
import projects.circularSimpleElection.nodes.messages.ElectionMessage;
import projects.defaultProject.nodes.timers.MessageTimer;
import sinalgo.exception.WrongConfigurationException;
import sinalgo.nodes.Node;
import sinalgo.nodes.messages.Inbox;
import sinalgo.nodes.messages.Message;
import sinalgo.tools.Tools;
public class NodeImpl extends Node {
@Getter
@Setter
private boolean partI = false;
@Getter
@Setter
private boolean done = false;
@Getter
@Setter
private boolean elected;
@Getter
@Setter
private long leaderId;
@Override
public void checkRequirements() throws WrongConfigurationException {
}
@Override
public void handleMessages(Inbox inbox) {
while (inbox.hasNext()) {
Message msg = inbox.next();
if (msg instanceof ElectionMessage) {
ElectionMessage electionMessage = (ElectionMessage) msg;
System.out.println(electionMessage.getId());
long id = electionMessage.getId();
if (id > this.getID()) {
this.partI = true;
this.sendElection(id);
} else if (id < this.getID()) {
if (!this.partI) {
this.partI = true;
this.sendElection(this.getID());
}
} else if (id == this.getID()) {
this.elected = true;
this.setColor(Color.RED);
Tools.appendToOutput("new leader is :" + id);
this.sendElected(id);
}
}
if (msg instanceof ElectedMessage) {
ElectedMessage electedMessage = (ElectedMessage) msg;
long id = electedMessage.getId();
this.leaderId = id;
this.done = true;
Tools.appendToOutput("\n " + this.getID() + "received that " + id + " is the new leader");
if (this.getID() != id) {
this.elected = false;
this.sendElected(id);
}
}
}
}
@Override
public void init() {
}
@Override
public void neighborhoodChange() {
}
@Override
public void postStep() {
}
@Override
public void preStep() {
}
@NodePopupMethod(menuText = "Start election")
public void start() {
if (!partI) {
partI = true;
this.sendElection(getID());
}
}
private void sendElection(long id) {
MessageTimer msgTimer = new MessageTimer(new ElectionMessage(id));
msgTimer.startRelative(1, this);
}
private void sendElected(long id) {
MessageTimer msgTimer = new MessageTimer(new ElectedMessage(id));
msgTimer.startRelative(id, this);
}
}
Place all your custom node implementations in this folder.
\ No newline at end of file
Place all your custom timer implementations in this folder.
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<Framework>
<!--*********************************************************************** -->
<!-- Simulation Area -->
<!--*********************************************************************** -->
<!--Number of dimensions (2 for 2D, 3 for 3D) -->
<dimensions value="2"/>
<!--Length of the deployment field along the x-axis. -->
<dimX value="1000"/>
<!--Length of the deployment field along the y-axis. -->
<dimY value="1000"/>
<!--Length of the deployment field along the z-axis. -->
<dimZ value="500"/>
<!--*********************************************************************** -->
<!-- Simulation -->
<!--*********************************************************************** -->
<!--Switches between synchronous and asynchronous mode. -->
<asynchronousMode value="false"/>
<!--If set to true, the runtime obtains for each node a new position from
the mobility model at the beginning of each round. This flag needs to be
turned on if the chosen mobility model of any node may change the node's
position. Set this flag to FALSE for static graphs whose nodes do never change
their position to increase performance. -->
<mobility value="true"/>
<!--If set to true, the chosen interference model is called at the end
of every round to test for interferring packets. To increase performance,
set this flag to FALSE if you do not consider interference. -->
<interference value="true"/>
<!--Set this flag to true if interference only decreases if less messages
are being sent and increases if more messages are being sent. This flag enables
considerable optimizations. -->
<interferenceIsAdditive value="true"/>
<!--Set this flag to true if a node can receive messages while it is sending
messages itself, otherwise to false. This flag is only relevant if interference
is turned on, and it must be handled properly in the used interference model. -->
<canReceiveWhileSending value="true"/>
<!--The default type of edges to be used -->
<edgeType value="sinalgo.nodes.edges.Edge"/>
<!--If set to true, the application exits as soon as the termination criteria
is met. This flag only affects the GUI mode. -->
<exitOnTerminationInGUI value="false"/>
<!--If set true, in asynchronous mode the connections are initialized before
the first event executes. Note that this flag is useless in synchronous mode
as the connections are updated in every step anyway. -->
<initializeConnectionsOnStartup value="false"/>
<!--Defines how often the GUI is updated. The GUI is redrawn after every
refreshRate-th round. -->
<refreshRate value="1"/>
<!--*********************************************************************** -->
<!-- Random number generators -->
<!--*********************************************************************** -->
<!--If set to true, the random number generators of the framework use a
fixed seed. -->
<useFixedSeed value="false"/>
<!--The seed to be used by the random number generators if useFixedSeed
is set to true. -->
<fixedSeed value="77654767234"/>
<!--*********************************************************************** -->
<!-- Logging -->
<!--*********************************************************************** -->
<!--Name of the default log file, used by the system, but also for use
by the end-user. (This log file is stored under sinalgo.runtime.Global.log.) -->
<logFileName value="logfile.txt"/>
<!--Redirects the default log file to the console. No logfile will be created
if set to true. -->
<outputToConsole value="true"/>
<!--Indicates whether all log-files of the current simulation are stored
in a new directory. The name of the new directory is given by the string-representation
of the date when the simulation starts. -->
<logToTimeDirectory value="true"/>
<!--If set to true, the system configuration is written to the default
log file after the application has been started. -->
<logConfiguration value="true"/>
<!--If set to true, the log files are flushed every time a new log is added. -->
<eagerFlush value="false"/>
<!--*********************************************************************** -->
<!-- GUI -->
<!--*********************************************************************** -->
<!--If true, the application shows an extended control panel. -->
<extendedControl value="true"/>
<!--If true, the graph edges are drawn as directed arrows, otherwise simple
lines. -->
<drawArrows value="false"/>
<!--Fraction of the old and new zoom values for a zoom step. -->
<zoomStep value="1.2"/>
<!--Fraction of the old and new zoom values for a zoom step when zooming
with the mouse wheel. -->
<wheelZoomStep value="1.05"/>
<!--The minimum required zoom -->
<minZoomFactor value="0.05"/>
<!--If set to true, the nodes are ordered according to their elevation
before drawing, such that nodes closer to the viewer are drawn on top. This
setting only applies to 3D. -->
<draw3DGraphNodesInProperOrder value="true"/>
<!--If set to true and in 3D mode, the cube is drawn with perspective. -->
<usePerspectiveView value="true"/>
<!--Factor that defines the distance of the observer from the cube when
useing the perspective view in 3D. Default: 30 -->
<perspectiveViewDistance value="40"/>
<!--*********************************************************************** -->
<!-- Background map in 2D -->
<!--*********************************************************************** -->
<!--If set to true, the background of a 2D simulation is colored according
to a map, specified in a map-file, specified by the field map -->
<useMap value="false"/>
<!--In 2D, the background can be colored depending on a map file. This
field contains the file name for this map, which is supposed to be located
in the source folder of the current project. The map is only painted if useMap
is set to true. -->
<map value="images/map.jpg"/>
<!--*********************************************************************** -->
<!-- Models -->
<!--*********************************************************************** -->
<!--The message transmission model used when none is specified -->
<defaultMessageTransmissionModel
value="ConstantTime"/>
<!--Default connectivity model used when none is specified -->
<defaultConnectivityModel value="UDG"/>
<!--Default distribution model used when none is specified -->
<defaultDistributionModel value="Random"/>
<!--Default interference model used when none is specified -->
<defaultInterferenceModel value="NoInterference"/>
<!--Default mobility model used when none is specified -->
<defaultMobilityModel value="NoMobility"/>
<!--Default reliability model used when none is specified -->
<defaultReliabilityModel value="ReliableDelivery"/>
<!--Default node implementation used when none is specified -->
<defaultNodeImplementation value="DummyNode"/>
<!--*********************************************************************** -->
<!-- Node storage, position transformation -->
<!--*********************************************************************** -->
<!--Transformation implementation for 2D. (This is used to translate between
the logic positions used by the simulation to the 2D coordinate system used
by the GUI to display the graph) -->
<guiPositionTransformation2D
value="sinalgo.gui.transformation.Transformation2D"/>
<!--Transformation implementation for 3D. (This is used to translate between
the logic positions used by the simulation to the 2D coordinate system used
by the GUI to display the graph) -->
<guiPositionTransformation3D
value="sinalgo.gui.transformation.Transformation3D"/>
<!--Node collection implementation for 2D. -->
<nodeCollection2D
value="sinalgo.runtime.nodeCollection.Geometric2DNodeCollection"/>
<!--Node collection implementation for 3D. -->
<nodeCollection3D
value="sinalgo.runtime.nodeCollection.Geometric3DNodeCollection"/>
<!--*********************************************************************** -->
<!-- Diverse Settings -->
<!--*********************************************************************** -->
<!--Show hints on how to further optimize the simulation when some parameters
seem not to be set optimally. -->
<showOptimizationHints value="true"/>
<!--Indicates whether the edges are drawn in the default draw implementation
for the graph. -->
<drawEdges value="true"/>
<!--Indicates whether the nodes are drawn in the default draw implementation
for the graph. -->
<drawNodes value="true"/>
<!--The number of future events that are shown in the control panel -->
<shownEventQueueSize value="10"/>
<!--The length of the arrows. This length is multiplied by the actualzoomLevel. -->
<arrowLength value="8"/>
<!--The width of the arrows. This width is multiplied by the actualzoomLevel. -->
<arrowWidth value="1"/>
<!--The dsfault value of the rounds field. -->
<defaultRoundNumber value="1"/>
<!--EPS 2 PDF command: This is the command that is used to convert an EPS
file into a PDF file. You can use the following parameters: %s is the complete
path from the root folder of the framework to the SOURCE file (the eps) %t
is the complete path from the root folder of the framework to the TARGET
file (the pdf) These placeholders are set by the framework. Example: 'epstopdf
%s') -->
<epsToPdfCommand value="epstopdf %s"/>
<!--Indicates whether the background in the ps should be white or gray.
The gray version is easier to understand (especially in 3D) but the white
one should be more useful to be imported in reports. -->
<epsDrawBackgroundWhite value="true"/>
</Framework>
<Custom>
<MessageTransmission ConstantTime="1"/>
<Node defaultSize="10"/>
<GeometricNodeCollection rMax="100"/>
<UDG rMax="100"/>
<SINR alpha="2" beta="0.7" noise="0"/>
<RandomWayPoint>
<Speed distribution="Gaussian" mean="10" variance="20"/>
<WaitingTime distribution="Poisson" lambda="10"/>
</RandomWayPoint>
<RandomDirection>
<NodeSpeed distribution="Gaussian" mean="10" variance="20"/>
<WaitingTime distribution="Poisson" lambda="10"/>
<MoveTime distribution="Uniform" min="5" max="20"/>
</RandomDirection>
<QUDG rMin="30" rMax="50" ProbabilityType="constant"
connectionProbability="0.6"/>
</Custom>
</Document>
This is the template project.
Copy this folder and rename it to start a new project. If this description
appears for a project that is not the template description then the
description has not yet been written. Please describe the project in
the description.txt stored in the project root folder of this
project.
\ No newline at end of file
This folder contains the images for the user-defined buttons.
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment