Browse Source

Adds Java importing V0.0

(Imported) Protocols are stored in the model.
ImportController to allow Importing.
FileChooser for the ConnectionCreationPanel.
Andreas T. Meyer-Berg 5 years ago
parent
commit
3f77058371

+ 17 - 2
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/control/Controller.java

@@ -20,7 +20,12 @@ public class Controller {
 	 * {@link Model} which stores the smart home model
 	 */
 	Model model;
-
+	
+	/**
+	 * Controller for Import of user defined java classes
+	 */
+	ImportController importController;
+	
 	/**
 	 * Create a new Controller, which controls the given model and allows
 	 * manipulation of this model
@@ -30,8 +35,18 @@ public class Controller {
 	 */
 	public Controller(Model model) {
 		this.model = model;
+		importController = new ImportController(model, this);
 	}
-
+	
+	/**
+	 * Returns the ImportController, which manages the user imported classes, 
+	 * which can be used in the framework
+	 * @return ImportExportController
+	 */
+	public ImportController getControllerImport(){
+		return importController;
+	}
+	
 	/**
 	 * Moves the SmartDevice device to the specified location, if it exists
 	 * 

+ 107 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/control/ImportController.java

@@ -0,0 +1,107 @@
+package de.tu_darmstadt.tk.SmartHomeNetworkSim.control;
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.LinkedList;
+
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Model;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Protocol;
+
+/**
+ * Controller which manages Imported Classes of the 
+ *
+ * @author Andreas T. Meyer-Berg
+ */
+public class ImportController {
+	Model model;
+	Controller controller;
+	
+	/**
+	 * Creates a new ImportController
+	 * @param model model to be edited
+	 * @param controller parent controller
+	 */
+	public ImportController(Model model, Controller controller) {
+		this.model = model;
+		this.controller = controller;
+	}
+	
+	/**
+	 * Returns the available Protocols of the model
+	 * 
+	 * @return available protocols
+	 */
+	public LinkedList<Class<? extends Protocol>> getProtocols(){
+		return model.getProtocols();
+	}
+	
+	/**
+	 * Adds new Protocol to the model
+	 * @param protocol protocol to be added
+	 * @return true if it was added
+	 */
+	public boolean addProtocol(Class<? extends Protocol> protocol){
+		if(isValidProtocol(protocol))
+			model.addProtocol(protocol);
+		else 
+			return false;
+		return true;
+		
+	}
+	
+	/**
+	 * Removes protocol from the model
+	 * @param protocol protocol to be removed
+	 */
+	public void removeProtocol(Class<? extends Protocol> protocol){
+		model.removeProtocol(protocol);
+	}
+	
+	/**
+	 * Returns true if it is a Valid Protocol, false if not
+	 * 
+	 * @param protocol protocol to be checked
+	 * @return true if it is a valid protocol
+	 */
+	public boolean isValidProtocol(Class<? extends Protocol> protocol){
+		try {
+			Protocol p = protocol.newInstance();
+			//Empty constructor required, to create new instance
+			if(p == null)
+				throw new Exception("Protocol required an empty constructor");
+			// Name shall not be null or empty string
+			if(p.getName() == null || p.getName()=="")
+				throw new Exception("Protocol name shall not be null or empty string.");
+			if(p.getRoles()==null||p.getRoles().length==0)
+				throw new Exception("Roles shall not be null or empty");
+			// Number of roles have to match
+			if(p.getNumberOfRoles()!=p.getRoles().length) 
+				throw new Exception("getNumberOfRoles() does not match getRoles().length");
+		} catch (Exception e) {
+			return false;
+		}
+		return true;
+	}
+	
+	public Class importJavaClass(File javaFile){
+		// Compile
+		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+		compiler.run(null, null, null, javaFile.getPath());
+
+		// Load compiled class. - not working
+		try{
+		URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("src/").toURI().toURL() });
+		String className = javaFile.getName().substring(javaFile.getName().lastIndexOf('.'));
+		Class<?> cls = Class.forName(className, true, classLoader); // Should load the class
+		
+		return cls;
+		}catch(Exception e){
+			
+		}
+		return null;
+	}
+}

+ 36 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/core/Model.java

@@ -4,6 +4,9 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Observable;
 
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.simpleImplementation.SimpleProtocol;
+
 /**
  * Model of the smart home, which contains all the important parts of the simulation, like {@link SmartDevice} and their {@link Link}.
  *
@@ -15,6 +18,9 @@ public class Model extends Observable{
 	private List<Link> connectionNetworks;
 	private List<Connection> connections;
 	
+	private LinkedList<Class<? extends Protocol>> standardProtocols = new LinkedList<Class<? extends Protocol>>();
+	private LinkedList<Class<? extends Protocol>> importedProtocols = new LinkedList<Class<? extends Protocol>>();
+	
 	/**
 	 * Width of the smart home model, 0 <= device.x < width
 	 */
@@ -53,6 +59,9 @@ public class Model extends Observable{
 		devices = new LinkedList<SmartDevice>();
 		connectionNetworks = new LinkedList<Link>();
 		connections = new LinkedList<Connection>();
+		
+		standardProtocols.add(MQTT_protocol.class);
+		standardProtocols.add(SimpleProtocol.class);
 	}
 
 	/**
@@ -171,4 +180,31 @@ public class Model extends Observable{
 	public void setSim(SimulationManager sim) {
 		this.sim = sim;
 	}
+	
+	/**
+	 * Returns Protocols of the Model
+	 * @return available Protocols
+	 */
+	public LinkedList<Class<? extends Protocol>> getProtocols(){
+		LinkedList<Class<? extends Protocol>> export = new LinkedList<Class<? extends Protocol>>();
+		export.addAll(standardProtocols);
+		export.addAll(importedProtocols);
+		return export;
+	}
+	
+	/**
+	 * Adds newProtocol to the available protocols
+	 * @param newProtocol new Protocol to be added
+	 */
+	public void addProtocol(Class<? extends Protocol> newProtocol){
+		importedProtocols.add(newProtocol);
+	}
+	
+	/**
+	 * Removes Protocol from the available protocols
+	 * @param remove protocol to be removed
+	 */
+	public void removeProtocol(Class<? extends Protocol> remove){
+		importedProtocols.remove(remove);
+	}
 }

+ 67 - 6
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/ConnectionCreationPanel.java

@@ -5,6 +5,7 @@ import java.awt.Dimension;
 import java.awt.Window;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
+import java.io.File;
 import java.util.Collection;
 import java.util.LinkedList;
 import java.util.concurrent.ThreadLocalRandom;
@@ -19,8 +20,8 @@ import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Protocol;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.simpleImplementation.SimpleLink;
-import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.simpleImplementation.SimpleProtocol;
 
+import javax.swing.JFileChooser;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.JLabel;
@@ -32,6 +33,7 @@ import javax.swing.JComboBox;
 import javax.swing.JButton;
 import javax.swing.event.DocumentEvent;
 import javax.swing.event.DocumentListener;
+import javax.swing.filechooser.FileFilter;
 
 @SuppressWarnings("serial")
 public class ConnectionCreationPanel extends JScrollPane {
@@ -135,9 +137,7 @@ public class ConnectionCreationPanel extends JScrollPane {
 	private void initializePanel() {
 		disconnectedIndex = connection.getProtocol().getNumberOfRoles();
 		
-		availableProtocols = new LinkedList<Class<? extends Protocol>>();
-		availableProtocols.add(MQTT_protocol.class);
-		availableProtocols.add(SimpleProtocol.class);
+		availableProtocols = controller.getControllerImport().getProtocols();
 
 		setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
 		this.setPreferredSize(new Dimension(600, 170 + ports.length * 20));
@@ -273,8 +273,69 @@ public class ConnectionCreationPanel extends JScrollPane {
 		JButton btnImportLink = new JButton("Import Link Type");
 		btnImportLink.setBounds(290, 40, 155, 20);
 		content.add(btnImportLink);
-		btnImportLink.addActionListener(a -> System.out
-				.println("WARNING: No import yet"));
+		btnImportLink.addActionListener(a -> {
+			//Filechooser starting in the base directory
+			JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
+			fc.setFileFilter(new FileFilter() {
+				
+				@Override
+				public String getDescription() {
+					return "Java Files(.java, .class)";
+				}
+				
+				@Override
+				public boolean accept(File f) {
+					if(f == null)
+						return false;
+					else if(f.isDirectory())
+						return true;
+					String[] parts = f.getName().split("[.]");
+					if(parts.length<=1)
+						return false;
+					String ending = parts[parts.length-1].toLowerCase();
+		            if(ending.equals("class"))
+		            	return true;
+		            else if(ending.equals("java"))
+		            	return true;
+		            else
+		            	return false;
+				}
+			});
+			int returnVal = fc.showOpenDialog(this);
+
+	        if (returnVal == JFileChooser.APPROVE_OPTION) {
+	            File file = fc.getSelectedFile();
+	            System.out.println("Opening: " + file.getName());
+	            String[] parts = file.getName().split("[.]");
+	            for(int i = 0; i<parts.length; i++)
+	            	System.out.println(i+" "+parts[i]);
+	            if(parts.length <= 1)
+	            	return;
+	            String ending = parts[parts.length-1].toLowerCase();
+	            if(ending.equals("class")){
+	            	System.out.println("Java Class File - not implemented");
+	            }
+	            else if(ending.equals("java")){
+	            	System.out.println("Java File");
+	            	// Compile source file.
+	            	Class imported = controller.getControllerImport().importJavaClass(file);
+	            	if(imported==null){
+	            		System.out.println("Importing failed");
+	            	}else{
+	            		Class[] interfaces = imported.getInterfaces();
+	            		for(int i = 0; i<interfaces.length; i++){
+	            			if(interfaces[i] == Protocol.class)
+	            				System.out.println("YEAH PROTOCOL");
+	            		}
+	            	}
+	            }else{
+	            	System.out.println("invalid File Type");
+	            	return;
+	            }
+	        } else {
+	            System.out.println("Open command cancelled by user.");
+	        }
+		});
 
 		JButton btnCreate = new JButton("Verify and Create");
 		btnCreate.setBounds(121, 103, 206, 25);