This commit is contained in:
2021-04-06 00:45:28 +02:00
commit 17fabc368e
836 changed files with 3042963 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
package org.fog.gui.core;
import java.io.Serializable;
public class ActuatorGui extends Node implements Serializable{
private static final long serialVersionUID = 4087896123649020073L;
private String name;
private String actuatorType;
public ActuatorGui(String name, String actuatorType){
super(name, "ACTUATOR");
setName(name);
setActuatorType(actuatorType);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Actuator []";
}
public String getActuatorType() {
return actuatorType;
}
public void setActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class ActuatorModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
String actuatorType;
public ActuatorModule() {
}
public ActuatorModule(String actuatorType) {
super(actuatorType, "ACTUATOR_MODULE");
setActuatorType(actuatorType);
}
public String getActuatorType() {
return actuatorType;
}
public void setActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,25 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class AppModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
public AppModule() {
}
public AppModule(String name) {
super(name, "APP_MODULE");
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,323 @@
package org.fog.gui.core;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.fog.utils.distribution.DeterministicDistribution;
import org.fog.utils.distribution.Distribution;
import org.fog.utils.distribution.NormalDistribution;
import org.fog.utils.distribution.UniformDistribution;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class Bridge {
private static Node getNode(Graph graph, String name){
for(Node node : graph.getAdjacencyList().keySet()){
if(node!=null){
if(node.getName().equals(name)){
return node;
}
}
}
return null;
}
// convert from JSON object to Graph object
public static Graph jsonToGraph(String fileName, int type){
Graph graph = new Graph();
// type 0->physical topology 1->virtual topology
if(0 == type){
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(fileName));
JSONArray nodes = (JSONArray) doc.get("nodes");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter =nodes.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String nodeType = (String) node.get("type");
String nodeName = (String) node.get("name");
if(nodeType.equalsIgnoreCase("host")){ //host
long pes = (Long) node.get("pes");
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long storage = (Long) node.get("storage");
long bw = new BigDecimal((Long)node.get("bw")).intValueExact();
int num = 1;
if (node.get("nums")!= null)
num = new BigDecimal((Long)node.get("nums")).intValueExact();
for(int n = 0; n< num; n++) {
Node hNode = new HostNode(nodeName, nodeType, pes, mips, ram, storage, bw);
graph.addNode(hNode);
}
} else if(nodeType.equals("FOG_DEVICE")){
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long upBw = new BigDecimal((Long)node.get("upBw")).intValueExact();
long downBw = new BigDecimal((Long)node.get("downBw")).intValueExact();
int level = new BigDecimal((Long)node.get("level")).intValue();
double rate = new BigDecimal((Double)node.get("ratePerMips")).doubleValue();
Node fogDevice = new FogDeviceGui(nodeName, mips, ram, upBw, downBw, level, rate);
graph.addNode(fogDevice);
} else if(nodeType.equals("SENSOR")){
String sensorType = node.get("sensorType").toString();
int distType = new BigDecimal((Long)node.get("distribution")).intValue();
Distribution distribution = null;
if(distType == Distribution.DETERMINISTIC)
distribution = new DeterministicDistribution(new BigDecimal((Double)node.get("value")).doubleValue());
else if(distType == Distribution.NORMAL){
distribution = new NormalDistribution(new BigDecimal((Double)node.get("mean")).doubleValue(),
new BigDecimal((Double)node.get("stdDev")).doubleValue());
} else if(distType == Distribution.UNIFORM){
distribution = new UniformDistribution(new BigDecimal((Double)node.get("min")).doubleValue(),
new BigDecimal((Double)node.get("max")).doubleValue());
}
System.out.println("Sensor type : "+sensorType);
Node sensor = new SensorGui(nodeName, sensorType, distribution);
graph.addNode(sensor);
} else if(nodeType.equals("ACTUATOR")){
String actuatorType = node.get("actuatorType").toString();
Node actuator = new ActuatorGui(nodeName, actuatorType);
graph.addNode(actuator);
} else { //switch
int bw = new BigDecimal((Long)node.get("bw")).intValueExact();
long iops = (Long) node.get("iops");
int upports = new BigDecimal((Long)node.get("upports")).intValueExact();
int downports = new BigDecimal((Long)node.get("downports")).intValueExact();
Node sNode = new SwitchNode(nodeName, nodeType, iops, upports, downports, bw);
graph.addNode(sNode);
}
}
JSONArray links = (JSONArray) doc.get("links");
@SuppressWarnings("unchecked")
Iterator<JSONObject> linksIter =links.iterator();
while(linksIter.hasNext()){
JSONObject link = linksIter.next();
String src = (String) link.get("source");
String dst = (String) link.get("destination");
double lat = (Double) link.get("latency");
Node source = (Node) getNode(graph, src);
Node target = (Node) getNode(graph, dst);
if(source!=null && target!=null){
System.out.println("Adding edge between "+source.getName()+" & "+target.getName());
Edge edge = new Edge(target, lat);
graph.addEdge(source, edge);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if(1 == type){
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(fileName));
JSONArray nodes = (JSONArray) doc.get("nodes");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter = nodes.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String nodeType = (String) node.get("type");
String nodeName = (String) node.get("name");
int pes = new BigDecimal((Long)node.get("pes")).intValueExact();
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long size = (Long) node.get("size");
Node vmNode = new VmNode(nodeName, nodeType, size, pes, mips, ram);
graph.addNode(vmNode);
}
JSONArray links = (JSONArray) doc.get("links");
@SuppressWarnings("unchecked")
Iterator<JSONObject> linksIter = links.iterator();
while(linksIter.hasNext()){
JSONObject link = linksIter.next();
String name = (String) link.get("name");
String src = (String) link.get("source");
String dst = (String) link.get("destination");
Object reqBw = link.get("bandwidth");
long bw = 0;
if(reqBw != null)
bw = (Long) reqBw;
Node source = getNode(graph, src);
Node target = getNode(graph, dst);
Edge edge = new Edge(target, name, bw);
graph.addEdge(source, edge);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
System.out.println("############################");
System.out.println(graph.getAdjacencyList());
System.out.println("############################");
return graph;
}
// convert from Graph object to JSON object
@SuppressWarnings("unchecked")
public static String graphToJson(Graph graph){
System.out.println();
System.out.println("****************************");
System.out.println(graph.getAdjacencyList());
System.out.println("****************************");
if(graph.getAdjacencyList().size() < 1){
return "Graph is Empty";
}
Map<Node, List<Node>> edgeList = new HashMap<Node, List<Node>>();
JSONObject topo = new JSONObject();
JSONArray nodes = new JSONArray();
JSONArray links = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.getAdjacencyList().entrySet()) {
Node srcNode = entry.getKey();
// add node
JSONObject jobj = new JSONObject();
switch(srcNode.getType()){
case "ACTUATOR":
ActuatorGui actuator = (ActuatorGui)srcNode;
jobj.put("name", actuator.getName());
jobj.put("type", actuator.getType());
jobj.put("actuatorType", actuator.getActuatorType());
break;
case "SENSOR":
SensorGui sensor = (SensorGui)srcNode;
jobj.put("name", sensor.getName());
jobj.put("sensorType", sensor.getSensorType());
jobj.put("type", sensor.getType());
jobj.put("distribution", sensor.getDistributionType());
if(sensor.getDistributionType()==Distribution.DETERMINISTIC)
jobj.put("value", ((DeterministicDistribution)sensor.getDistribution()).getValue());
else if(sensor.getDistributionType()==Distribution.NORMAL){
jobj.put("mean", ((NormalDistribution)sensor.getDistribution()).getMean());
jobj.put("stdDev", ((NormalDistribution)sensor.getDistribution()).getStdDev());
} else if(sensor.getDistributionType()==Distribution.UNIFORM){
jobj.put("min", ((UniformDistribution)sensor.getDistribution()).getMin());
jobj.put("max", ((UniformDistribution)sensor.getDistribution()).getMax());
}
break;
case "FOG_DEVICE":
FogDeviceGui fogDevice = (FogDeviceGui)srcNode;
jobj.put("name", fogDevice.getName());
jobj.put("type", fogDevice.getType());
jobj.put("mips", fogDevice.getMips());
jobj.put("ram", fogDevice.getRam());
jobj.put("upBw", fogDevice.getUpBw());
jobj.put("downBw", fogDevice.getDownBw());
jobj.put("level", fogDevice.getLevel());
jobj.put("ratePerMips", fogDevice.getRatePerMips());
break;
case "host":
HostNode hNode = (HostNode)srcNode;
jobj.put("name", hNode.getName());
jobj.put("type", hNode.getType());
jobj.put("pes", hNode.getPes());
jobj.put("mips", hNode.getMips());
jobj.put("ram", hNode.getRam());
jobj.put("storage", hNode.getStorage());
jobj.put("bw", hNode.getBw());
break;
case "core":
case "edge":
SwitchNode sNode = (SwitchNode)srcNode;
jobj.put("name", sNode.getName());
jobj.put("type", sNode.getType());
jobj.put("iops", sNode.getIops());
jobj.put("upports", sNode.getDownports());
jobj.put("downports", sNode.getDownports());
jobj.put("bw", sNode.getBw());
break;
case "vm":
VmNode vNode = (VmNode)srcNode;
jobj.put("name", vNode.getName());
jobj.put("type", vNode.getType());
jobj.put("size", vNode.getSize());
jobj.put("pes", vNode.getPes());
jobj.put("mips", vNode.getMips());
jobj.put("ram", vNode.getRam());
break;
}
nodes.add(jobj);
// add edge
for (Edge edge : entry.getValue()) {
Node destNode = edge.getNode();
// check if edge exist (dest->src)
if (edgeList.containsKey(destNode) && edgeList.get(destNode).contains(srcNode)) {
continue;
}
JSONObject jobj2 = new JSONObject();
jobj2.put("source", srcNode.getName());
jobj2.put("destination", destNode.getName());
if("host"==destNode.getType() || "core"==destNode.getType() || "edge"==destNode.getType() ||
"FOG_DEVICE"==destNode.getType() || "SENSOR"==destNode.getType() || "ACTUATOR"==destNode.getType()){
jobj2.put("latency", edge.getLatency());
}else if("vm"==destNode.getName()){
if(edge.getBandwidth()>0){
jobj2.put("bandwidth", edge.getBandwidth());
}
}
links.add(jobj2);
// add exist edge to the edgeList
if (edgeList.containsKey(entry.getKey())) {
edgeList.get(entry.getKey()).add(edge.getNode());
} else {
List<Node> ns = new ArrayList<Node>();
ns.add(edge.getNode());
edgeList.put(entry.getKey(), ns);
}
}
}
topo.put("nodes", nodes);
topo.put("links", links);
StringWriter out = new StringWriter();
String jsonText = "";
try {
topo.writeJSONString(out);
jsonText = out.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(jsonText);
return jsonText;
}
}

View File

@@ -0,0 +1,36 @@
package org.fog.gui.core;
public class Coordinates {
private int x;
private int y;
public Coordinates() {
this.x = 0;
this.y = 0;
}
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Coordinates [abscissa=" + x + ", ordinate=" + y + "]";
}
}

View File

@@ -0,0 +1,93 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The model that represents an edge with two vertexes, for physical link and virtual edge.
*
*/
public class Edge implements Serializable {
private static final long serialVersionUID = -356975278987708987L;
private Node dest = null;
private double latency = 0.0;
private String name = "";
private long bandwidth = 0;
/**
* Constructor.
*
* @param node the node that belongs to the edge.
*/
public Edge(Node to) {
this.dest = to;
}
/** physical topology link */
public Edge(Node to, double latency) {
this.dest = to;
this.latency = latency;
}
/** virtual virtual edge */
public Edge(Node to, String name, long bw) {
this.dest = to;
this.name = name;
this.bandwidth = bw;
}
/** copy edge */
public Edge(Node to, Map<String, Object> info){
this.dest = to;
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
public Node getNode() {
return dest;
}
public long getBandwidth() {
return bandwidth;
}
public double getLatency() {
return latency;
}
public Map<String, Object> getInfo() {
Map<String, Object> info = new HashMap<String, Object>();
info.put("name", this.name);
info.put("bandwidth",this.bandwidth);
info.put("latency", this.latency);
return info;
}
public void setInfo(Map<String, Object> info){
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
@Override
public String toString() {
return "Edge [dest=" + dest + "]";
}
}

View File

@@ -0,0 +1,94 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class FogDeviceGui extends Node {
private static final long serialVersionUID = -8635044061126993668L;
private int level;
private String name;
private long mips;
private int ram;
private long upBw;
private long downBw;
private double ratePerMips;
public FogDeviceGui() {
}
public FogDeviceGui(String name, long mips, int ram, long upBw, long downBw, int level, double rate) {
super(name, "FOG_DEVICE");
this.name = name;
this.mips = mips;
this.ram = ram;
this.upBw = upBw;
this.downBw = downBw;
this.level = level;
this.ratePerMips = rate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getMips() {
return mips;
}
public void setMips(long mips) {
this.mips = mips;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public long getUpBw() {
return upBw;
}
public void setUpBw(long upBw) {
this.upBw = upBw;
}
public long getDownBw() {
return downBw;
}
public void setDownBw(long downBw) {
this.downBw = downBw;
}
@Override
public String toString() {
return "FogDevice [mips=" + mips + " ram=" + ram + " upBw=" + upBw + " downBw=" + downBw + "]";
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public double getRatePerMips() {
return ratePerMips;
}
public void setRatePerMips(double ratePerMips) {
this.ratePerMips = ratePerMips;
}
}

View File

@@ -0,0 +1,153 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A graph model. Normally a model should not have any logic, but in this case we implement logic to manipulate the
* adjacencyList like reorganizing, adding nodes, removing nodes, e.g
*
*/
public class Graph implements Serializable {
private static final long serialVersionUID = 745864022429447529L;
private Map<Node, List<Edge>> adjacencyList;
public Graph() {
// when creating a new graph ensure that a new adjacencyList is created
adjacencyList = new HashMap<Node, List<Edge>>();
}
public Graph(Map<Node, List<Edge>> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public void setAdjacencyList(Map<Node, List<Edge>> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public Map<Node, List<Edge>> getAdjacencyList() {
return adjacencyList;
}
/** Adds a given edge to the adjacency list. If the base node is not yet part of the adjacency list a new entry is added */
public void addEdge(Node key, Edge value) {
if (adjacencyList.containsKey(key)) {
if (adjacencyList.get(key) == null) {
adjacencyList.put(key, new ArrayList<Edge>());
}
// TODO: perhaps check if a value may not be added twice.
// add edge if not null
if (value != null) {
adjacencyList.get(key).add(value);
}
} else {
List<Edge> edges = new ArrayList<Edge>();
// add edge if not null
if (value != null) {
edges.add(value);
}
adjacencyList.put(key, edges);
}
// do bidirectional adding. Ugly duplicated code.
// only execute when there is an edge defined.
/*if (value != null) {
Edge reverseEdge = new Edge(key, value.getInfo());
if (adjacencyList.containsKey(value.getNode())) {
if (adjacencyList.get(value.getNode()) == null) {
adjacencyList.put(value.getNode(), new ArrayList<Edge>());
}
// TODO: perhaps check if a value may not be added twice.
// add edge if not null
if (reverseEdge != null) {
adjacencyList.get(value.getNode()).add(reverseEdge);
}
} else {
List<Edge> edges = new ArrayList<Edge>();
// add edge if not null
if (reverseEdge != null) {
edges.add(reverseEdge);
}
adjacencyList.put(value.getNode(), edges);
}
}*/
}
/** Simply adds a new node, without setting any edges */
public void addNode(Node node) {
addEdge(node, null);
}
public void removeEdge(Node key, Edge value) {
if (!adjacencyList.containsKey(key)) {
throw new IllegalArgumentException("The adjacency list does not contain a node for the given key: " + key);
}
List<Edge> edges = adjacencyList.get(key);
if (!edges.contains(value)) {
throw new IllegalArgumentException("The list of edges does not contain the given edge to remove: " + value);
}
edges.remove(value);
// remove bidirectional
List<Edge> reverseEdges = adjacencyList.get(value.getNode());
List<Edge> toRemove = new ArrayList<Edge>();
for (Edge edge : reverseEdges) {
if (edge.getNode().equals(key)) {
toRemove.add(edge);
}
}
//normally only one element
reverseEdges.removeAll(toRemove);
}
/** Deletes a node */
public void removeNode(Node key) {
if (!adjacencyList.containsKey(key)) {
throw new IllegalArgumentException("The adjacency list does not contain a node for the given key: " + key);
}
adjacencyList.remove(key);
// clean up all edges
for (Entry<Node, List<Edge>> entry : adjacencyList.entrySet()) {
List<Edge> toRemove = new ArrayList<Edge>();
for (Edge edge : entry.getValue()) {
if (edge.getNode().equals(key)) {
toRemove.add(edge);
}
}
entry.getValue().removeAll(toRemove);
}
}
public void clearGraph(){
adjacencyList.clear();
}
public String toJsonString(){
String jsonText = Bridge.graphToJson(this);
return jsonText;
}
@Override
public String toString() {
return "Graph [adjacencyList=" + adjacencyList + "]";
}
}

View File

@@ -0,0 +1,378 @@
package org.fog.gui.core;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.fog.utils.FogUtils;
/** Panel that displays a graph */
public class GraphView extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel canvas;
private Graph graph;
private Image imgHost;
private Image imgSensor;
private Image imgSwitch;
private Image imgAppModule;
private Image imgActuator;
private Image imgSensorModule;
private Image imgActuatorModule;
public GraphView(final Graph graph) {
this.graph = graph;
imgHost = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/host.png"));
imgSwitch = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/disk.png"));
imgAppModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/module.png"));
imgSensor = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/sensor.png"));
imgActuator = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/actuator.png"));
imgSensorModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/sensorModule.png"));
imgActuatorModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/actuatorModule.png"));
initComponents();
}
private Map<Node, List<Node>> createChildrenMap(){
Map<Node, List<Node>> childrenMap = new HashMap<Node, List<Node>>();
for(Node node : graph.getAdjacencyList().keySet()){
if(node.getType().equals("FOG_DEVICE") && !childrenMap.containsKey(node))
childrenMap.put(node, new ArrayList<Node>());
List<Edge> edgeList = graph.getAdjacencyList().get(node);
for(Edge edge : edgeList){
Node neighbour = edge.getNode();
if(node.getType().equals("SENSOR") || node.getType().equals("ACTUATOR")){
if(!childrenMap.containsKey(neighbour)){
childrenMap.put(neighbour, new ArrayList<Node>());
}
childrenMap.get(neighbour).add(node);
} else if(neighbour.getType().equals("SENSOR") || neighbour.getType().equals("ACTUATOR")){
if(!childrenMap.containsKey(node)){
childrenMap.put(node, new ArrayList<Node>());
}
childrenMap.get(node).add(neighbour);
}else {
Node child = (((FogDeviceGui)node).getLevel() > ((FogDeviceGui)neighbour).getLevel())?node:neighbour;
Node parent = (((FogDeviceGui)node).getLevel() < ((FogDeviceGui)neighbour).getLevel())?node:neighbour;
if(!childrenMap.containsKey(parent)){
childrenMap.put(parent, new ArrayList<Node>());
}
childrenMap.get(parent).add(child);
}
}
}
return childrenMap;
}
@SuppressWarnings("serial")
private void initComponents() {
canvas = new JPanel() {
@Override
public void paint(Graphics g) {
if (graph.getAdjacencyList() == null) {
return;
}
Map<Node, Coordinates> coordForNodes = new HashMap<Node, Coordinates>();
/*int offsetX = canvas.getWidth() / 2;
int offsetY = canvas.getHeight() / 2;*/
System.out.println("sys:"+canvas.getWidth() + ":" + canvas.getHeight());
int height = 40;
/*double angle = 2 * Math.PI / graph.getAdjacencyList().keySet().size();
int radius = offsetY / 2 - 20;*/
FontMetrics f = g.getFontMetrics();
int nodeHeight = Math.max(height, f.getHeight());
int nodeWidth = nodeHeight;
int maxLevel=-1, minLevel=FogUtils.MAX;
Map<Integer, List<Node>> levelMap = new HashMap<Integer, List<Node>>();
List<Node> endpoints = new ArrayList<Node>();
for (Node node : graph.getAdjacencyList().keySet()) {
if(node.getType().equals("FOG_DEVICE")){
int level = ((FogDeviceGui)node).getLevel();
if(!levelMap.containsKey(level))
levelMap.put(level, new ArrayList<Node>());
levelMap.get(level).add(node);
if(level > maxLevel)
maxLevel = level;
if(level < minLevel)
minLevel = level;
} else if(node.getType().equals("SENSOR") || node.getType().equals("ACTUATOR")){
endpoints.add(node);
}
}
double yDist = canvas.getHeight()/(maxLevel-minLevel+3);
System.out.println("===================\n================\n=============");
Map<Integer, List<PlaceHolder>> levelToPlaceHolderMap = new HashMap<Integer, List<PlaceHolder>>();
int k=1;
for(int i=minLevel;i<=maxLevel;i++, k++){
double xDist = canvas.getWidth()/(levelMap.get(i).size()+1);
for(int j=1;j<=levelMap.get(i).size();j++){
int x = (int)xDist*j;
int y = (int)yDist*k;
if(!levelToPlaceHolderMap.containsKey(i))
levelToPlaceHolderMap.put(i, new ArrayList<PlaceHolder>());
levelToPlaceHolderMap.get(i).add(new PlaceHolder(x, y));
//coordForNodes.put(node, new Coordinates(x, y));
//node.setCoordinate(new Coordinates(x, y));
}
}
List<PlaceHolder> endpointPlaceHolders = new ArrayList<PlaceHolder>();
double xDist = canvas.getWidth()/(endpoints.size()+1);
for(int i=0;i<endpoints.size();i++){
Node node = endpoints.get(i);
int x = (int)xDist*(i+1);
int y = (int)yDist*k;
endpointPlaceHolders.add(new PlaceHolder(x, y));
coordForNodes.put(node, new Coordinates(x, y));
node.setCoordinate(new Coordinates(x, y));
}
for (Node node : graph.getAdjacencyList().keySet()) {
if(node.getType().equals("FOG_DEVICE")||node.getType().equals("SENSOR")||node.getType().equals("ACTUATOR"))
continue;
// calculate coordinates
/*int x = Double.valueOf(offsetX + Math.cos(i * angle) * radius).intValue();
int y = Double.valueOf(offsetY + Math.sin(i * angle) * radius).intValue();*/
//coordForNodes.put(node, new Coordinates(x, y));
//node.setCoordinate(new Coordinates(x, y));
}
coordForNodes = getCoordForNodes(levelToPlaceHolderMap, endpointPlaceHolders, levelMap, endpoints, minLevel, maxLevel);
System.out.println("COORD MAP"+coordForNodes);
Map<Node, List<Node>> drawnList = new HashMap<Node, List<Node>>();
for (Entry<Node, Coordinates> entry : coordForNodes.entrySet()) {
// first paint a single node for testing.
g.setColor(Color.black);
// int nodeWidth = Math.max(width, f.stringWidth(entry.getKey().getNodeText()) + width / 2);
Coordinates wrapper = entry.getValue();
String nodeName = entry.getKey().getName();
switch(entry.getKey().getType()){
case "host":
g.drawImage(imgHost, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
break;
case "APP_MODULE":
g.drawImage(imgAppModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "core":
case "edge":
g.drawImage(imgSwitch, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
break;
case "FOG_DEVICE":
g.drawImage(imgHost, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "SENSOR":
g.drawImage(imgSensor, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "ACTUATOR":
g.drawImage(imgActuator, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "SENSOR_MODULE":
g.drawImage(imgSensorModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "ACTUATOR_MODULE":
g.drawImage(imgActuatorModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
}
//g.setColor(Color.white);
//g.fillOval(wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight);
//g.setColor(Color.black);
//g.drawOval(wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight);
//System.out.println((wrapper.getX())+" "+(wrapper.getY()));
//g.drawString(entry.getKey().getName(), wrapper.getX() - f.stringWidth(entry.getKey().getName()) / 2, wrapper.getY() + f.getHeight() / 2);
}
// draw edges first
// TODO: we draw one edge two times at the moment because we have an undirected graph. But this
// shouldn`t matter because we have the same edge costs and no one will see in. Perhaps refactor later.
for (Entry<Node, List<Edge>> entry : graph.getAdjacencyList().entrySet()) {
Coordinates startNode = coordForNodes.get(entry.getKey());
System.out.println("Start Node : "+entry.getKey().getName());
for (Edge edge : entry.getValue()) {
/*
// if other direction was drawn already continue
if (drawnList.containsKey(edge.getNode()) && drawnList.get(edge.getNode()).contains(entry.getKey())) {
continue;
}
*/
Coordinates targetNode = coordForNodes.get(edge.getNode());
System.out.println("Target Node : "+edge.getNode().getName());
g.setColor(Color.RED);
g.drawLine(startNode.getX(), startNode.getY(), targetNode.getX(), targetNode.getY());
//drawArrow(g, startNode.getX(), startNode.getY(), targetNode.getX(), targetNode.getY());
// add drawn edges to the drawnList
if (drawnList.containsKey(entry.getKey())) {
drawnList.get(entry.getKey()).add(edge.getNode());
} else {
List<Node> nodes = new ArrayList<Node>();
nodes.add(edge.getNode());
drawnList.put(entry.getKey(), nodes);
}
/*int labelX = (startNode.getX() - targetNode.getX()) / 2;
int labelY = (startNode.getY() - targetNode.getY()) / 2;
labelX *= -1;
labelY *= -1;
labelX += startNode.getX();
labelY += startNode.getY();
*/
//g.setColor(Color.BLACK);
//g.drawString(String.valueOf(edge.getInfo()), labelX - f.stringWidth(String.valueOf(edge.getInfo())) / 2, labelY + f.getHeight() / 2);
}
}
}
};
JScrollPane scrollPane = new JScrollPane(canvas);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(scrollPane);
}
protected Map<Node, Coordinates> getCoordForNodes(
Map<Integer, List<PlaceHolder>> levelToPlaceHolderMap,
List<PlaceHolder> endpointPlaceHolders,
Map<Integer, List<Node>> levelMap, List<Node> endpoints, int minLevel, int maxLevel) {
// TODO Auto-generated method stub
Map<Node, Coordinates> coordForNodesMap = new HashMap<Node, Coordinates>();
Map<Node, List<Node>> childrenMap = createChildrenMap();
for(Node node : graph.getAdjacencyList().keySet())node.setPlaced(false);
for(Node node : endpoints)node.setPlaced(false);
if(maxLevel < 0)
return new HashMap<Node, Coordinates>();
int j=0;
for(PlaceHolder placeHolder : levelToPlaceHolderMap.get(minLevel)){
Node node = levelMap.get(minLevel).get(j);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
j++;
}
for(int level = minLevel+1;level <= maxLevel; level++){
List<PlaceHolder> upperLevelNodes = levelToPlaceHolderMap.get(level-1);
List<Node> nodes = levelMap.get(level);
int i=0;
for(PlaceHolder parentPH : upperLevelNodes){
List<Node> children = childrenMap.get(parentPH.getNode());
for(Node child : children){
PlaceHolder childPlaceHolder = levelToPlaceHolderMap.get(level).get(i);
childPlaceHolder.setOccupied(true);
childPlaceHolder.setNode(child);
child.setCoordinate(childPlaceHolder.getCoordinates());
coordForNodesMap.put(child, child.getCoordinate());
child.setPlaced(true);
i++;
}
}
for(Node node : nodes){
if(!node.isPlaced()){
PlaceHolder placeHolder = levelToPlaceHolderMap.get(level).get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
i++;
}
}
}
int i=0;
for(PlaceHolder parentPH : levelToPlaceHolderMap.get(maxLevel)){
List<Node>children = childrenMap.get(parentPH.getNode());
for(Node child : children){
PlaceHolder placeHolder = endpointPlaceHolders.get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(child);
child.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(child, child.getCoordinate());
child.setPlaced(true);
i++;
}
}
for(Node node : endpoints){
if(!node.isPlaced()){
PlaceHolder placeHolder = endpointPlaceHolders.get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
i++;
}
}
return coordForNodesMap;
}
/*private void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
Graphics2D g = (Graphics2D) g1.create();
System.out.println("Drawing arrow");
double dx = x2 - x1, dy = y2 - y1;
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);
AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
at.concatenate(AffineTransform.getRotateInstance(angle));
g.transform(at);
// Draw horizontal arrow starting in (0, 0)
QuadCurve2D.Double curve = new QuadCurve2D.Double(0,0,50+0.5*len,50,len,0);
g.draw(curve);
g.fillPolygon(new int[] { len, len - ARR_SIZE, len - ARR_SIZE, len }, new int[] { 0, -ARR_SIZE, ARR_SIZE, 0 }, 4);
}*/
public void setGraph(Graph newGraph){
this.graph = newGraph;
}
}

View File

@@ -0,0 +1,74 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class HostNode extends Node {
private static final long serialVersionUID = -8635044061126993668L;
private long pes;
private long mips;
private int ram;
private long storage;
private long bw;
public HostNode() {
}
public HostNode(String name, String type, long pes, long mips, int ram, long storage, long bw) {
super(name, type);
this.pes = pes;
this.mips = mips;
this.ram = ram;
this.storage = storage;
this.bw = bw;
}
public void setPes(long pes) {
this.pes = pes;
}
public long getPes() {
return pes;
}
public void setMips(long mips) {
this.mips = mips;
}
public long getMips() {
return mips;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getRam() {
return ram;
}
public void setStorage(long storage) {
this.storage = storage;
}
public long getStorage() {
return storage;
}
public void setBw(long bw) {
this.bw = bw;
}
public long getBw() {
return bw;
}
@Override
public String toString() {
return "Node [pes=" + pes + " mips=" + mips + " ram=" + ram + " storage=" + storage + " bw=" + bw + "]";
}
}

View File

@@ -0,0 +1,97 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The model that represents an edge with two vertexes, for physical link and virtual edge.
*
*/
public class Link extends Edge implements Serializable {
private static final long serialVersionUID = -356975278987708987L;
private Node dest = null;
private double latency = 0.0;
private String name = "";
private long bandwidth = 0;
/**
* Constructor.
*
* @param node the node that belongs to the edge.
*/
public Link(Node to) {
super(to);
this.dest = to;
}
/** physical topology link */
public Link(Node to, double latency) {
super(to, latency);
this.dest = to;
this.latency = latency;
}
/** virtual virtual edge */
public Link(Node to, String name, long bw) {
super(to, name, bw);
this.dest = to;
this.name = name;
this.bandwidth = bw;
}
/** copy edge */
public Link(Node to, Map<String, Object> info){
super(to, info);
this.dest = to;
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
public Node getNode() {
return dest;
}
public long getBandwidth() {
return bandwidth;
}
public double getLatency() {
return latency;
}
public Map<String, Object> getInfo() {
Map<String, Object> info = new HashMap<String, Object>();
info.put("name", this.name);
info.put("bandwidth",this.bandwidth);
info.put("latency", this.latency);
return info;
}
public void setInfo(Map<String, Object> info){
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
@Override
public String toString() {
return "Edge [dest=" + dest + "]";
}
}

View File

@@ -0,0 +1,92 @@
package org.fog.gui.core;
import java.io.Serializable;
/**
* The model that represents node (host or vm) for the graph.
*
*/
public class Node implements Serializable {
private static final long serialVersionUID = 823544330517091616L;
private Coordinates coord;
private String name;
private String type;
private boolean isPlaced;
public Node() {
setPlaced(false);
}
public Node(String name, String type) {
this.name = name;
this.type = type;
setPlaced(false);
coord = new Coordinates();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setCoordinate(Coordinates coord) {
this.coord.setX(coord.getX());
this.coord.setY(coord.getY());
}
public Coordinates getCoordinate() {
return coord;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Node [name=" + name + " type=" + type + "]";
}
public boolean isPlaced() {
return isPlaced;
}
public void setPlaced(boolean isPlaced) {
this.isPlaced = isPlaced;
}
}

View File

@@ -0,0 +1,27 @@
package org.fog.gui.core;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
/** A cell renderer for the JComboBox when displaying a node object */
@SuppressWarnings("rawtypes")
public class NodeCellRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 6021697923766790099L;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Node node = (Node) value;
JLabel label = new JLabel();
if (node != null && node.getName() != null) {
label.setText(node.getName());
}
return label;
}
}

View File

@@ -0,0 +1,47 @@
package org.fog.gui.core;
public class PlaceHolder {
protected Coordinates coordinates;
protected boolean isOccupied;
protected Node node;
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public boolean isOccupied() {
return isOccupied;
}
public void setOccupied(boolean isOccupied) {
this.isOccupied = isOccupied;
}
public PlaceHolder(Coordinates coordinates){
setCoordinates(coordinates);
setOccupied(false);
}
public PlaceHolder(){
setCoordinates(new Coordinates());
setOccupied(false);
}
public PlaceHolder(int x, int y){
setCoordinates(new Coordinates(x, y));
setOccupied(false);
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
}

View File

@@ -0,0 +1,82 @@
package org.fog.gui.core;
import java.io.Serializable;
import org.fog.utils.distribution.DeterministicDistribution;
import org.fog.utils.distribution.Distribution;
import org.fog.utils.distribution.NormalDistribution;
import org.fog.utils.distribution.UniformDistribution;
public class SensorGui extends Node implements Serializable{
private static final long serialVersionUID = 4087896123649020073L;
private String name;
private String sensorType;
private Distribution distribution;
public SensorGui(String name, String type, Distribution distribution){
super(name, "SENSOR");
setName(name);
setSensorType(type);
setDistribution(distribution);
}
public SensorGui(String name, String sensorType, String selectedItem, double normalMean_,
double normalStdDev_, double uniformLow_, double uniformUp_,
double deterministicVal_) {
super(name, "SENSOR");
setName(name);
setSensorType(sensorType);
if(normalMean_ != -1){
setDistribution(new NormalDistribution(normalMean_, normalStdDev_));
}else if(uniformLow_ != -1){
setDistribution(new UniformDistribution(uniformLow_, uniformUp_));
}else if(deterministicVal_ != -1){
setDistribution(new DeterministicDistribution(deterministicVal_));
}
}
public int getDistributionType(){
return distribution.getDistributionType();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Distribution getDistribution() {
return distribution;
}
public void setDistribution(Distribution distribution) {
this.distribution = distribution;
}
@Override
public String toString() {
if(distribution instanceof NormalDistribution)
return "Sensor [dist=1 mean=" + ((NormalDistribution)distribution).getMean() + " stdDev=" + ((NormalDistribution)distribution).getStdDev() + "]";
else if(distribution instanceof UniformDistribution)
return "Sensor [dist=2 min=" + ((UniformDistribution)distribution).getMin() + " max=" + ((UniformDistribution)distribution).getMax() + "]";
else if(distribution instanceof DeterministicDistribution)
return "Sensor [dist=3 value=" + ((DeterministicDistribution)distribution).getValue() + "]";
else
return "";
}
public String getSensorType() {
return sensorType;
}
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class SensorModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
String sensorType;
public SensorModule() {
}
public SensorModule(String sensorType) {
super(sensorType, "SENSOR_MODULE");
setSensorType(sensorType);
}
public String getSensorType() {
return sensorType;
}
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,194 @@
package org.fog.gui.core;
import javax.swing.*;
import javax.swing.SpringLayout;
import java.awt.*;
/**
* A 1.4 file that provides utility methods for
* creating form- or grid-style layouts with SpringLayout.
* These utilities are used by several programs, such as
* SpringBox and SpringCompactGrid.
*/
public class SpringUtilities {
/**
* A debugging utility that prints to stdout the component's
* minimum, preferred, and maximum sizes.
*/
public static void printSizes(Component c) {
System.out.println("minimumSize = " + c.getMinimumSize());
System.out.println("preferredSize = " + c.getPreferredSize());
System.out.println("maximumSize = " + c.getMaximumSize());
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>parent</code> in
* a grid. Each component is as big as the maximum
* preferred width and height of the components.
* The parent is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeGrid must use SpringLayout.");
return;
}
Spring xPadSpring = Spring.constant(xPad);
Spring yPadSpring = Spring.constant(yPad);
Spring initialXSpring = Spring.constant(initialX);
Spring initialYSpring = Spring.constant(initialY);
int max = rows * cols;
//Calculate Springs that are the max of the width/height so that all
//cells have the same size.
Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
getWidth();
Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
getHeight();
for (int i = 1; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
}
//Apply the new width/height Spring. This forces all the
//components to have the same size.
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
cons.setWidth(maxWidthSpring);
cons.setHeight(maxHeightSpring);
}
//Then adjust the x/y constraints of all the cells so that they
//are aligned in a grid.
SpringLayout.Constraints lastCons = null;
SpringLayout.Constraints lastRowCons = null;
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
if (i % cols == 0) { //start of new row
lastRowCons = lastCons;
cons.setX(initialXSpring);
} else { //x position depends on previous component
cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
xPadSpring));
}
if (i / cols == 0) { //first row
cons.setY(initialYSpring);
} else { //y position depends on previous row
cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
yPadSpring));
}
lastCons = cons;
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH,
Spring.sum(
Spring.constant(yPad),
lastCons.getConstraint(SpringLayout.SOUTH)));
pCons.setConstraint(SpringLayout.EAST,
Spring.sum(
Spring.constant(xPad),
lastCons.getConstraint(SpringLayout.EAST)));
}
/* Used by makeCompactGrid. */
private static SpringLayout.Constraints getConstraintsForCell(
int row, int col,
Container parent,
int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>parent</code> in
* a grid. Each component in a column is as wide as the maximum
* preferred width of the components in that column;
* height is similarly determined for each row.
* The parent is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
}

View File

@@ -0,0 +1,62 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class SwitchNode extends Node {
private static final long serialVersionUID = 804858850147477656L;
private long iops;
private int upports;
private int downports;
private long bw;
public SwitchNode() {
}
public SwitchNode(String name, String type, long iops, int upports, int downports, long bw) {
super(name, type);
this.iops = iops;
this.upports = upports;
this.downports = downports;
this.bw = bw;
}
public void setIops(long iops) {
this.iops = iops;
}
public long getIops() {
return iops;
}
public void setUpports(int upports) {
this.upports = upports;
}
public int getUpports() {
return upports;
}
public void setDownports(int downports) {
this.downports = downports;
}
public int getDownports() {
return downports;
}
public void setBw(long bw) {
this.bw = bw;
}
public long getBw() {
return bw;
}
@Override
public String toString() {
return "Node [iops=" + iops + " upports=" + upports + " downports=" + downports + " bw=" + bw + "]";
}
}

View File

@@ -0,0 +1,62 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class VmNode extends Node {
private static final long serialVersionUID = 804858850147477656L;
private long size;
private int pes;
private long mips;
private int ram;
public VmNode() {
}
public VmNode(String name, String type, long size, int pes, long mips, int ram) {
super(name, type);
this.size = size;
this.pes = pes;
this.mips = mips;
this.ram = ram;
}
public void setSize(int size) {
this.size = size;
}
public long getSize() {
return size;
}
public void setPes(int pes) {
this.pes = pes;
}
public int getPes() {
return pes;
}
public void setMips(long mips) {
this.mips = mips;
}
public long getMips() {
return mips;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getRam() {
return ram;
}
@Override
public String toString() {
return "Node [size=" + size + " pes=" + pes + " mips=" + mips + " ram=" + ram + "]";
}
}

View File

@@ -0,0 +1,59 @@
package org.fog.gui.dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
@SuppressWarnings("serial")
class About extends JDialog {
public About() {
initUI();
}
public final void initUI() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0, 10)));
ImageIcon icon = new ImageIcon("src/logo.png");
JLabel label = new JLabel(icon);
label.setAlignmentX(0.5f);
add(label);
add(Box.createRigidArea(new Dimension(0, 10)));
JLabel name = new JLabel("CloudSim SDN, 1.00");
name.setFont(new Font("Serif", Font.BOLD, 15));
name.setAlignmentX(0.5f);
add(name);
add(Box.createRigidArea(new Dimension(0, 50)));
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
close.setAlignmentX(0.5f);
add(close);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("About CloudSim");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(350, 300);
}
}

View File

@@ -0,0 +1,136 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.ActuatorGui;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddActuator extends JDialog {
private static final long serialVersionUID = -511667786177319577L;
private final Graph graph;
private JTextField actuatorName;
private JTextField actuatorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddActuator(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Actuator");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (actuatorName.getText() == null || actuatorName.getText().length() < 1) {
prompt("Please type Actuator name", "Error");
} else {
if(!catchedError){
ActuatorGui actuator = new ActuatorGui(actuatorName.getText(),
actuatorType.getText().toString());
graph.addNode(actuator);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
actuatorName = new JTextField();
lName.setLabelFor(actuatorName);
springPanel.add(actuatorName);
JLabel lType = new JLabel("Actuator Type : ");
springPanel.add(lType);
actuatorType = new JTextField();
lName.setLabelFor(actuatorType);
springPanel.add(actuatorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
2, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddActuator.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.ActuatorModule;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddActuatorModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField actuatorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddActuatorModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (actuatorType.getText() == null || actuatorType.getText().length() < 1) {
prompt("Please enter Actuator Type", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new ActuatorModule(actuatorType.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Sensor Type: ");
springPanel.add(lName);
actuatorType = new JTextField();
lName.setLabelFor(actuatorType);
springPanel.add(actuatorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddActuatorModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,244 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
import org.fog.gui.core.SpringUtilities;
/** A dialog to add a new edge */
public class AddAppEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tupleType;
private JTextField tupleCpuLen;
private JTextField tupleNwLen;
public AddAppEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Application edge");
setModal(true);
setPreferredSize(new Dimension(400, 250));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel2 = new JPanel();
textAreaPanel2.setLayout(new BoxLayout(textAreaPanel2, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label("--->"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
JPanel springPanel = new JPanel(new SpringLayout());
//springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel tupleTypeLabel = new JLabel("Tuple Type : ");
springPanel.add(tupleTypeLabel);
tupleType = new JTextField();
tupleTypeLabel.setLabelFor(tupleType);
springPanel.add(tupleType);
JLabel tupleCpuLenLabel = new JLabel("Tuple CPU Len : ");
springPanel.add(tupleCpuLenLabel);
tupleCpuLen = new JTextField();
tupleCpuLenLabel.setLabelFor(tupleCpuLen);
springPanel.add(tupleCpuLen);
JLabel tupleNwLenLabel = new JLabel("Tuple NW Len : ");
springPanel.add(tupleNwLenLabel);
tupleNwLen = new JTextField();
tupleNwLenLabel.setLabelFor(tupleNwLen);
springPanel.add(tupleNwLen);
SpringUtilities.makeCompactGrid(springPanel,
3, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
inputPanelWrapper.add(springPanel);
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = "default";
long bandwidth = 0;
boolean catchedError = false;
if (tupleType.getText() == null || tupleType.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple Type", "Error");
} else if (tupleCpuLen.getText() == null || tupleCpuLen.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple CPU Length", "Error");
} else if (tupleNwLen.getText() == null || tupleNwLen.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple NW Length", "Error");
}
else {
name = ((Node)sourceNode.getSelectedItem()).getName()+"-"+((Node)sourceNode.getSelectedItem()).getName();
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, name, bandwidth);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddAppEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.AppModule;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddApplicationModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField tfName;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddApplicationModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Application Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new AppModule(tfName.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddApplicationModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,201 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.FogDeviceGui;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddFogDevice extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JLabel deviceNameLabel;
private JLabel upBwLabel;
private JLabel downBwLabel;
private JLabel mipsLabel;
private JLabel ramLabel;
private JLabel levelLabel;
private JLabel rateLabel;
private JTextField deviceName;
private JTextField upBw;
private JTextField downBw;
private JTextField mips;
private JTextField ram;
private JTextField level;
private JTextField rate;
public AddFogDevice(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Fog Device");
setModal(true);
setPreferredSize(new Dimension(350, 380));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (deviceName.getText() == null || deviceName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (upBw.getText() == null || upBw.getText().length() < 1) {
prompt("Please enter uplink BW", "Error");
} else if (downBw.getText() == null || downBw.getText().length() < 1) {
prompt("Please enter downlink BW", "Error");
} else if (mips.getText() == null || mips.getText().length() < 1) {
prompt("Please enter MIPS", "Error");
} else if (ram.getText() == null || ram.getText().length() < 1) {
prompt("Please enter RAM", "Error");
} else if (level.getText() == null || level.getText().length() < 1) {
prompt("Please enter Level", "Error");
} else if (rate.getText() == null || rate.getText().length() < 1) {
prompt("Please enter Rate", "Error");
}
long upBw_=-1, downBw_=-1, mips_=-1; int ram_=-1, level_=-1;double rate_ = -1;
try {
upBw_ = Long.parseLong(upBw.getText());
downBw_ = Long.parseLong(downBw.getText());
mips_ = Long.parseLong(mips.getText());
ram_ = Integer.parseInt(ram.getText());
level_ = Integer.parseInt(level.getText());
rate_ = Double.parseDouble(rate.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
FogDeviceGui fogDevice = new FogDeviceGui(deviceName.getText().toString(), mips_, ram_, upBw_, downBw_, level_, rate_);
graph.addNode(fogDevice);
setVisible(false);
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
//springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
deviceNameLabel = new JLabel("Name: ");
springPanel.add(deviceNameLabel);
deviceName = new JTextField();
deviceNameLabel.setLabelFor(deviceName);
springPanel.add(deviceName);
levelLabel = new JLabel("Level: ");
springPanel.add(levelLabel);
level = new JTextField();
levelLabel.setLabelFor(level);
springPanel.add(level);
upBwLabel = new JLabel("Uplink Bw: ");
springPanel.add(upBwLabel);
upBw = new JTextField();
upBwLabel.setLabelFor(upBw);
springPanel.add(upBw);
downBwLabel = new JLabel("Downlink Bw: ");
springPanel.add(downBwLabel);
downBw = new JTextField();
downBwLabel.setLabelFor(downBw);
springPanel.add(downBw);
/** switch and host */
mipsLabel = new JLabel("Mips: ");
springPanel.add(mipsLabel);
mips = new JTextField();
mipsLabel.setLabelFor(mips);
springPanel.add(mips);
ramLabel = new JLabel("Ram: ");
springPanel.add(ramLabel);
ram = new JTextField();
ramLabel.setLabelFor(ram);
springPanel.add(ram);
rateLabel = new JLabel("Rate/MIPS: ");
springPanel.add(rateLabel);
rate = new JTextField();
rateLabel.setLabelFor(rate);
springPanel.add(rate);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
7, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
//updatePanel("core");
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddFogDevice.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,222 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Link;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddLink extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfLatency;
public AddLink(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Link");
setModal(true);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
if(!(selectedNode.getType().equals("SENSOR")||selectedNode.getType().equals("ACTUATOR")) || edgesForSelectedNode.size()==0){
for (Node node : allNodes) {
if((selectedNode.getType().equals("SENSOR")||selectedNode.getType().equals("ACTUATOR")) && !node.getType().equals("FOG_DEVICE"))
continue;
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label("---->"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Latency: "));
tfLatency = new JTextField();
tfLatency.setMaximumSize(tfLatency.getPreferredSize());
tfLatency.setMinimumSize(new Dimension(150, tfLatency.getPreferredSize().height));
tfLatency.setPreferredSize(new Dimension(150, tfLatency.getPreferredSize().height));
textAreaPanel.add(tfLatency);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double latency = 0;
boolean catchedError = false;
if (tfLatency.getText() == null || tfLatency.getText().isEmpty()) {
catchedError = true;
prompt("Please type latency", "Error");
}else {
try {
latency = Double.valueOf(tfLatency.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Latency should be double type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Link edge = new Link(target, latency);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddLink.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,217 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddPhysicalEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfLatency;
public AddPhysicalEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Physical Topology edge");
setModal(true);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label(" <20><>"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Latency: "));
tfLatency = new JTextField();
tfLatency.setMaximumSize(tfLatency.getPreferredSize());
tfLatency.setMinimumSize(new Dimension(150, tfLatency.getPreferredSize().height));
tfLatency.setPreferredSize(new Dimension(150, tfLatency.getPreferredSize().height));
textAreaPanel.add(tfLatency);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double latency = 0;
boolean catchedError = false;
if (tfLatency.getText() == null || tfLatency.getText().isEmpty()) {
catchedError = true;
prompt("Please type latency", "Error");
}else {
try {
latency = Double.valueOf(tfLatency.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Latency should be double type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, latency);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddPhysicalEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,290 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
import org.fog.gui.core.SwitchNode;
import org.fog.gui.core.HostNode;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddPhysicalNode extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JLabel lName;
private JLabel lType;
private JLabel lBw;
private JLabel lop1;
private JLabel lop2;
private JLabel lop3;
private JLabel lop4;
private JTextField tfName;
private JComboBox cType;
private JTextField tfBw;
private JTextField top1;
private JTextField top2;
private JTextField top3;
private JTextField top4;
public AddPhysicalNode(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Physical Node");
setModal(true);
setPreferredSize(new Dimension(350, 380));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (tfBw.getText() == null || tfBw.getText().length() < 1) {
prompt("Please type VM Bw", "Error");
} else if(cType.getSelectedIndex() < 0) {
prompt("Please type VM Type", "Error");
}else{
String type = (String)cType.getSelectedItem();
if("host"==getType(type)){
if (top1.getText() == null || top1.getText().length() < 1) {
prompt("Please type pes", "Error");
} else if (top2.getText() == null || top2.getText().length() < 1) {
prompt("Please type VM mips", "Error");
} else if (top3.getText() == null || top3.getText().length() < 1) {
prompt("Please type VM RAM", "Error");
} else if (top4.getText() == null || top4.getText().length() < 1) {
prompt("Please type VM Storage", "Error");
} else {
long t1 = 0;
long t2 = 0;
int t3 = 0;
long t4 = 0;
long t5 = 0;
try {
t1 = Long.parseLong(top1.getText());
t2 = Long.parseLong(top2.getText());
t3 = Integer.parseInt(top3.getText());
t4 = Long.parseLong(top4.getText());
t5 = Long.parseLong(tfBw.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new HostNode(tfName.getText().toString(), type, t1, t2, t3, t4, t5);
graph.addNode(node);
setVisible(false);
}
}
}else if("switch"==getType(type)){
if (top1.getText() == null || top1.getText().length() < 1) {
prompt("Please type Iops", "Error");
} else if (top2.getText() == null || top2.getText().length() < 1) {
prompt("Please type upports", "Error");
} else if (top3.getText() == null || top3.getText().length() < 1) {
prompt("Please type VM downports", "Error");
} else {
long t1 = 0;
int t2 = 0;
int t3 = 0;
long t4 = 0;
try {
t1 = Long.parseLong(top1.getText());
t2 = Integer.parseInt(top2.getText());
t3 = Integer.parseInt(top3.getText());
t4 = Long.parseLong(tfBw.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new SwitchNode(tfName.getText().toString(), type, t1, t2, t3, t4);
graph.addNode(node);
setVisible(false);
}
}
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private void updatePanel(String type){
switch(type){
case "core":
case "edge":
lop1.setText("Iops: ");
lop2.setText("Upports: ");
lop3.setText("Downports: ");
lop4.setVisible(false);
top1.setText("");
top2.setText("");
top3.setText("");
top4.setVisible(false);
break;
case "host":
lop1.setText("Pes: ");
lop2.setText("Mips: ");
lop3.setText("Ram: ");
lop4.setVisible(true);
lop4.setText("Storage: ");
top1.setText("");
top2.setText("");
top3.setText("");
top4.setVisible(true);
top4.setText("");
break;
}
}
private String getType(String type){
if("core"==type || "edge"==type){
return "switch";
} else if("host"==type){
return "host";
}
return "";
}
private JPanel createInputPanelArea() {
String[] vmType = {"core","edge","host"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
lType = new JLabel("Type: "); //, JLabel.TRAILING);
springPanel.add(lType);
cType = new JComboBox(vmType);
lType.setLabelFor(cType);
cType.setSelectedIndex(0);
cType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
JComboBox ctype = (JComboBox)e.getSource();
String item = (String)ctype.getSelectedItem();
updatePanel(item);
}
});
springPanel.add(cType);
lBw = new JLabel("Bw: ");
springPanel.add(lBw);
tfBw = new JTextField();
lBw.setLabelFor(tfBw);
springPanel.add(tfBw);
/** switch and host */
lop1 = new JLabel("Pes: ");
springPanel.add(lop1);
top1 = new JTextField();
lop1.setLabelFor(top1);
springPanel.add(top1);
lop2 = new JLabel("Mips: ");
springPanel.add(lop2);
top2 = new JTextField();
lop2.setLabelFor(top2);
springPanel.add(top2);
lop3 = new JLabel("Ram: ");
springPanel.add(lop3);
top3 = new JTextField();
lop3.setLabelFor(top3);
springPanel.add(top3);
lop4 = new JLabel("Storage: ");
springPanel.add(lop4);
top4 = new JTextField();
lop4.setLabelFor(top4);
springPanel.add(top4);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
7, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
updatePanel("core");
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddPhysicalNode.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,270 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.entities.Sensor;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SensorGui;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddSensor extends JDialog {
private static final long serialVersionUID = -511667786177319577L;
private final Graph graph;
private JTextField sensorName;
private JTextField sensorType;
private JComboBox distribution;
private JTextField uniformLowerBound;
private JTextField uniformUpperBound;
private JTextField deterministicValue;
private JTextField normalMean;
private JTextField normalStdDev;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddSensor(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (sensorName.getText() == null || sensorName.getText().length() < 1) {
prompt("Please type Sensor name", "Error");
} else if (sensorType.getText() == null || sensorType.getText().length() < 1) {
prompt("Please type Sensor Type", "Error");
} else if (distribution.getSelectedIndex() < 0) {
prompt("Please select Emission time distribution", "Error");
} else {
double normalMean_ = -1;
double normalStdDev_ = -1;
double uniformLow_ = -1;
double uniformUp_ = -1;
double deterministicVal_ = -1;
String _sensorType = sensorType.getText();
String dist = (String)distribution.getSelectedItem();
if(dist.equals("Normal")){
try {
normalMean_ = Double.parseDouble(normalMean.getText());
normalStdDev_ = Double.parseDouble(normalStdDev.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
} else if(dist.equals("Uniform")){
try {
uniformLow_ = Double.parseDouble(uniformLowerBound.getText());
uniformUp_ = Double.parseDouble(uniformUpperBound.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
} else if(dist.equals("Deterministic")){
try {
deterministicVal_ = Double.parseDouble(deterministicValue.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
String[] distributionType = {"Normal", "Uniform", "Deterministic"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
sensorName = new JTextField();
lName.setLabelFor(sensorName);
springPanel.add(sensorName);
JLabel lType = new JLabel("Type: ");
springPanel.add(lType);
sensorType = new JTextField();
lType.setLabelFor(sensorType);
springPanel.add(sensorType);
JLabel distLabel = new JLabel("Distribution Type: ", JLabel.TRAILING);
springPanel.add(distLabel);
distribution = new JComboBox(distributionType);
distLabel.setLabelFor(distribution);
distribution.setSelectedIndex(-1);
distribution.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
JComboBox ctype = (JComboBox)e.getSource();
String item = (String)ctype.getSelectedItem();
updatePanel(item);
}
});
springPanel.add(distribution);
JLabel normalMeanLabel = new JLabel("Mean: ");
springPanel.add(normalMeanLabel);
normalMean = new JTextField();
normalMeanLabel.setLabelFor(normalMean);
springPanel.add(normalMean);
JLabel normalStdDevLabel = new JLabel("StdDev: ");
springPanel.add(normalStdDevLabel);
normalStdDev = new JTextField();
normalStdDevLabel.setLabelFor(normalStdDev);
springPanel.add(normalStdDev);
JLabel uniformLowLabel = new JLabel("Min: ");
springPanel.add(uniformLowLabel);
uniformLowerBound = new JTextField();
uniformLowLabel.setLabelFor(uniformLowerBound);
springPanel.add(uniformLowerBound);
JLabel uniformUpLabel = new JLabel("Max: ");
springPanel.add(uniformUpLabel);
uniformUpperBound = new JTextField();
uniformUpLabel.setLabelFor(uniformUpperBound);
springPanel.add(uniformUpperBound);
JLabel deterministicValueLabel = new JLabel("Value: ");
springPanel.add(deterministicValueLabel);
deterministicValue = new JTextField();
uniformLowLabel.setLabelFor(deterministicValue);
springPanel.add(deterministicValue);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
8, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
protected void updatePanel(String item) {
switch(item){
case "Normal":
normalMean.setVisible(true);
normalStdDev.setVisible(true);
uniformLowerBound.setVisible(false);
uniformUpperBound.setVisible(false);
deterministicValue.setVisible(false);
break;
case "Uniform":
normalMean.setVisible(false);
normalStdDev.setVisible(false);
uniformLowerBound.setVisible(true);
uniformUpperBound.setVisible(true);
deterministicValue.setVisible(false);
break;
case "Deterministic":
normalMean.setVisible(false);
normalStdDev.setVisible(false);
uniformLowerBound.setVisible(false);
uniformUpperBound.setVisible(false);
deterministicValue.setVisible(true);
break;
default:
break;
}
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddSensor.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SensorModule;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddSensorModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField sensorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddSensorModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (sensorType.getText() == null || sensorType.getText().length() < 1) {
prompt("Please entyer Sensor Type", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new SensorModule(sensorType.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Sensor Type: ");
springPanel.add(lName);
sensorType = new JTextField();
lName.setLabelFor(sensorType);
springPanel.add(sensorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddSensorModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,241 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddVirtualEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfName;
private JTextField tfBandwidth;
public AddVirtualEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Virtual Topology edge");
setModal(true);
setPreferredSize(new Dimension(400, 250));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel2 = new JPanel();
textAreaPanel2.setLayout(new BoxLayout(textAreaPanel2, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
// inputPanel.add(Box.createRigidArea(new Dimension(10, 0)));
inputPanel.add(new Label(" <20><>"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Edge Name: "));
tfName = new JTextField();
tfName.setMaximumSize(tfName.getPreferredSize());
tfName.setMinimumSize(new Dimension(180, tfName.getPreferredSize().height));
tfName.setPreferredSize(new Dimension(180, tfName.getPreferredSize().height));
textAreaPanel.add(tfName);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
textAreaPanel2.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel2.add(new JLabel("Bandwidth: "));
tfBandwidth = new JTextField();
tfBandwidth.setMaximumSize(tfBandwidth.getPreferredSize());
tfBandwidth.setMinimumSize(new Dimension(180, tfBandwidth.getPreferredSize().height));
tfBandwidth.setPreferredSize(new Dimension(180, tfBandwidth.getPreferredSize().height));
textAreaPanel2.add(tfBandwidth);
textAreaPanel2.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel2);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = "default";
long bandwidth = 0;
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().isEmpty()) {
catchedError = true;
prompt("Please type Edge Name", "Error");
}else {
name = (String)tfName.getText();
}
if (tfBandwidth.getText() == null || tfBandwidth.getText().isEmpty()) {
catchedError = true;
prompt("Please type Bandwidth", "Error");
}else {
try {
bandwidth = Long.valueOf(tfBandwidth.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Bandwidth should be long type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, name, bandwidth);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddVirtualEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,198 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
import org.fog.gui.core.VmNode;
import org.fog.gui.core.Node;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddVirtualNode extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField tfName;
private JComboBox cType;
private JTextField tfSize;
private JTextField tfPes;
private JTextField tfMips;
private JTextField tfRam;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddVirtualNode(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Virtual Node");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (cType.getSelectedIndex() < 0) {
prompt("Please select VM type", "Error");
} else if (tfSize.getText() == null || tfSize.getText().length() < 1) {
prompt("Please type VM size", "Error");
} else if (tfPes.getText() == null || tfPes.getText().length() < 1) {
prompt("Please type pes", "Error");
} else if (tfMips.getText() == null || tfMips.getText().length() < 1) {
prompt("Please type VM mips", "Error");
} else if (tfRam.getText() == null || tfRam.getText().length() < 1) {
prompt("Please type VM RAM", "Error");
} else {
long t1 = 0;
int t2 = 0;
long t3 = 0;
int t4 = 0;
try {
t1 = Long.parseLong(tfSize.getText());
t2 = Integer.parseInt(tfPes.getText());
t3 = Long.parseLong(tfMips.getText());
t4 = Integer.parseInt(tfRam.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new VmNode(tfName.getText().toString(), (String)cType.getSelectedItem(),
t1, t2, t3, t4);
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
String[] vmType = {"vm"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
JLabel lType = new JLabel("Type: ", JLabel.TRAILING);
springPanel.add(lType);
cType = new JComboBox(vmType);
lType.setLabelFor(cType);
cType.setSelectedIndex(-1);
cType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
}
});
springPanel.add(cType);
JLabel lSize = new JLabel("Size: ");
springPanel.add(lSize);
tfSize = new JTextField();
lSize.setLabelFor(tfSize);
springPanel.add(tfSize);
JLabel lPes = new JLabel("Pes: ");
springPanel.add(lPes);
tfPes = new JTextField();
lPes.setLabelFor(tfPes);
springPanel.add(tfPes);
JLabel lMips = new JLabel("Mips: ");
springPanel.add(lMips);
tfMips = new JTextField();
lMips.setLabelFor(tfMips);
springPanel.add(tfMips);
JLabel lRam = new JLabel("Ram: ");
springPanel.add(lRam);
tfRam = new JTextField();
lRam.setLabelFor(tfRam);
springPanel.add(tfRam);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
6, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddVirtualNode.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,174 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import org.cloudbus.cloudsim.sdn.graph.example.GraphicSDNExample;
public class SDNRun extends JDialog {
private static final long serialVersionUID = -8313194085507492462L;
private String physicalTopologyFile = ""; //physical
private String deploymentFile = ""; //virtual
private String workloads_background = ""; //workload
private String workloads = ""; //workload
private JPanel panel;
private JScrollPane pane;
private JTextArea outputArea;
private JLabel imageLabel;
private JLabel msgLabel;
private JComponent space;
private int counter = 0;
private Timer timer;
private GraphicSDNExample sdn;
public SDNRun(final String phy, final String vir, final String wlbk, final String wl, final JFrame frame){
physicalTopologyFile = phy;
deploymentFile = vir;
workloads_background = wlbk;
workloads = wl;
setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
initUI();
run();
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE );
setTitle("Run Simulation");
setModal(true);
setPreferredSize(new Dimension(900, 600));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
private void initUI(){
ImageIcon ii = new ImageIcon(this.getClass().getResource("/src/1.gif"));
imageLabel = new JLabel(ii);
imageLabel.setAlignmentX(CENTER_ALIGNMENT);
msgLabel = new JLabel("Simulation is executing");
msgLabel.setAlignmentX(CENTER_ALIGNMENT);
space = (JComponent)Box.createRigidArea(new Dimension(0, 200));
panel.add(space);
panel.add(msgLabel);
panel.add(imageLabel);
pane = new JScrollPane();
outputArea = new JTextArea();
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
outputArea.setEditable(false);
//outputArea.setText("wo ai bei jin tian an men");
//readFile(physicalTopologyFile, outputArea);
pane.getViewport().add(outputArea);
panel.add(pane);
pane.setVisible(false);
}
private void run(){
sdn = new GraphicSDNExample(physicalTopologyFile, deploymentFile, workloads_background, workloads, outputArea);
SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
protected Boolean doInBackground() throws Exception {
boolean success = false;
success = sdn.simulate();
if(success){
sdn.output();
append("<<<<<<<<<< Simulation completed >>>>>>>>>");
}else{
append("<<<<<<<<<< Running Error >>>>>>>>>>");
}
return success;
}
protected void done() {
boolean status;
try {
status = get();
panel.remove(space);
panel.remove(imageLabel);
panel.remove(msgLabel);
pane.setVisible(true);
panel.revalidate();
panel.repaint();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
};
worker.execute();
}
private void append(String content){
outputArea.append(content+"\n");
}
/** below only used for testing reading file to textarea */
private void startTest(){
ActionListener updateProBar = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if(counter>=100){
timer.stop();
panel.remove(space);
panel.remove(imageLabel);
panel.remove(msgLabel);
pane.setVisible(true);
panel.revalidate();
panel.repaint();
}else{
counter +=2;
}
}
};
timer = new Timer(50, updateProBar);
timer.start();
}
private void readFile(String path, JTextArea area) {
try{
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
area.read( br, null );
br.close();
area.requestFocus();
}catch(Exception e2) {
System.out.println(e2);
}
}
}

View File

@@ -0,0 +1,585 @@
package org.fog.gui.example;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.fog.gui.core.Bridge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.GraphView;
import org.fog.gui.dialog.AddActuator;
import org.fog.gui.dialog.AddFogDevice;
import org.fog.gui.dialog.AddLink;
import org.fog.gui.dialog.AddPhysicalEdge;
import org.fog.gui.dialog.AddPhysicalNode;
import org.fog.gui.dialog.AddSensor;
import org.fog.gui.dialog.SDNRun;
public class FogGui extends JFrame {
private static final long serialVersionUID = -2238414769964738933L;
private JPanel contentPane;
/** Import file names */
private String physicalTopologyFile = ""; //physical
private String deploymentFile = ""; //virtual
private String workloads_background = ""; //workload
private String workloads = ""; //workload
private JPanel panel;
private JPanel graph;
private Graph physicalGraph;
//private Graph virtualGraph;
private GraphView physicalCanvas;
//private GraphView virtualCanvas;
private JButton btnRun;
private String mode; //'m':manual; 'i':import
public FogGui() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1280, 800));
setLocationRelativeTo(null);
//setResizable(false);
setTitle("Fog Topology Creator");
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
initUI();
initGraph();
pack();
setVisible(true);
}
public final void initUI() {
setUIFont (new javax.swing.plaf.FontUIResource("Serif",Font.BOLD,18));
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
graph = new JPanel(new java.awt.GridLayout(1, 2));
initBar();
doPosition();
}
/** position window */
private void doPosition() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
int x = (width / 2 - 1280 / 2);
int y = (height / 2 - 800 / 2);
// One could use the dimension of the frame. But when doing so, one have to call this method !BETWEEN! pack and
// setVisible. Otherwise the calculation will go wrong.
this.setLocation(x, y);
}
/** Initialize project menu and tool bar */
private final void initBar() {
//---------- Start ActionListener ----------
ActionListener readPhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
physicalTopologyFile = importFile("josn");
checkImportStatus();
}
};
ActionListener readVirTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
deploymentFile = importFile("json");
checkImportStatus();
}
};
ActionListener readWorkloadBkListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
workloads_background = importFile("cvs");
checkImportStatus();
}
};
ActionListener readWorkloadListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
workloads = importFile("cvs");
checkImportStatus();
}
};
ActionListener addFogDeviceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddFogDeviceDialog();
}
};
ActionListener addPhysicalNodeListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddPhysicalNodeDialog();
}
};
ActionListener addPhysicalEdgeListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddPhysicalEdgeDialog();
}
};
ActionListener addLinkListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddLinkDialog();
}
};
ActionListener addActuatorListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddActuatorDialog();
}
};
ActionListener addSensorListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddSensorDialog();
}
};
ActionListener importPhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fileName = importFile("josn");
Graph phyGraph= Bridge.jsonToGraph(fileName, 0);
physicalGraph = phyGraph;
physicalCanvas.setGraph(physicalGraph);
physicalCanvas.repaint();
}
};
ActionListener savePhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
saveFile("json", physicalGraph);
} catch (IOException e1) {
e1.printStackTrace();
}
}
};
//---------- End ActionListener ----------
//---------- Start Creating project tool bar ----------
JToolBar toolbar = new JToolBar();
ImageIcon iSensor = new ImageIcon(
getClass().getResource("/images/sensor.png"));
ImageIcon iActuator = new ImageIcon(
getClass().getResource("/images/actuator.png"));
ImageIcon iFogDevice = new ImageIcon(
getClass().getResource("/images/dc.png"));
ImageIcon iLink = new ImageIcon(
getClass().getResource("/images/hline2.png"));
ImageIcon iHOpen = new ImageIcon(
getClass().getResource("/images/openPhyTop.png"));
ImageIcon iHSave = new ImageIcon(
getClass().getResource("/images/savePhyTop.png"));
ImageIcon run = new ImageIcon(
getClass().getResource("/images/play.png"));
ImageIcon exit = new ImageIcon(
getClass().getResource("/images/exit.png"));
final JButton btnSensor = new JButton(iSensor);
btnSensor.setToolTipText("Add Sensor");
final JButton btnActuator = new JButton(iActuator);
btnActuator.setToolTipText("Add Actuator");
final JButton btnFogDevice = new JButton(iFogDevice);
btnFogDevice.setToolTipText("Add Fog Device");
final JButton btnLink = new JButton(iLink);
btnLink.setToolTipText("Add Link");
final JButton btnHopen = new JButton(iHOpen);
btnHopen.setToolTipText("Open Physical Topology");
final JButton btnHsave = new JButton(iHSave);
btnHsave.setToolTipText("Save Physical Topology");
btnRun = new JButton(run);
btnRun.setToolTipText("Start simulation");
JButton btnExit = new JButton(exit);
btnExit.setToolTipText("Exit CloudSim");
toolbar.setAlignmentX(0);
btnSensor.addActionListener(addSensorListener);
btnActuator.addActionListener(addActuatorListener);
btnFogDevice.addActionListener(addFogDeviceListener);
btnLink.addActionListener(addLinkListener);
btnHopen.addActionListener(importPhyTopoListener);
btnHsave.addActionListener(savePhyTopoListener);
btnRun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if("i"==mode){
if(physicalTopologyFile==null || physicalTopologyFile.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select physicalTopologyFile", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(deploymentFile==null || deploymentFile.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select deploymentFile", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(workloads_background==null || workloads_background.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select workloads_background", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(workloads==null || workloads.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select workloads", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// run simulation
SDNRun run = new SDNRun(physicalTopologyFile, deploymentFile,
workloads_background, workloads, FogGui.this);
}else if("m"==mode){
}
}
});
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
toolbar.add(btnSensor);
toolbar.add(btnActuator);
toolbar.add(btnFogDevice);
toolbar.add(btnLink);
toolbar.add(btnHopen);
toolbar.add(btnHsave);
toolbar.addSeparator();
/*toolbar.add(btnSensorModule);
toolbar.add(btnActuatorModule);
toolbar.add(btnModule);
toolbar.add(btnAppEdge);*/
toolbar.addSeparator();
toolbar.add(btnRun);
toolbar.add(btnExit);
panel.add(toolbar);
contentPane.add(panel, BorderLayout.NORTH);
//---------- End Creating project tool bar ----------
//---------- Start Creating project menu bar ----------
//1-1
JMenuBar menubar = new JMenuBar();
//ImageIcon iconNew = new ImageIcon(getClass().getResource("/src/new.png"));
//2-1
JMenu graph = new JMenu("Graph");
graph.setMnemonic(KeyEvent.VK_G);
//Graph by importing json and cvs files
final JMenuItem MiPhy = new JMenuItem("Physical Topology");
final JMenuItem MiVir = new JMenuItem("Virtual Topology");
final JMenuItem MiWl1 = new JMenuItem("Workload Background");
final JMenuItem MiWl2 = new JMenuItem("Workload");
//Graph drawing elements
final JMenu MuPhy = new JMenu("Physical");
JMenuItem MiFogDevice = new JMenuItem("Add Fog Device");
JMenuItem MiPhyEdge = new JMenuItem("Add Edge");
JMenuItem MiPhyOpen = new JMenuItem("Import Physical Topology");
JMenuItem MiPhySave = new JMenuItem("Save Physical Topology");
MuPhy.add(MiFogDevice);
MuPhy.add(MiPhyEdge);
MuPhy.add(MiPhyOpen);
MuPhy.add(MiPhySave);
MiPhy.addActionListener(readPhyTopoListener);
MiVir.addActionListener(readVirTopoListener);
MiWl1.addActionListener(readWorkloadBkListener);
MiWl2.addActionListener(readWorkloadListener);
MiFogDevice.addActionListener(addFogDeviceListener);
MiPhyEdge.addActionListener(addPhysicalEdgeListener);
MiPhyOpen.addActionListener(importPhyTopoListener);
MiPhySave.addActionListener(savePhyTopoListener);
graph.add(MuPhy);
//graph.add(MuVir);
graph.add(MiPhy);
//graph.add(MiVir);
graph.add(MiWl1);
graph.add(MiWl2);
//2-2
JMenu view = new JMenu("View");
view.setMnemonic(KeyEvent.VK_F);
//switch mode between manual mode (to create graph by hand) and import mode (to create graph from file)
ActionListener actionSwitcher = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String cmd = e.getActionCommand();
if("Canvas" == cmd){
btnSensor.setVisible(true);
btnActuator.setVisible(true);
btnFogDevice.setVisible(true);
btnLink.setVisible(true);
btnHopen.setVisible(true);
btnHsave.setVisible(true);
MiPhy.setVisible(false);
MiVir.setVisible(false);
MiWl1.setVisible(false);
MiWl2.setVisible(false);
MuPhy.setVisible(true);
//MuVir.setVisible(true);
btnRun.setVisible(false);
btnRun.setEnabled(false);
mode = "m";
}else if("Execution" == cmd){
btnSensor.setVisible(false);
btnActuator.setVisible(false);
btnFogDevice.setVisible(false);
btnLink.setVisible(false);
btnHopen.setVisible(false);
btnHsave.setVisible(false);
MiPhy.setVisible(true);
MiVir.setVisible(true);
MiWl1.setVisible(true);
MiWl2.setVisible(true);
MuPhy.setVisible(false);
//MuVir.setVisible(false);
btnRun.setVisible(true);
btnRun.setEnabled(false);
mode = "i";
}
//System.out.println(e.getActionCommand());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
JRadioButtonMenuItem manualMode = new JRadioButtonMenuItem("Canvas");
manualMode.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
manualMode.addActionListener(actionSwitcher);
JRadioButtonMenuItem importMode = new JRadioButtonMenuItem("Execution");
importMode.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
importMode.addActionListener(actionSwitcher);
ButtonGroup group = new ButtonGroup();
group.add(manualMode);
group.add(importMode);
JMenuItem fileExit = new JMenuItem("Exit");
fileExit.setMnemonic(KeyEvent.VK_C);
fileExit.setToolTipText("Exit CloudSim");
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.CTRL_MASK));
fileExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
view.add(manualMode);
view.add(importMode);
view.addSeparator();
view.add(fileExit);
//3-1
menubar.add(view);
menubar.add(graph);
//4-1
setJMenuBar(menubar);
//----- End Creating project menu bar -----
//----- Start Initialize menu and tool bar -----
manualMode.setSelected(true);
mode = "m";
//btnHost.setVisible(true);
btnSensor.setVisible(true);
btnActuator.setVisible(true);
btnFogDevice.setVisible(true);
btnLink.setVisible(true);
btnHopen.setVisible(true);
btnHsave.setVisible(true);
MiPhy.setVisible(false);
MiVir.setVisible(false);
MiWl1.setVisible(false);
MiWl2.setVisible(false);
MuPhy.setVisible(true);
//MuVir.setVisible(true);
btnRun.setVisible(false);
btnRun.setEnabled(false);
//----- End Initialize menu and tool bar -----
}
protected void openAddActuatorDialog() {
AddActuator actuator = new AddActuator(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddLinkDialog() {
AddLink phyEdge = new AddLink(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddFogDeviceDialog() {
AddFogDevice fogDevice = new AddFogDevice(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
/** initialize Canvas */
private void initGraph(){
physicalGraph = new Graph();
//virtualGraph = new Graph();
physicalCanvas = new GraphView(physicalGraph);
//virtualCanvas = new GraphView(virtualGraph);
graph.add(physicalCanvas);
//graph.add(virtualCanvas);
contentPane.add(graph, BorderLayout.CENTER);
}
/** dialog opening */
private void openAddPhysicalNodeDialog(){
AddPhysicalNode phyNode = new AddPhysicalNode(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
private void openAddPhysicalEdgeDialog(){
AddPhysicalEdge phyEdge = new AddPhysicalEdge(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddSensorDialog() {
AddSensor sensor = new AddSensor(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
/** common utility */
private String importFile(String type){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(type.toUpperCase()+" Files", type);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(panel, "Import file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
return file.getPath();
}
return "";
}
/** save network topology */
private void saveFile(String type, Graph graph) throws IOException{
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(type.toUpperCase()+" Files", type);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showSaveDialog(panel);
if (ret == JFileChooser.APPROVE_OPTION) {
String jsonText = graph.toJsonString();
System.out.println(jsonText);
String path = fileopen.getSelectedFile().toString();
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
out.write(jsonText.getBytes());
out.close();
}
}
private static void setUIFont(javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void checkImportStatus(){
if((physicalTopologyFile!=null && !physicalTopologyFile.isEmpty()) &&
(deploymentFile!=null && !deploymentFile.isEmpty()) &&
(workloads_background!=null && !workloads_background.isEmpty()) &&
(workloads!=null && !workloads.isEmpty())){
btnRun.setEnabled(true);
}else{
btnRun.setEnabled(false);
}
}
/** Application entry point */
public static void main(String args[]) throws InterruptedException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FogGui sdn = new FogGui();
sdn.setVisible(true);
}
});
}
}