// Parse configuration file
// Assumption here is that .config file is written with the correct syntax (need typechecking)
- //File file = new File(strCfgFileName);
- //Scanner scanFile = new Scanner(new FileReader(file));
- //System.out.println("IoTInstaller: Extracting information from config file: " + strCfgFileName);
-
// Initialize String for ID and TYPE
String strID = "";
String strType = "";
*/
public void extractTableAndInstall(String strCfgFileName) {
// TO DO: WE PROBABLY NEED TO IMPROVE THE FILE PARSING BUT FOR NOW KEEP IT MINIMUM
-
try {
// Parse configuration file
strFields[iFieldCnt++] = scanFile.next();
}
-
// Create a new installer object
tbl.setTableName(STR_COMM_TABLE_NAME);
tbl.insertEntry(strFields);
// Insert new address entry
tbl.insertEntry(strFieldsAddress);
-
System.out.println("IoTInstaller: Installing a new device/entity address into the system");
}
File file = new File(strCfgFileName);
FileInputStream fis = new FileInputStream(file);
System.out.println("IoTInstaller: Extracting information from config file: " + strCfgFileName);
-
installDeviceAddressCore(fis);
} catch (FileNotFoundException ex) {
// Insert new address entry
tbl.insertEntry(strFieldsAddress);
-
System.out.println("IoTInstaller: Installing a new device/entity address into the system");
} catch (FileNotFoundException ex) {
// Insert new address entry
tbl.insertEntry(strFieldsAddress);
-
System.out.println("IoTInstaller: Installing a new device/entity address into the system");
} catch (FileNotFoundException ex) {
// Create a new installer object
tbl.setTableName(STR_HOST_TABLE_NAME);
tbl.insertEntry(strFields);
-
System.out.println("IoTInstaller: Installing a new host into the system");
} catch (FileNotFoundException ex) {
tbl.setTableName(STR_HOST_TABLE_NAME);
String strWhere = "HOSTADDRESS='" + strHostAddress + "';";
tbl.deleteEntry(strWhere);
-
System.out.println("IoTInstaller: Deleting a host from the system");
}
String strWhere = "ID='" + strEntID + "';";
tbl.deleteEntry(strWhere);
System.out.println("IoTInstaller: Removing entity from table " + STR_MAIN_TABLE_NAME);
-
// Delete from table with type name, e.g. Camera
tbl.setTableName(strEntType);
strWhere = "ID='" + strEntID + "';";
tbl.setTableName(strEntAddType + strEntID);
tbl.dropTable();
System.out.println("IoTInstaller: Dropping class constructor table...");
-
System.out.println("IoTInstaller: Deleting an entry from the system...");
}
try {
String strCommand = "SELECT " + strTableName + ".* "
- /*+ strOtherTableName + ".*, "
- + STR_COMM_TABLE_NAME + ".ACCESS "*/
+ "FROM "
+ strTableName + ", "
+ strOtherTableName + ", "
try {
String strCommand = "SELECT "/*+ strTableName + ".*, "*/
+ strOtherTableName + ".* "
- /*+ STR_COMM_TABLE_NAME + ".ACCESS "*/
+ "FROM "
+ strTableName + ", "
+ strOtherTableName + ", "
String strClassImplTableID = rs.getString(1);
String strClassImplTableName = rs.getString(2);
String strSQLCommand = "SELECT * FROM " + strClassImplTableName +
- strClassImplTableID + ";";
+ strClassImplTableID + ";";
ResultSet rsClassImplementation = sqlInterface.sqlCommandQuery(strSQLCommand);
if(rsClassImplementation.next()) {
// Get the column type name
String strClassImplTableID = rs.getString(1);
String strClassImplTableName = rs.getString(2);
String strCommand = "SELECT * FROM " + strClassImplTableName +
- strClassImplTableID + ";";
+ strClassImplTableID + ";";
RuntimeOutput.print(strCommand, bVerbose);
ResultSet rsClassImplementation = sqlInterface.sqlCommandQuery(strCommand);
// Get the column type name
// | 0 | 100 |
// +------+-------+
String strCommand = "SELECT * FROM " + strClassImplTableName +
- strClassImplTableID + ";";
+ strClassImplTableID + ";";
RuntimeOutput.print(strCommand, bVerbose);
ResultSet rsClassImplementation = sqlInterface.sqlCommandQuery(strCommand);
rsmd = rsClassImplementation.getMetaData();
for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
String newIntface = intMeth.getKey();
int newObjectId = getNewIntfaceObjectId(newIntface);
- //println("private final static int object" + newObjectId + "Id = " +
- // newObjectId + ";\t//" + newIntface);
Set<String> methodIds = intMeth.getValue();
print("private static Integer[] object" + newObjectId + "Permission = { ");
int i = 0;
println("retClsVal[retPos++] = null;");
}
}
- //println("Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
// Handle the actual returned struct
writeWaitForReturnValueJava(method, intDecl, "Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
if (isArray(retType)) { // An array
// Now, write the body of stub!
if (isCallbackMethod)
writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
- //else
writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
println("}\n");
}
private void writePropertiesJavaSkeleton(String intface, InterfaceDecl intDecl) {
println("private " + intface + " mainObj;");
- //println("private int objectId = 0;");
Integer objId = mapIntfaceObjId.get(intface);
println("private int objectId = " + objId + ";");
println("// Communications and synchronizations");
// Generate array of parameter objects
boolean isCallbackMethod = false;
- //String callbackType = null;
Set<String> callbackType = new HashSet<String>();
println("byte[] localMethodBytes = methodBytes;");
println("rmiComm.setGetMethodBytes();");
// Generate array of parameter objects
boolean isCallbackMethod = false;
- //String callbackType = null;
Set<String> callbackType = new HashSet<String>();
println("byte[] localMethodBytes = methodBytes;");
println("rmiComm.setGetMethodBytes();");
String paramType = returnGenericCallbackType(methPrmTypes.get(i));
if (callbackClasses.contains(paramType)) {
isCallbackMethod = true;
- //callbackType = paramType;
callbackType.add(paramType);
print("int[].class");
} else { // Generate normal classes if it's not a callback object
if (i != methParams.size() - 1)
print(", ");
}
- //println(" }, ");
// Generate generic class if it's a generic type.. null otherwise
print(" }, new Class<?>[] { ");
for (int i = 0; i < methParams.size(); i++) {
println("1;");
}
println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
- //println("void* retStructLen" + i + " = NULL;");
println("rmiComm->remoteCall(objectId, methodIdStruct" + i +
", paramClsStruct" + i + ", paramObjStruct" + i +
", numParam" + i + ");\n");
println("retObj[retPos++] = &retParam" + i + ";");
}
}
- //println("rmiComm->getStructObjects(retCls, numRet, retObj);");
writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getStructObjects(retCls, numRet, retObj);");
if (isArrayOrList(retType, retType)) { // An array or list
println("vector<" + simpleType + "> structRet(retLen);");
println("delete obj;");
println("}\n");
println("extern \"C\" void init" + newStubClass + "(void* t) {");
- //println(newStubClass + "* obj = (" + newStubClass + "*) t;");
- //println("obj->init();");
- //println("while(true);");
println("}\n");
}
}
println("using namespace std;"); println("");
// Add default constructor and destructor
- //println(newStubClass + "() { }"); println("");
writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
writeCallbackConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
for (int i = 0; i < methParams.size(); i++) {
String paramType = methPrmTypes.get(i);
String param = methParams.get(i);
- //if (callbackType.equals(paramType)) {
if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
- //println("int numStubs" + i + " = 0;");
println("vector<int> numStubIdArray" + i + ";");
}
}
// Generate array of parameter types
boolean isCallbackMethod = false;
- //String callbackType = null;
Set<String> callbackType = new HashSet<String>();
print("string paramCls[] = { ");
for (int i = 0; i < methParams.size(); i++) {
String paramType = returnGenericCallbackType(methPrmTypes.get(i));
if (callbackClasses.contains(paramType)) {
isCallbackMethod = true;
- //callbackType = paramType;
callbackType.add(paramType);
print("\"int*\"");
} else { // Generate normal classes if it's not a callback object
String prmType = returnGenericCallbackType(methPrmTypes.get(i));
if (callbackClasses.contains(prmType)) {
isCallbackMethod = true;
- //callbackType = prmType;
callbackType.add(prmType);
- //println("int numStubs" + i + " = 0;");
println("vector<int> numStubIdArray" + i + ";");
println("paramCls[pos] = \"int*\";");
println("paramObj[pos++] = &numStubIdArray" + i + ";");
println("delete obj;");
println("}\n");
println("extern \"C\" void init" + newSkelClass + "(void* t) {");
- //println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
- //println("obj->init();");
- //println("while(true);");
println("}\n");
}
public static void printUsage() {
System.out.println();
- System.out.println("Sentinel interface and stub compiler version 1.0");
+ System.out.println("Vigilia interface and stub compiler version 1.0");
System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
System.out.println("All rights reserved.");
System.out.println("Usage:");
// Basically the compiler needs to parse the policy (and requires) files for callback class first
private int getNewIntfaceObjectId(String newIntface) {
-// if (!mapNewIntfaceObjId.containsKey(newIntface)) {
-// throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
-// "Please place the two files for callback class in front...\n");
-// return -1;
-// } else {
- int retObjId = mapNewIntfaceObjId.get(newIntface);
- return retObjId;
-// }
+ int retObjId = mapNewIntfaceObjId.get(newIntface);
+ return retObjId;
}
// Add the standard list first
importClasses.add("<vector>");
importClasses.add("<set>");
- //importClasses.add("\"IoTRMICall.hpp\"");
- //importClasses.add("\"IoTRMIObject.hpp\"");
importClasses.add("\"IoTRMIComm.hpp\"");
importClasses.add("\"IoTRMICommClient.hpp\"");
importClasses.add("\"IoTRMICommServer.hpp\"");
// JFlex parser specification written by
// Rahmadi Trimananda
-// for Sentinel system
+// for Vigilia system
// University of California, Irvine
// Technische Universitaet Muenchen
rmiComm->returnQueue.enqueue(packetBytes, packetLen);
} else {
// TODO: We need to log error message when we come to running this using IoTSlave
- // TODO: Beware that using "cout" in the process will kill it (as IoTSlave is loaded in Sentinel)
+ // TODO: Beware that using "cout" in the process will kill it (as IoTSlave is loaded at runtime)
cerr << "IoTRMICommClient: Packet type is unknown: " << packetType << endl;
exit(1);
}
rmiComm->returnQueue.enqueue(packetBytes, packetLen);
} else {
// TODO: We need to log error message when we come to running this using IoTSlave
- // TODO: Beware that using "cout" in the process will kill it (as IoTSlave is loaded in Sentinel)
+ // TODO: Beware that using "cout" in the process will kill it (as IoTSlave is loaded at runtime)
cerr << "IoTRMICommServer: Packet type is unknown: " << packetType << endl;
exit(1);
}
// Take the current method from the queue and wake up the correct thread
retValueBytes = returnQueue.poll();
if (retValueBytes != null) { // If there is method bytes
- //System.out.println("retValBytes in wake up thread: " + Arrays.toString(retValueBytes));
int objectId = getObjectId(retValueBytes);
int methodId = getMethodId(retValueBytes);
String strKey = objectId + "-" + methodId;
AtomicBoolean retRecv = mapStubId.get(strKey);
- //System.out.println("boolean status: " + retRecv + " with key: " + strKey);
didGetReturnBytes.set(false);
while(!retRecv.compareAndSet(false, true));
- //System.out.println("boolean status: " + retRecv + " - map has: " + mapStubId.size());
while(!didGetReturnBytes.get()); // While skeleton is still processing
}
}
public synchronized void registerStub(int objectId, int methodId, AtomicBoolean retValueReceived) {
String strKey = objectId + "-" + methodId;
- //System.out.println("Key exist? " + mapStubId.containsKey(strKey));
mapStubId.put(strKey, retValueReceived);
- //System.out.println("\n\nAdding keyBytes: " + strKey + " now size: " + mapStubId.size() + "\n\n");
}
System.arraycopy(packetBytes, IoTRMIUtil.OBJECT_ID_LEN, methodIdBytes, 0, IoTRMIUtil.METHOD_ID_LEN);
// Get method Id
int methodId = IoTRMIUtil.byteArrayToInt(methodIdBytes);
- // Get method Id
return methodId;
}
// Receive return value and return it to caller
// Now just strip off the object ID and method ID
int headerLen = IoTRMIUtil.OBJECT_ID_LEN + IoTRMIUtil.METHOD_ID_LEN + IoTRMIUtil.PACKET_TYPE_LEN;
- //if (retValueBytes == null)
- // System.out.println("retValueBytes is null!");
-
int valByteLen = retValueBytes.length - headerLen;
byte[] retValBytes = new byte[valByteLen];
// Method Id is positioned after object Id in the byte array
-
- //System.out.println("Val byte len: " + valByteLen);
- //System.out.println("Length retValBytes: " + retValBytes.length);
-
- //System.arraycopy(retValueBytes, headerLen, retValBytes, 0, valByteLen);
- //Object retObj = IoTRMIUtil.getParamObject(retType, retGenTypeVal, retValBytes);
Object retObj = null;
if (valByteLen != 0) {
System.arraycopy(retValueBytes, headerLen, retValBytes, 0, valByteLen);
if (packetBytes != null) {
int packetType = IoTRMIComm.getPacketType(packetBytes);
if (packetType == IoTRMIUtil.METHOD_TYPE) {
- //System.out.println("Method packet: " + Arrays.toString(packetBytes));
methodQueue.offer(packetBytes);
} else if (packetType == IoTRMIUtil.RET_VAL_TYPE) {
- //System.out.println("Return value packet: " + Arrays.toString(packetBytes));
returnQueue.offer(packetBytes);
} else
throw new Error("IoTRMICommClient: Packet type is unknown: " + packetType);
- } //else
- // Thread.sleep(100);
+ }
packetBytes = null;
} catch (Exception ex) {
ex.printStackTrace();
public synchronized void sendReturnObj(Object retObj, byte[] methodBytes) {
// Send back return value
- //byte[] retObjBytes = IoTRMIUtil.getObjectBytes(retObj);
byte[] retObjBytes = null;
if (retObj != null) // Handle nullness
retObjBytes = IoTRMIUtil.getObjectBytes(retObj);
// Send return value together with OBJECT_ID and METHOD_ID for arbitration
int objMethIdLen = IoTRMIUtil.OBJECT_ID_LEN + IoTRMIUtil.METHOD_ID_LEN;
int headerLen = objMethIdLen + IoTRMIUtil.PACKET_TYPE_LEN;
- //byte[] retAllBytes = new byte[headerLen + retObjBytes.length];
byte[] retAllBytes = null;
if (retObj == null) // Handle nullness
retAllBytes = new byte[headerLen];
try {
packetBytes = rmiServerRecv.receiveBytes(packetBytes);
if (packetBytes != null) {
- //System.out.println("Packet received: " + Arrays.toString(packetBytes));
int packetType = IoTRMIComm.getPacketType(packetBytes);
if (packetType == IoTRMIUtil.METHOD_TYPE) {
- //System.out.println("Method packet: " + Arrays.toString(packetBytes));
methodQueue.offer(packetBytes);
} else if (packetType == IoTRMIUtil.RET_VAL_TYPE) {
- //System.out.println("Return value packet: " + Arrays.toString(packetBytes));
returnQueue.offer(packetBytes);
} else
throw new Error("IoTRMICommServer: Packet type is unknown: " + packetType);
- } //else
- // Thread.sleep(100);
+ }
packetBytes = null;
} catch (Exception ex) {
ex.printStackTrace();
public synchronized void sendReturnObj(Object retObj, byte[] methodBytes) {
// Send back return value
- //byte[] retObjBytes = IoTRMIUtil.getObjectBytes(retObj);
byte[] retObjBytes = null;
if (retObj != null) // Handle nullness
retObjBytes = IoTRMIUtil.getObjectBytes(retObj);
// Send return value together with OBJECT_ID and METHOD_ID for arbitration
int objMethIdLen = IoTRMIUtil.OBJECT_ID_LEN + IoTRMIUtil.METHOD_ID_LEN;
int headerLen = objMethIdLen + IoTRMIUtil.PACKET_TYPE_LEN;
- //byte[] retAllBytes = new byte[headerLen + retObjBytes.length];
byte[] retAllBytes = null;
if (retObj == null) // Handle nullness
retAllBytes = new byte[headerLen];
}
- /**
- * setMethodBytes() sets bytes for method
- */
- /*public void setMethodBytes(byte[] _methodBytes) throws IOException {
-
- // Set method bytes
- methodBytes = _methodBytes;
- }*/
-
-
/**
* getMethodId() gets method Id from bytes
*/
System.arraycopy(methodBytes, IoTRMIUtil.OBJECT_ID_LEN, methodIdBytes, 0, IoTRMIUtil.METHOD_ID_LEN);
// Get method Id
int methodId = IoTRMIUtil.byteArrayToInt(methodIdBytes);
- // Get method Id
return methodId;
}
System.arraycopy(methodBytes, IoTRMIUtil.OBJECT_ID_LEN, methodIdBytes, 0, IoTRMIUtil.METHOD_ID_LEN);
// Get method Id
int methodId = IoTRMIUtil.byteArrayToInt(methodIdBytes);
- // Get method Id
return methodId;
}
*/
public final static String[] nonPrimitivesJava = new String[] {
- //"Set",
- //"HashSet",
- //"Map",
- //"HashMap",
"List",
"ArrayList"
};
*/
public final static String[] nonPrimitiveJavaLibs = new String[] {
- //"java.util.Set",
- //"java.util.HashSet",
- //"java.util.Map",
- //"java.util.HashMap",
"java.util.List",
"java.util.ArrayList"
};
*/
public final static String[] nonPrimitivesCplus = new String[] {
- //"set",
- //"unordered_set",
- //"map",
- //"unordered_map",
- //"list",
- //"list"
"vector",
"vector"
};
IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
}
-
- /*public static void initRMICall(int port, String address, int rev) throws IOException {
- rmiCall = new IoTRMICall(port, address, rev);
- }
-
- public static void initRMICall(int localPort, int port, String address, int rev) throws IOException {
- rmiCall = new IoTRMICall(localPort, port, address, rev);
- }
-
- public static void initRMIObject(int port) throws IOException, ClassNotFoundException,
- InstantiationException, IllegalAccessException {
- rmiObj = new IoTRMIObject(port);
- }*/
-
/**
* getHashCodeBytes() gets hash value (in bytes) from method name
* Class Constant
*/
protected static int BUFFSIZE = 128000; // how many bytes our incoming buffer can hold (original)
- //protected static int BUFFSIZE = 8388608; // 8388608 = 2^23 bytes of memory (8MB) - this is required by our IHome speaker driver
protected static int MSG_LEN_SIZE = 4; // send length in the size of integer (4 bytes)
/**
ByteBuffer bb = ByteBuffer.allocate(MSG_LEN_SIZE);
bb.putInt(len);
output.write(bb.array(), 0, MSG_LEN_SIZE);
- //System.out.println("Sender about to send: " + Arrays.toString(bb.array()));
output.flush();
// Write the byte array
output.write(vals, 0, len);
- //System.out.println("Sender sending: " + len);
output.flush();
- //System.out.println("Sender about to receive ACK!");
receiveAck();
- //System.out.println("Sender about to send ACK!\n\n");
sendAck();
}
return null;
}
- //System.out.println("Receiver about to receive: " + input.available());
// Read the maxlen first - read 4 bytes here
byte[] lenBytes = new byte[MSG_LEN_SIZE];
input.read(lenBytes, 0, MSG_LEN_SIZE);
- //System.out.println("Receiver lenBytes: " + Arrays.toString(lenBytes));
int maxlen = ByteBuffer.wrap(lenBytes).getInt();
- //System.out.println("Receiver received length: " + maxlen);
// Receive until maxlen
if (maxlen>BUFFSIZE) {
System.out.println("IoTSocketClient/Server: Sending more bytes then will fit in buffer! Number of bytes: " + maxlen);
}
// we now send an acknowledgement to the server to let them
// know we've got it
- //System.out.println("Receiver about to send ACK!");
sendAck();
- //System.out.println("Receiver about to receive ACK!\n\n");
receiveAck();
return val;
+++ /dev/null
-
-public class CallBack implements CallBackInterface {
-
- /**
- * Class Properties
- */
- private int intA;
-
- /**
- * Constructors
- */
- public CallBack(int _i) {
-
- intA = _i;
- }
-
-
- public int printInt() {
-
- System.out.println("Integer: " + intA);
- return intA;
- }
-
-
- public void setInt(int _i) {
-
- intA = _i;
- }
-
-
- public void needCallback(TestClassComplete tc) {
-
- //System.out.println("Going to invoke getShort()!");
- //for(int i=0; i<10; i++)
- System.out.println("Short from TestClass: " + tc.getShort((short)1234));
- }
-}
+++ /dev/null
-import java.util.Set;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-public class TestClass implements TestClassInterface {
-
- /**
- * Class Properties
- */
- private int intA;
- private float floatB;
- private String stringC;
- private List<CallBackInterfaceWithCallBack> cblist;
-
- /**
- * Constructors
- */
- public TestClass() {
-
- intA = 1;
- floatB = 2;
- stringC = "345";
- cblist = new ArrayList<CallBackInterfaceWithCallBack>();
- }
-
-
- public TestClass(int _int, float _float, String _string) {
-
- intA = _int;
- floatB = _float;
- stringC = _string;
- cblist = new ArrayList<CallBackInterfaceWithCallBack>();
- }
-
-
- public int callBack() {
-
- int sum = 0;
- System.out.println("Callback called! cblist: " + cblist.size());
- for (CallBackInterfaceWithCallBack cb : cblist) {
- sum = sum + cb.printInt();
- //cb.needCallback(this);
- TestClass tci = new TestClass();
- cb.needCallback(this);
- cb.needCallback(tci);
- System.out.println("\n\nInside the loop! Sum is now: " + sum + "\n\n");
- }
- System.out.println("Executed callback of callback! Returning value: " + sum + "\n\n");
- return sum;
- }
-
- // Callback
- //public void registerCallback(CallBackInterface _cb) {
- public void registerCallback(CallBackInterfaceWithCallBack _cb) {
-
- cblist.add(_cb);
- System.out.println("Registering callback object! Items: " + cblist.size());
- }
-
-
- public void registerCallbackArray(CallBackInterfaceWithCallBack _cb[]) {
-
- for (CallBackInterfaceWithCallBack cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback objects in array!");
- }
- }
-
-
- public void registerCallbackList(List<CallBackInterfaceWithCallBack> _cb) {
-
- for (CallBackInterfaceWithCallBack cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback objects in list!");
- }
- }
-
-
- public void registerCallbackComplex(int in, List<CallBackInterfaceWithCallBack> _cb, double db) {
-
- for (CallBackInterfaceWithCallBack cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback objects in list!");
- }
-
- System.out.println("Integer: " + in);
- System.out.println("Double: " + db);
- }
-
-
- // Single variables
- public byte getByte(byte in) {
-
- return in;
- }
-
-
- public short getShort(short in) {
-
- return in;
- }
-
-
- public long getLong(long in) {
-
- return in;
- }
-
-
- public float getFloat(float in) {
-
- return in;
- }
-
-
- public double getDouble(double in) {
-
- return in;
- }
-
-
- public boolean getBoolean(boolean in) {
-
- return in;
- }
-
-
- public char getChar(char in) {
-
- return in;
- }
-
-
- // Arrays
- public byte[] getByteArray(byte[] in) {
-
- return in;
- }
-
-
- public short[] getShortArray(short[] in) {
-
- return in;
- }
-
-
- public long[] getLongArray(long[] in) {
-
- return in;
- }
-
-
- public float[] getFloatArray(float[] in) {
-
- return in;
- }
-
-
- public double[] getDoubleArray(double[] in) {
-
- return in;
- }
-
-
- public boolean[] getBooleanArray(boolean[] in) {
-
- return in;
- }
-
-
- public char[] getCharArray(char[] in) {
-
- return in;
- }
-
-
- // Lists
- public List<Byte> getByteList(List<Byte> in) {
-
- return in;
- }
-
-
- public List<Short> getShortList(List<Short> in) {
-
- return in;
- }
-
-
- public List<Long> getLongList(List<Long> in) {
-
- return in;
- }
-
-
- public List<Float> getFloatList(List<Float> in) {
-
- return in;
- }
-
-
- public List<Double> getDoubleList(List<Double> in) {
-
- return in;
- }
-
-
- public List<Boolean> getBooleanList(List<Boolean> in) {
-
- return in;
- }
-
-
- public List<Character> getCharList(List<Character> in) {
-
- return in;
- }
-
-
- // Other functions
- public int getA() {
-
- return intA;
- }
-
-
- public void setA(int _int) {
-
- intA = _int;
- }
-
-
- public void setB(float _float) {
-
- floatB = _float;
- }
-
-
- public void setC(String _string) {
-
- stringC = _string;
- }
-
-
- // Enum
- public Enum handleEnum(Enum en) {
-
- System.out.println("Enum: " + en);
-
- return en;
- }
-
-
- public Enum[] handleEnumArray(Enum[] en) {
-
- for (Enum e : en) {
- System.out.println("Enum: " + e);
- }
-
- return en;
- }
-
-
- public List<Enum> handleEnumList(List<Enum> en) {
-
- for (Enum e : en) {
- System.out.println("Enum: " + e);
- }
-
- return en;
- }
-
-
- public Enum handleEnumComplex(Enum en, int i, char c) {
-
- System.out.println("Enum: " + en);
- System.out.println("Integer: " + i);
- System.out.println("Char: " + c);
-
- return en;
- }
-
-
- public Enum[] handleEnumComplex2(Enum[] en, int in, char c) {
-
- for (Enum e : en) {
- System.out.println("Enum: " + e);
- }
- System.out.println("Integer: " + in);
- System.out.println("Char: " + c);
-
- return en;
- }
-
-
- public Enum[] handleEnumTwo(Enum en1[], Enum en2[]) {
-
- for (Enum e : en1) {
- System.out.println("Enum1: " + e);
- }
- for (Enum e : en2) {
- System.out.println("Enum2: " + e);
- }
-
- return en1;
- }
-
-
- public Enum[] handleEnumThree(Enum en1[], Enum en2[], List<Struct> str1, List<Struct> str2) {
-
- for (Enum e : en1) {
- System.out.println("Enum1: " + e);
- }
- for (Enum e : en2) {
- System.out.println("Enum2: " + e);
- }
-
- return en1;
- }
-
-
- // Struct
- public Struct handleStruct(Struct str) {
-
- //System.out.println("Name: " + str.name);
- //System.out.println("Value: " + str.value);
- //System.out.println("Year: " + str.year);
-
-
- //Struct test = new Struct();
- //test.name = "Anonymous";
- //test.value = 1.33f;
- //test.year = 2016;
-
- //str = test;
-
- return str;
- }
-
-
- public Struct[] handleStructArray(Struct str[]) {
-
- for (Struct st : str) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- Struct test = new Struct();
- test.name = "Anonymous";
- test.value = 1.33f;
- test.year = 2016;
-
- str[0] = test;
-
- return str;
- }
-
-
- public List<Struct> handleStructList(List<Struct> str) {
-
- for (Struct st : str) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- Struct test = new Struct();
- test.name = "Tests";
- test.value = 1.34f;
- test.year = 2017;
-
- str.add(test);
-
- return str;
- }
-
-
- public Struct handleStructComplex(int in, char c, Struct str) {
-
- System.out.println("Name: " + str.name);
- System.out.println("Value: " + str.value);
- System.out.println("Year: " + str.year);
-
- System.out.println("Integer: " + in);
- System.out.println("Char: " + c);
-
- Struct test = new Struct();
- test.name = "Anonymous";
- test.value = 1.33f;
- test.year = 2016;
-
- str = test;
-
- return str;
- }
-
-
- public List<Struct> handleStructComplex2(int in, char c, Struct str[]) {
-
- for (Struct st : str) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- System.out.println("Integer: " + in);
- System.out.println("Char: " + c);
-
- return new ArrayList<Struct>(Arrays.asList(str));
- }
-
-
- public Enum[] handleEnumStruct(Enum en[], List<Struct> str, char c) {
-
- for (Struct st : str) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- System.out.println("Char: " + c);
-
- return en;
- }
-
-
- public List<Struct> handleStructTwo(List<Struct> str1, List<Struct> str2) {
-
- for (Struct st : str1) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- return str1;
- }
-
-
- public List<Struct> handleStructThree(List<Struct> str1, List<Struct> str2, List<Struct> str3) {
-
- for (Struct st : str1) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- return str2;
- }
-
-
- public Enum[] handleAll(Enum en[], List<Struct> str, char c, List<CallBackInterfaceWithCallBack> _cb) {
-
- for (CallBackInterfaceWithCallBack cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback objects in list!");
- }
-
- for (Struct st : str) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- System.out.println("Char: " + c);
-
- return en;
- }
-
-
- public Enum[] handleCallbackEnum(Enum en[], char c, List<CallBackInterfaceWithCallBack> _cb) {
-
- for (CallBackInterfaceWithCallBack cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback objects in list!");
- }
-
- System.out.println("Char: " + c);
-
- return en;
- }
-
-
- public Enum[] handleAllTwo(Enum en1[], Enum en2[], List<Struct> str1, List<Struct> str2, char c, List<CallBackInterfaceWithCallBack> _cb1, List<CallBackInterfaceWithCallBack> _cb2) {
-
- for (CallBackInterfaceWithCallBack cb : _cb1) {
- cblist.add(cb);
- System.out.println("Registering callback objects in list!");
- }
-
- for (Struct st : str1) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- System.out.println("Char: " + c);
-
- return en1;
- }
-
-
- // Getters
- public String sumArray(String[] newA) {
-
- String sum = "";
- for (String i : newA)
- sum = sum + i;
- return sum;
- }
-
-
- public int setAndGetA(int newA) {
-
- intA = newA;
- return intA;
- }
-
-
- public int setACAndGetA(String newC, int newA) {
-
- stringC = newC;
- intA = newA;
- return intA;
- }
-
- public static void main(String[] args) {
-
- TestClass tc = new TestClass();
- System.out.println("Get short: " + tc.getShort((short) 1234));
- }
-}
+++ /dev/null
-import java.util.Arrays;
-import java.util.List;
-import java.util.ArrayList;
-import iotruntime.master.CommunicationHandler;
-
-public class TestClassAdvanced_Stub {
-
- public static void main(String[] args) throws Exception {
-
- CommunicationHandler comHan = new CommunicationHandler(true);
- int numOfPorts = 1;
- int[] ports = comHan.getCallbackPorts(numOfPorts);
-
- int port = 5010;
- //String address = "localhost";
- //String address = "192.168.2.191"; // RPi2
- //String skeletonAddress = "128.195.136.170"; // dc-9.calit2.uci.edu
- String skeletonAddress = "128.195.204.132";
- String callbackAddress = "128.195.204.132"; // dw-2.eecs.uci.edu (this machine)
- //String skeletonAddress = "192.168.2.108"; // RPi1
- //String callbackAddress = "192.168.2.191"; // RPi2
- int rev = 0;
-
- TestClassComplete_Stub tcstub = new TestClassComplete_Stub(port, skeletonAddress, callbackAddress, rev, ports);
- /*System.out.println("==== ENUM ====");
- Enum en = Enum.APPLE;
- Enum res = tcstub.handleEnum(en);
- System.out.println("Enum member: " + res);
- Enum resComp = tcstub.handleEnumComplex(en, 23, 'c');
- System.out.println("Enum member: " + resComp);
-
- Enum[] enArr = { Enum.APPLE, Enum.ORANGE, Enum.APPLE, Enum.GRAPE };
- Enum[] resArr = tcstub.handleEnumArray(enArr);
- System.out.println("Enum members: " + Arrays.toString(resArr));
- List<Enum> enArr2 = new ArrayList(Arrays.asList(enArr));
- List<Enum> resArr2 = tcstub.handleEnumList(enArr2);
- System.out.println("Enum members: " + resArr2.toString());
- Enum[] resArr3 = tcstub.handleEnumComplex2(enArr, 23, 'c');
- System.out.println("Enum members: " + Arrays.toString(resArr3));
-
-
- System.out.println("==== STRUCT ====");
- Struct str = new Struct();
- str.name = "Rahmadi";
- str.value = 0.123f;
- str.year = 2016;
- Struct strRes = tcstub.handleStruct(str);
- System.out.println("Name: " + strRes.name);
- System.out.println("Value: " + strRes.value);
- System.out.println("Year: " + strRes.year);
- Struct strRes2 = tcstub.handleStructComplex(23, 'c', str);
- System.out.println("Name: " + strRes2.name);
- System.out.println("Value: " + strRes2.value);
- System.out.println("Year: " + strRes2.year);
- Struct str2 = new Struct();
- str2.name = "Trimananda";
- str2.value = 0.124f;
- str2.year = 2017;
- Struct[] arrStr = { str, str2 };
- Struct[] arrRet = tcstub.handleStructArray(arrStr);
- for(Struct st : arrRet) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
- List<Struct> stList = new ArrayList(Arrays.asList(arrStr));
- List<Struct> stRetList = tcstub.handleStructList(stList);
- for(Struct st : stRetList) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
- List<Struct> stRetList2 = tcstub.handleStructComplex2(23, 'c', arrStr);
- for(Struct st : stRetList2) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
- Enum[] resArr3 = tcstub.handleEnumStruct(enArr, stList, 'c');
- System.out.println("Enum members: " + Arrays.toString(resArr3));*/
-
- System.out.println("==== CALLBACKS ====");
- CallBackInterface cbSingle = new CallBack(2354);
- tcstub.registerCallback(cbSingle);
- System.out.println("Return value from callback: " + tcstub.callBack());
- /*CallBackInterface cb1 = new CallBack(23);
- CallBackInterface cb2 = new CallBack(33);
- CallBackInterface cb3 = new CallBack(43);
- CallBackInterface[] cb = { cb1, cb2, cb3 };
- tcstub.registerCallbackArray(cb);
- System.out.println("Return value from callback: " + tcstub.callBack());
- List<CallBackInterface> cblist = new ArrayList<CallBackInterface>();
- CallBackInterface cb4 = new CallBack(53); cblist.add(cb4);
- CallBackInterface cb5 = new CallBack(63); cblist.add(cb5);
- CallBackInterface cb6 = new CallBack(73); cblist.add(cb6);
-// tcstub.registerCallbackList(cblist);
-// System.out.println("Return value from callback: " + tcstub.callBack());
-
- tcstub.registerCallbackComplex(23, cblist, 0.1234);
- System.out.println("Return value from callback: " + tcstub.callBack());
- Enum[] resArr4 = tcstub.handleAll(enArr, stList, 'c', cblist);
- System.out.println("Enum members: " + Arrays.toString(resArr4));
-
- Enum[] resArr5 = tcstub.handleCallbackEnum(enArr, 'c', cblist);
- System.out.println("Enum members: " + Arrays.toString(resArr5));
- //Enum[] resArr6 = tcstub.handleAllTwo(enArr, stList, stList, enArr, 'c', cblist, cblist);
-// Enum[] resArr6 = tcstub.handleAllTwo(enArr, enArr, stList, stList, 'c', cblist, cblist);
-// System.out.println("Enum members: " + Arrays.toString(resArr6));
- Enum[] resArr7 = tcstub.handleEnumTwo(enArr, enArr);
- System.out.println("Enum members: " + Arrays.toString(resArr7));
- Enum[] resArr8 = tcstub.handleEnumThree(enArr, enArr, stList, stList);
- System.out.println("Enum members: " + Arrays.toString(resArr8));
- List<Struct> stRetList2 = tcstub.handleStructTwo(stList, stList);
- for(Struct st : stRetList2) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
- List<Struct> stRetList3 = tcstub.handleStructThree(stList, stList, stList);
- for(Struct st : stRetList3) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }*/
- }
-}
+++ /dev/null
-import java.util.Arrays;
-import java.util.List;
-import java.util.ArrayList;
-import iotruntime.master.CommunicationHandler;
-
-public class TestClassCallbacks_Stub {
-
- public static void main(String[] args) throws Exception {
-
- CommunicationHandler comHan = new CommunicationHandler(true);
- int numOfPorts = 2;
- //int[] ports = comHan.getCallbackPorts(numOfPorts);
-
- int localportsend = 5011;
- int localportrecv = 6011;
- int portsend = 5000;
- int portrecv = 6000;
- //String address = "localhost";
- //String address = "192.168.2.191"; // RPi2
- //String skeletonAddress = "128.195.136.170"; // dc-9.calit2.uci.edu
- String skeletonAddress = "128.195.204.132";
- String callbackAddress = "128.195.204.132"; // dw-2.eecs.uci.edu (this machine)
- //String skeletonAddress = "192.168.2.108"; // RPi1
- //String callbackAddress = "192.168.2.191"; // RPi2
- int rev = 0;
-
- TestClassComplete_Stub tcstub = new TestClassComplete_Stub(localportsend, localportrecv, portsend, portrecv,
- skeletonAddress, rev);
- System.out.println("==== CALLBACKS ====");
- CallBackInterface cbSingle = new CallBack(2354);
- tcstub.registerCallback(cbSingle);
- System.out.println("Registered callback!");
-// CallBackInterface cbSingle1 = new CallBack(2356);
-// tcstub.registerCallback(cbSingle1);
-// System.out.println("Registered callback!");
-// CallBackInterface cbSingle2 = new CallBack(2360);
-// tcstub.registerCallback(cbSingle2);
-// System.out.println("Registered callback!");
- /*CallBackInterface cb1 = new CallBack(23);
- CallBackInterface cb2 = new CallBack(33);
- CallBackInterface cb3 = new CallBack(43);
- CallBackInterface[] cb = { cb1, cb2, cb3 };
- tcstub.registerCallbackArray(cb);
- List<CallBackInterface> cblist = new ArrayList<CallBackInterface>();
- CallBackInterface cb4 = new CallBack(53); cblist.add(cb4);
- CallBackInterface cb5 = new CallBack(63); cblist.add(cb5);
- CallBackInterface cb6 = new CallBack(73); cblist.add(cb6);
- tcstub.registerCallbackList(cblist);*/
- /*Enum[] enArr = { Enum.APPLE, Enum.ORANGE, Enum.APPLE, Enum.GRAPE };
- List<Enum> enArr2 = new ArrayList(Arrays.asList(enArr));
- List<Enum> resArr2 = tcstub.handleEnumList(enArr2);
- System.out.println("Enum members: " + resArr2.toString());*/
- Struct str = new Struct();
- str.name = "Rahmadi";
- str.value = 0.123f;
- str.year = 2016;
- Struct str2 = new Struct();
- str2.name = "Trimananda";
- str2.value = 0.124f;
- str2.year = 2017;
- Struct[] arrStr = { str, str2 };
- Struct[] arrRet = tcstub.handleStructArray(arrStr);
- for(Struct st : arrRet) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
-// System.out.println("Return value from callback 1: " + tcstub.callBack() + "\n\n");
-// System.out.println("\n\nCalling short one more time value: " + tcstub.getShort((short)4576) + "\n\n");
-// System.out.println("Return value from callback 2: " + tcstub.callBack() + "\n\n");
-// System.out.println("\n\nCalling short one more time value: " + tcstub.getShort((short)1233) + "\n\n");
-// System.out.println("\n\nCalling short one more time value: " + tcstub.getShort((short)1321) + "\n\n");
- while(true) {}
- }
-}
+++ /dev/null
-public class TestClassProfiling implements TestClassInterface {
-
- /**
- * Constructors
- */
- public TestClassProfiling() {
-
- }
-
-
- // Arrays
- public byte[] getByteArray(byte[] in) {
-
- return in;
- }
-}
\ No newline at end of file
+++ /dev/null
-import java.util.Arrays;
-import java.util.List;
-import java.util.ArrayList;
-import iotruntime.master.CommunicationHandler;
-
-public class TestClass_ProfilingStub {
-
- public static void main(String[] args) throws Exception {
- CommunicationHandler comHan = new CommunicationHandler(true);
- int numOfPorts = 2;
- //int[] ports = comHan.getCallbackPorts(numOfPorts);
-
- //int localportsend = 5011;
- //int localportrecv = 6011;
- int portsend = 5000;
- int portrecv = 6000;
- //String skeletonAddress = "128.195.136.163";
- //String skeletonAddress = "128.195.204.132";
- String skeletonAddress = "192.168.2.108";
- //String callbackAddress = "128.195.204.132"; // dw-2.eecs.uci.edu (this machine)
- String callbackAddress = "192.168.2.191";
- int rev = 0;
-
- //TestClassComplete_Stub tcstub = new TestClassComplete_Stub(localportsend, localportrecv, portsend, portrecv,
- //skeletonAddress, rev);
- TestClassComplete_Stub tcstub = new TestClassComplete_Stub(0, 0, portsend, portrecv, skeletonAddress, rev);
- //byte[] in1 = { 68, 69 };
- //int counter = 100;
- //byte[] in1 = new byte[counter];
- //for (int i=0; i<counter; i++)
- // in1[i] = 68;
- System.out.println("==== STRUCT ====");
- Struct str = new Struct();
- str.name = "Rahmadi";
- str.value = 0.123f;
- str.year = 2016;
- // PROFILING
- long start = 0;
- long end = 0;
- //byte[] returned = null;
- int exp = 10;
- long avg = 0;
- //Struct strRes = null;
- long longVar = 0;
- long inVar = 1234;
- double doubleVar = 0;
- double inDouble = 1234.1234;
- for (int i = 0; i < exp; i++) {
- start = System.currentTimeMillis();
- //start = System.nanoTime();
- //System.out.println("Return value: " + Arrays.toString(tcstub.getByteArray(in1)));
- //returned = tcstub.getByteArray(in1);
- //strRes = tcstub.handleStruct(str);
- //longVar = tcstub.getLong(inVar);
- doubleVar = tcstub.getDouble(inDouble);
- end = System.currentTimeMillis();
- //end = System.nanoTime();
- //long res = (end - start) / 1000;
- long res = (end - start);
- System.out.println("\n\n ==> Time: " + res);
- //System.out.println("\n\n ==> Time: " + (end - start));
- avg = avg + res;
- }
- System.out.println("Average: " + (avg / exp));
- }
-
-}
+++ /dev/null
-import java.net.InetAddress;
-
-public class TestClass_Skeleton {
-
- public static void main(String[] args) throws Exception {
-
- int portsend = 5000;
- int portrecv = 6000;
- String callbackAddress = InetAddress.getLocalHost().getHostAddress();
- //TestClassProfiling tc = new TestClassProfiling();
- TestClass tc = new TestClass();
- TestClassInterface_Skeleton tcSkel = new TestClassInterface_Skeleton(tc, portsend, portrecv);
- }
-}
+++ /dev/null
-import java.util.Arrays;
-import java.util.List;
-import java.util.ArrayList;
-import iotruntime.master.CommunicationHandler;
-
-public class TestClass_Stub {
-
- public static void main(String[] args) throws Exception {
-
- CommunicationHandler comHan = new CommunicationHandler(true);
- int numOfPorts = 1;
- int[] ports = comHan.getCallbackPorts(numOfPorts);
-
- int port = 5010;
- String address = "localhost";
- //String address = "128.195.136.170"; // dc-9.calit2.uci.edu
- int rev = 0;
-
- System.out.println("Allocated ports: " + Arrays.toString(ports));
-
- TestClassComplete_Stub tcstub = new TestClassComplete_Stub(port, address, rev, ports);
- System.out.println("==== SINGLE ====");
- System.out.println("Return value: " + tcstub.getByte((byte)68));
- System.out.println("Return value: " + tcstub.getShort((short)1234));
- System.out.println("Return value: " + tcstub.getLong(12345678l));
- System.out.println("Return value: " + tcstub.getFloat(12.345f));
- System.out.println("Return value: " + tcstub.getDouble(12345.678));
- System.out.println("Return value: " + tcstub.getBoolean(true));
- System.out.println("Return value: " + tcstub.getChar('c'));
-
- System.out.println("==== ARRAY ====");
- byte[] in1 = { 68, 69 };
- System.out.println("Return value: " + Arrays.toString(tcstub.getByteArray(in1)));
- short[] in2 = { (short)1234, (short)1235 };
- System.out.println("Return value: " + Arrays.toString(tcstub.getShortArray(in2)));
- long[] in3 = { 12345678l, 12356782l };
- System.out.println("Return value: " + Arrays.toString(tcstub.getLongArray(in3)));
- float[] in4 = { 12.345f, 12.346f };
- System.out.println("Return value: " + Arrays.toString(tcstub.getFloatArray(in4)));
- double[] in5 = { 12345.678, 12345.543 };
- System.out.println("Return value: " + Arrays.toString(tcstub.getDoubleArray(in5)));
- boolean[] in6 = { true, false };
- System.out.println("Return value: " + Arrays.toString(tcstub.getBooleanArray(in6)));
- char[] in7 = { 'c', 'e' };
- System.out.println("Return value: " + Arrays.toString(tcstub.getCharArray(in7)));
-
- System.out.println("==== LIST ====");
- List<Byte> inl1 = Arrays.asList(new Byte[] { 68, 69 });
- System.out.println("Return value: " + tcstub.getByteList(inl1));
- List<Short> inl2 = Arrays.asList(new Short[] { (short)1234, (short)1235 });
- System.out.println("Return value: " + tcstub.getShortList(inl2));
- List<Long> inl3 = Arrays.asList(new Long[] { 12345678l, 12356782l });
- System.out.println("Return value: " + tcstub.getLongList(inl3));
- List<Float> inl4 = Arrays.asList(new Float[] { 12.345f, 12.346f });
- System.out.println("Return value: " + tcstub.getFloatList(inl4));
- List<Double> inl5 = Arrays.asList(new Double[] { 12345.678, 12345.543 });
- System.out.println("Return value: " + tcstub.getDoubleList(inl5));
- List<Boolean> inl6 = Arrays.asList(new Boolean[] { true, false });
- System.out.println("Return value: " + tcstub.getBooleanList(inl6));
- List<Character> inl7 = Arrays.asList(new Character[] { 'c', 'e' });
- System.out.println("Return value: " + tcstub.getCharList(inl7));
-
- System.out.println("==== ENUM ====");
- Enum en = Enum.APPLE;
- Enum res = tcstub.handleEnum(en);
- System.out.println("Enum member: " + res);
- Enum[] enArr = { Enum.APPLE, Enum.ORANGE, Enum.APPLE, Enum.GRAPE };
- Enum[] resArr = tcstub.handleEnumArray(enArr);
- System.out.println("Enum members: " + Arrays.toString(resArr));
- List<Enum> enArr2 = new ArrayList(Arrays.asList(enArr));
- List<Enum> resArr2 = tcstub.handleEnumList(enArr2);
- System.out.println("Enum members: " + resArr2.toString());
-
- System.out.println("==== STRUCT ====");
- Struct str = new Struct();
- str.name = "Rahmadi";
- str.value = 0.123f;
- str.year = 2016;
- Struct strRes = tcstub.handleStruct(str);
- System.out.println("Name: " + strRes.name);
- System.out.println("Value: " + strRes.value);
- System.out.println("Year: " + strRes.year);
- Struct str2 = new Struct();
- str2.name = "Trimananda";
- str2.value = 0.124f;
- str2.year = 2017;
- Struct[] arrStr = { str, str2 };
- Struct[] arrRet = tcstub.handleStructArray(arrStr);
- for(Struct st : arrRet) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
- List<Struct> stList = new ArrayList(Arrays.asList(arrStr));
- List<Struct> stRetList = tcstub.handleStructList(stList);
- for(Struct st : stRetList) {
- System.out.println("Name: " + st.name);
- System.out.println("Value: " + st.value);
- System.out.println("Year: " + st.year);
- }
-
- System.out.println("==== CALLBACKS ====");
- CallBackInterface cbSingle = new CallBack(2354);
- tcstub.registerCallback(cbSingle);
- System.out.println("Return value from callback: " + tcstub.callBack());
- //CallBackInterface cbSingle2 = new CallBack(2355);
- //tcstub.registerCallback(cbSingle2);
- //System.out.println("Return value from callback: " + tcstub.callBack());
- CallBackInterface cb1 = new CallBack(23);
- CallBackInterface cb2 = new CallBack(33);
- CallBackInterface cb3 = new CallBack(43);
- CallBackInterface[] cb = { cb1, cb2, cb3 };
- tcstub.registerCallbackArray(cb);
- System.out.println("Return value from callback: " + tcstub.callBack());
- List<CallBackInterface> cblist = new ArrayList<CallBackInterface>();
- CallBackInterface cb4 = new CallBack(53); cblist.add(cb4);
- CallBackInterface cb5 = new CallBack(63); cblist.add(cb5);
- CallBackInterface cb6 = new CallBack(73); cblist.add(cb6);
- tcstub.registerCallbackList(cblist);
- System.out.println("Return value from callback: " + tcstub.callBack());
-
- System.out.println("==== OTHERS ====");
- System.out.println("Return value: " + tcstub.getA());
- System.out.println("Return value: " + tcstub.setAndGetA(123));
- System.out.println("Return value: " + tcstub.setACAndGetA("string", 123));
- System.out.println("Return value: " + tcstub.sumArray(new String[] { "123", "456", "987" }));
-
-
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public class CallBack implements CallBackInterface {
-
- /**
- * Class Properties
- */
- private int intA;
-
- /**
- * Constructors
- */
- public CallBack(int _i) {
-
- intA = _i;
- }
-
-
- public int printInt() {
-
- System.out.println("Integer: " + intA);
- return intA;
- }
-
-
- public void setInt(int _i) {
-
- intA = _i;
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public interface CallBackInterface {
-
- public int printInt();
- public void setInt(int _i);
-
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import java.util.Set;
-import java.util.Arrays;
-import iotrmi.Java.IoTRMIObject;
-
-public class CallBack_CBSkeleton implements CallBackInterface {
-
- private int objectId = 0; // Default value is 0
- private CallBackInterface cb;
-
-
- /**
- * Constructors
- */
- public CallBack_CBSkeleton(CallBackInterface _cb, int _objectId) throws
- ClassNotFoundException, InstantiationException,
- IllegalAccessException, IOException {
-
- cb = _cb;
- objectId = _objectId;
- System.out.println("Creating CallBack_Skeleton and waiting!");
- }
-
-
- public int printInt() {
- return cb.printInt();
- }
-
-
- public void ___printInt(IoTRMIObject rmiObj) throws IOException {
- Object retObj = printInt();
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public void setInt(int _i) {
- cb.setInt(_i);
- }
-
-
- public void ___setInt(IoTRMIObject rmiObj) {
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- setInt((int) paramObj[0]);
- }
-
-
- public void invokeMethod(IoTRMIObject rmiObj) throws IOException {
-
- int methodId = rmiObj.getMethodId();
-
- switch (methodId) {
- case 0: ___printInt(rmiObj); break;
- case 1: ___setInt(rmiObj); break;
- default:
- throw new Error("Method Id not recognized!");
- }
- }
-
-
- public static void main(String[] args) throws Exception {
-
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import iotrmi.Java.IoTRMICall;
-
-public class CallBack_CBStub implements CallBackInterface {
-
- /**
- * Class Properties
- */
- private IoTRMICall rmiCall;
-
- private int objectId = 0; // Default value is 0
-
- /**
- * Constructors
- */
- public CallBack_CBStub(IoTRMICall _rmiCall, int _objectId) throws IOException {
-
- objectId = _objectId;
- rmiCall = _rmiCall;
- }
-
-
- public int printInt() {
-
- int methodId = 0;
- Class<?> retType = int.class;
- Class<?>[] paramCls = new Class<?>[] { };
- Object[] paramObj = new Object[] { };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (int)retObj;
- }
-
-
- public void setInt(int _i) {
-
- int methodId = 1;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { _i };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- public static void main(String[] args) throws Exception {
-
- int port = 5010;
- String address = "localhost";
- int rev = 0;
-
- CallBack_Stub cbstub = new CallBack_Stub(port, address, rev);
- cbstub.setInt(23);
- cbstub.printInt();
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import java.util.Set;
-import java.util.Arrays;
-import iotrmi.Java.IoTRMIObject;
-
-public class CallBack_Skeleton implements CallBackInterface {
-
- private int objectId = 0; // Default value is 0
- private CallBackInterface cb;
- private IoTRMIObject rmiObj;
-
-
- /**
- * Constructors
- */
- public CallBack_Skeleton(CallBackInterface _cb, int _port) throws
- ClassNotFoundException, InstantiationException,
- IllegalAccessException, IOException {
-
- cb = _cb;
- System.out.println("Creating CallBack_Skeleton and waiting!");
- rmiObj = new IoTRMIObject(_port);
- ___waitRequestInvokeMethod();
- }
-
-
- public int printInt() {
- return cb.printInt();
- }
-
-
- public void ___printInt() throws IOException {
- Object retObj = printInt();
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public void setInt(int _i) {
- cb.setInt(_i);
- }
-
-
- public void ___setInt() {
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- setInt((int) paramObj[0]);
- }
-
-
- private void ___waitRequestInvokeMethod() throws IOException {
-
- // Loop continuously waiting for incoming bytes
- while (true) {
-
- rmiObj.getMethodBytes();
- int objId = rmiObj.getObjectId();
- if (objId == objectId) {
- // Multiplex based on object Id
- rmiObj.getMethodBytes();
- int methodId = rmiObj.getMethodId();
-
- switch (methodId) {
- case 0: ___printInt(); break;
- case 1: ___setInt(); break;
- default:
- throw new Error("Method Id not recognized!");
- }
- }
- }
- }
-
-
- public static void main(String[] args) throws Exception {
-
- int port = 5010;
- CallBack cb = new CallBack(23);
- CallBack_Skeleton cbSkel = new CallBack_Skeleton(cb, port);
- //cbSkel.waitRequestInvokeMethod();
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import iotrmi.Java.IoTRMICall;
-
-public class CallBack_Stub implements CallBackInterface {
-
- /**
- * Class Properties
- */
- private IoTRMICall rmiCall;
-
- private int objectId = 0; // Default value is 0
-
- /**
- * Constructors
- */
- public CallBack_Stub(int _port, String _address, int _rev) throws IOException {
-
- rmiCall = new IoTRMICall(_port, _address, _rev);
- }
-
-
- public int printInt() {
-
- int methodId = 0;
- Class<?> retType = int.class;
- Class<?>[] paramCls = new Class<?>[] { };
- Object[] paramObj = new Object[] { };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (int)retObj;
- }
-
-
- public void setInt(int _i) {
-
- int methodId = 1;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { _i };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- public static void main(String[] args) throws Exception {
-
- int port = 5010;
- String address = "localhost";
- int rev = 0;
-
- CallBack_Stub cbstub = new CallBack_Stub(port, address, rev);
- cbstub.setInt(23);
- cbstub.printInt();
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public enum EnumJ {
-
- APPLE,
- ORANGE,
- GRAPE
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public class EnumMain {
-
- public static void main (String[] args) {
-
- // Enum to int
- int enum1 = EnumJ.APPLE.ordinal();
- System.out.println("Enum 1: " + enum1);
- int enum2 = EnumJ.ORANGE.ordinal();
- System.out.println("Enum 2: " + enum2);
- int enum3 = EnumJ.GRAPE.ordinal();
- System.out.println("Enum 3: " + enum3);
-
- // Int to enum
- EnumJ[] enumJ = EnumJ.values();
- System.out.println("Enum 1: " + enumJ[enum1]);
- System.out.println("Enum 1: " + enumJ[enum2]);
- System.out.println("Enum 1: " + enumJ[enum3]);
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public class StructJ {
-
- public static String name;
- public static float value;
- public static int year;
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-public class StructMain {
-
- public static void main (String[] args) {
-
- StructJ data = new StructJ();
- data.name = "Rahmadi";
- data.value = 0.123f;
- data.year = 2016;
-
- System.out.println("Name: " + data.name);
- System.out.println("Value: " + data.value);
- System.out.println("Year: " + data.year);
- }
-}
-
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.util.Set;
-import java.util.List;
-import java.util.ArrayList;
-
-public class TestClass implements TestClassInterface {
-
- /**
- * Class Properties
- */
- private int intA;
- private float floatB;
- private String stringC;
- private CallBackInterface cb;
- private List<CallBackInterface> cblist;
-
- /**
- * Constructors
- */
- public TestClass() {
-
- intA = 1;
- floatB = 2;
- stringC = "345";
- cb = null;
- cblist = new ArrayList<CallBackInterface>();
- }
-
-
- public TestClass(int _int, float _float, String _string) {
-
- intA = _int;
- floatB = _float;
- stringC = _string;
- cb = null;
- cblist = new ArrayList<CallBackInterface>();
- }
-
-
- public void setA(int _int) {
-
- intA = _int;
- }
-
-
- public void setB(float _float) {
-
- floatB = _float;
- }
-
-
- public void setC(String _string) {
-
- stringC = _string;
- }
-
-
- // Getters
- public String sumArray(String[] newA) {
-
- String sum = "";
- for (String i : newA)
- sum = sum + i;
- return sum;
- }
-
-
- public int setAndGetA(int newA) {
-
- intA = newA;
- return intA;
- }
-
-
- public int setACAndGetA(String newC, int newA) {
-
- stringC = newC;
- intA = newA;
- return intA;
- }
-
-
- public void registerCallback(CallBackInterface _cb) {
-
- cb = _cb;
- }
-
-
- public void registerCallback(CallBackInterface[] _cb) {
-
- for (CallBackInterface cb : _cb) {
- cblist.add(cb);
- System.out.println("Registering callback object!");
- }
- }
-
-
- //public int callBack() {
- // return cb.printInt();
- //}
-
-
- public int callBack() {
-
- int sum = 0;
- for (CallBackInterface cb : cblist) {
- sum = sum + cb.printInt();
- }
-
- /*final CallBackInterface cb1 = cblist.get(1);
- final CallBackInterface cb2 = cblist.get(2);
-
- Thread thread1 = new Thread() {
- public void run() {
- try{
- for(int i = 0; i < 10; i++) {
- cb1.printInt();
- Thread.sleep(1000);
- }
- } catch (Exception ex){
- ex.printStackTrace();
- throw new Error("Error running thread!");
- }
- }
- };
- thread1.start();
-
- Thread thread2 = new Thread() {
- public void run() {
- try{
- for(int i = 0; i < 10; i++) {
- cb2.printInt();
- Thread.sleep(1000);
- }
- } catch (Exception ex){
- ex.printStackTrace();
- throw new Error("Error running thread!");
- }
- }
- };
- thread2.start();
-
- return 1;*/
- return sum;
- }
-
- public StructJ[] handleStruct(StructJ[] data) {
-
- for (StructJ str : data) {
- System.out.println("Name: " + str.name);
- System.out.println("Value: " + str.value);
- System.out.println("Year: " + str.year);
- }
-
- StructJ test = new StructJ();
- test.name = "Anonymous";
- test.value = 1.33f;
- test.year = 2016;
-
- data[0] = test;
-
- return data;
- }
-
-
- public EnumJ[] handleEnum(EnumJ[] en) {
-
- for (EnumJ e : en) {
- System.out.println("Enum: " + e);
- }
-
- return en;
- }
-
-
- public static void main(String[] args) {
-
- //TestClass tc = new TestClass();
- //CallBack cb = new CallBack(3);
-
- //tc.registerCallback(cb);
- //System.out.println("Return value: " + tc.callBack());
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.util.Set;
-
-public interface TestClassInterface {
-
- public class StructJ {
-
- public static String name;
- public static float value;
- public static int year;
- }
-
- public enum EnumJ {
-
- APPLE,
- ORANGE,
- GRAPE
- }
-
- public void setA(int _int);
- public void setB(float _float);
- public void setC(String _string);
- public String sumArray(String[] newA);
- public int setAndGetA(int newA);
- public int setACAndGetA(String newC, int newA);
- public void registerCallback(CallBackInterface _cb);
- public void registerCallback(CallBackInterface[] _cb);
- public int callBack();
- public StructJ[] handleStruct(StructJ[] data);
- public EnumJ[] handleEnum(EnumJ[] en);
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import java.util.List;
-
-import iotrmi.Java.IoTRMIObject;
-import iotrmi.Java.IoTRMICall;
-
-public class TestClass_Skeleton implements TestClassInterface {
-
- /**
- * Class Constants
- */
- private TestClassInterface tc;
- private int port;
- private IoTRMIObject rmiObj;
-
- // Callback stuff
- private static int objIdCnt = 0; // Counter for callback object Ids
- private IoTRMICall rmiCall;
- private CallBackInterface cbstub;
-
- // Object permission
- private int object0Id = 0;
- private static Integer[] object0Permission = { 0, 1, 2, 3, 4, 5 };
- private List<Integer> set0Allowed;
-
-
- /**
- * Constructors
- */
- public TestClass_Skeleton(TestClass _tc, int _port) throws
- ClassNotFoundException, InstantiationException,
- IllegalAccessException, IOException {
-
- tc = _tc;
- port = _port;
- rmiObj = new IoTRMIObject(_port);
- set0Allowed = Arrays.asList(object0Permission);
- ___waitRequestInvokeMethod();
- }
-
-
- public void setA(int _int) {
-
- tc.setA(_int);
- }
-
-
- public void ___setA() {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- setA((int) paramObj[0]);
- }
-
-
- public void setB(float _float) {
-
- tc.setB(_float);
- }
-
-
- public void ___setB() {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { float.class },
- new Class<?>[] { null });
- setB((float) paramObj[0]);
- }
-
-
- public void setC(String _string) {
-
- tc.setC(_string);
- }
-
-
- public void ___setC() {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { String.class },
- new Class<?>[] { null });
- setC((String) paramObj[0]);
- }
-
-
- public String sumArray(String[] newA) {
-
- return tc.sumArray(newA);
- }
-
-
- public void ___sumArray() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { String[].class },
- new Class<?>[] { null });
- Object retObj = sumArray((String[]) paramObj[0]);
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public int setAndGetA(int newA) {
-
- return tc.setAndGetA(newA);
- }
-
-
- public void ___setAndGetA() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- Object retObj = setAndGetA((int) paramObj[0]);
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public int setACAndGetA(String newC, int newA) {
-
- return tc.setACAndGetA(newC, newA);
- }
-
-
- public void ___setACAndGetA() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { String.class, int.class },
- new Class<?>[] { null, null });
- Object retObj = setACAndGetA((String) paramObj[0], (int) paramObj[1]);
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public void registerCallback(CallBackInterface _cb) {
-
- tc.registerCallback(_cb);
- }
-
-
- public void ___registerCallback() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },
- new Class<?>[] { null, null, null });
- CallBackInterface cbstub = new CallBack_Stub((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);
- registerCallback((CallBackInterface) cbstub);
- }
-
-
- public void registerCallback(CallBackInterface[] _cb) {
-
- tc.registerCallback(_cb);
- }
-
-
- // Use 4 underscores because this is a second instance of registerCallback
- public void ____registerCallback() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- int numStubs = (int) paramObj[0];
- CallBackInterface[] stub = new CallBackInterface[numStubs];
- for (int objId = 0; objId < numStubs; objId++) {
- stub[objId] = new CallBack_CBStub(rmiCall, objIdCnt);
- objIdCnt++;
- }
- registerCallback(stub);
- }
-
-
- public void ___regCB() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },
- new Class<?>[] { null, null, null });
- //String[] methodSignatures = CallBack_CBStub.getMethodSignatures();
- rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);
- System.out.println("Creating a new IoTRMICall object");
- }
-
-
- public int callBack() {
-
- return tc.callBack();
- }
-
-
- public void ___callBack() throws IOException {
-
- Object retObj = callBack();
- rmiObj.sendReturnObj(retObj);
- }
-
-
- public StructJ[] handleStruct(StructJ[] data) {
-
- return tc.handleStruct(data);
- }
-
-
- public int ___structSize() {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class },
- new Class<?>[] { null });
- return (int) paramObj[0];
- }
-
-
- public void ___handleStruct(int structsize1) throws IOException {
-
- Class<?>[] paramCls = new Class<?>[3*structsize1];
- Class<?>[] paramClsVal = new Class<?>[3*structsize1];
- int pos = 0;
- for(int i=0; i < structsize1; i++) {
- paramCls[pos] = String.class;
- paramClsVal[pos++] = null;
- paramCls[pos] = float.class;
- paramClsVal[pos++] = null;
- paramCls[pos] = int.class;
- paramClsVal[pos++] = null;
- }
- Object[] paramObj = rmiObj.getMethodParams(paramCls,
- paramClsVal);
- StructJ[] data = new StructJ[structsize1];
- for (int i=0; i < structsize1; i++) {
- data[i] = new StructJ();
- }
- pos = 0;
- for(int i=0; i < structsize1; i++) {
- data[i].name = (String) paramObj[pos++];
- data[i].value = (float) paramObj[pos++];
- data[i].year = (int) paramObj[pos++];
- }
- // Just the following if there is no returned value
- //tc.handleStruct(data);
- StructJ[] retStruct = tc.handleStruct(data);
- // Return length first
- int structsize2 = retStruct.length;
- Object retObj = structsize2;
- rmiObj.sendReturnObj(retObj);
- // Send the actual struct members
- // Calculate the size of the array
- Class<?>[] retCls = new Class<?>[3*structsize2];
- Object[] retObj2 = new Object[3*structsize2];
- // Handle with for loop
- pos = 0;
- for(int i = 0; i < structsize2; i++) {
- retCls[pos] = String.class;
- retObj2[pos++] = data[i].name;
- retCls[pos] = float.class;
- retObj2[pos++] = data[i].value;
- retCls[pos] = int.class;
- retObj2[pos++] = data[i].year;
- }
- rmiObj.sendReturnObj(retCls, retObj2);
- }
-
-
- public EnumJ[] handleEnum(EnumJ[] en) {
-
- return tc.handleEnum(en);
- }
-
-
- public void ___handleEnum() throws IOException {
-
- Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int[].class },
- new Class<?>[] { null });
- // Encoder/decoder
- int paramInt[] = (int[]) paramObj[0];
- int enumSize1 = paramInt.length;
- EnumJ[] enumJ = EnumJ.values();
- EnumJ[] data = new EnumJ[enumSize1];
- for (int i=0; i < enumSize1; i++) {
- data[i] = enumJ[paramInt[i]];
- }
- // if void, just "handleEnum(data)"
- // this is when we have return value EnumJ[]
- EnumJ[] retEnum = handleEnum(data);
- // Get length first
- int enumSize2 = retEnum.length;
- // Now send the array of integers
- int[] retEnumInt = new int[enumSize2];
- for (int i=0; i < enumSize2; i++) {
- retEnumInt[i] = retEnum[i].ordinal();
- }
- Object retObj = retEnumInt;
- rmiObj.sendReturnObj(retObj);
- }
-
-
- private void ___waitRequestInvokeMethod() throws IOException {
-
- // Struct size
- int structSize1 = 0;
- int enumSize1 = 0;
- // Loop continuously waiting for incoming bytes
- while (true) {
-
- rmiObj.getMethodBytes();
- int _objectId = rmiObj.getObjectId();
- int methodId = rmiObj.getMethodId();
- if (_objectId == object0Id) {
- // Multiplex based on object Id
- // Complain if the method is not allowed
- if (!set0Allowed.contains(methodId))
- throw new Error("TestClass_Skeleton: This object is not allowed to access method " + methodId);
- // If we have more than 1 object Id...
- //else if (_objectId == object1Id) {
-
- } else
- throw new Error("TestClass_Skeleton: Unrecognizable object Id: " + _objectId);
-
- switch (methodId) {
-
- case 0: ___setA(); break;
- case 1: ___setB(); break;
- case 2: ___setC(); break;
- case 3: ___sumArray(); break;
- case 4: ___setAndGetA(); break;
- case 5: ___setACAndGetA(); break;
- case 6: ___callBack(); break;
- case 7: ___registerCallback(); break;
- case 8: ____registerCallback(); break;
- // Special option to register callback
- case 9: ___regCB(); break;
- // Struct handling (3 is the size of the struct)
- case 10: ___handleStruct(structSize1); break;
- case 11: structSize1 = ___structSize(); break;
- case 12: ___handleEnum(); break;
- default:
- throw new Error("Method Id " + methodId + " not recognized!");
- }
-
- }
- }
-
-
- public static void main(String[] args) throws Exception {
-
- int port = 5010;
- TestClass tc = new TestClass(3, 5f, "7911");
- TestClass_Skeleton tcSkel = new TestClass_Skeleton(tc, port);
-
- }
-}
+++ /dev/null
-package iotrmi.Java.sample;
-
-import java.io.IOException;
-import iotrmi.Java.IoTRMICall;
-import iotruntime.master.CommunicationHandler;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.ArrayList;
-
-import iotrmi.Java.IoTRMIObject;
-
-public class TestClass_Stub implements TestClassInterface {
-
- /**
- * Class Properties
- */
- private IoTRMICall rmiCall;
- private IoTRMIObject rmiObj;
- private String address;
- private int[] ports;
-
- /**
- * Class Constants
- */
- private int objectId = 0; // Default value is 0
- // This is permission system for callback objects
- private static Integer[] object0Permission = { 0, 1 }; // object0 is the callback object
- private List<Integer> set0Allowed;
-
- /**
- * Properties and constants for Callbacks!
- */
- private List<CallBackInterface> listCBObj;
- private final static int NUM_CB_OBJ = 1;
- private static int objIdCnt = 0; // Counter for callback object Ids
-
-
- /**
- * Constructors
- */
- public TestClass_Stub(int _port, String _address, int _rev, int[] _ports) throws Exception {
-
- address = _address;
- ports = _ports;
- rmiCall = new IoTRMICall(_port, _address, _rev);
-
- set0Allowed = Arrays.asList(object0Permission);
-
- // Only for callbacks!!!
- listCBObj = new ArrayList<CallBackInterface>();
- ___initCallBack();
- }
-
-
- /**
- * Instantiation of callback objects
- */
- public static int numCallbackObjects() {
-
- return NUM_CB_OBJ; // Generated by the IoTCompiler
- }
-
-
- // Initialize callback
- public void ___initCallBack() {
-
- Thread thread = new Thread() {
- public void run() {
- try{
- rmiObj = new IoTRMIObject(ports[0]);
- while (true) {
- byte[] method = rmiObj.getMethodBytes();
- // Permission checking
- int methId = IoTRMIObject.getMethodId(method);
- if (!set0Allowed.contains(methId))
- throw new Error("CallBack_CBSkeleton: This object is not allowed to access method " + methId);
-
- int objId = IoTRMIObject.getObjectId(method);
- CallBack_CBSkeleton skel = (CallBack_CBSkeleton) listCBObj.get(objId);
- if (skel != null) {
- //rmiObj.setMethodBytes(method);
- skel.invokeMethod(rmiObj);
- }
- }
- } catch (Exception ex){
- ex.printStackTrace();
- throw new Error("Error instantiating class CallBack_Skeleton!");
- }
- }
- };
- thread.start();
-
- //String sign = "registercallback"; // can be any string
- int methodId = 9;
- Class<?> retType = void.class;
- // port, address, rev
- Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };
- Object[] paramObj = new Object[] { ports[0], address, 0 };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- // Single callback handling
- public void registerCallback(CallBackInterface _cb) {
-
- /*Thread thread = new Thread() {
- public void run() {
- try{
- CallBack_Skeleton cbskel = new CallBack_Skeleton(_cb, ports[0]);
- } catch (Exception ex){
- ex.printStackTrace();
- throw new Error("Error instantiating class CallBack_Skeleton!");
- }
- }
- };
- thread.start();
-
- String sign = "voidregisterCallBack(CallBackInterface)";
- Class<?> retType = void.class;
- // port, address, and rev
- Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };
- Object[] paramObj = new Object[] { ports[0], address, 0 };
- rmiCall.remoteCall(objectId, sign, retType, null, null, paramCls, paramObj);*/
- }
-
-
- public void registerCallback(CallBackInterface[] _cb) {
-
- try {
- //for (int objId = 0; objId < _cb.length; objId++) {
- for (CallBackInterface cb : _cb) {
- CallBack_CBSkeleton skel = new CallBack_CBSkeleton(cb, objIdCnt++);
- listCBObj.add(skel);
- }
- } catch (Exception ex){
- ex.printStackTrace();
- throw new Error("Class not found / instantiation / illegal access / IO error!");
- }
-
- //String sign = "voidregisterCallBack(CallBackInterface[])";
- int methodId = 8;
- Class<?> retType = void.class;
- // port, address, rev, and number of objects
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { _cb.length };
- //rmiCall.remoteCall(objectId, sign, retType, null, null, paramCls, paramObj);
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- public void setA(int _int) {
-
- //String sign = "voidsetA(int)";
- int methodId = 0;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { _int };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- public void setB(float _float) {
-
- int methodId = 1;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { float.class };
- Object[] paramObj = new Object[] { _float };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- public void setC(String _string) {
-
- int methodId = 2;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { String.class };
- Object[] paramObj = new Object[] { _string };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- }
-
-
- // Getters
- public String sumArray(String[] newA) {
-
- int methodId = 3;
- Class<?> retType = String.class;
- Class<?>[] paramCls = new Class<?>[] { String[].class };
- Object[] paramObj = new Object[] { newA };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (String)retObj;
- }
-
-
- public int setAndGetA(int newA) {
- int methodId = 4;
- Class<?> retType = int.class;
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { newA };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (int)retObj;
- }
-
-
- public int setACAndGetA(String newC, int newA) {
-
- int methodId = 5;
- Class<?> retType = int.class;
- Class<?>[] paramCls = new Class<?>[] { String.class, int.class };
- Object[] paramObj = new Object[] { newC, newA };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (int)retObj;
- }
-
-
- public int callBack() {
-
- int methodId = 6;
- Class<?> retType = int.class;
- Class<?>[] paramCls = new Class<?>[] { };
- Object[] paramObj = new Object[] { };
- Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- return (int)retObj;
-
- }
-
-
- public StructJ[] handleStruct(StructJ[] data) {
-
- int methodId = 11;
- Class<?> retType = void.class;
- Class<?>[] paramCls = new Class<?>[] { int.class };
- Object[] paramObj = new Object[] { data.length };
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
-
- int methodId2 = 10;
- Class<?> retType2 = int.class; // return type is integer if it is a struct!!!
- // Calculate the size of the array
- Class<?>[] paramCls2 = new Class<?>[3*data.length];
- Object[] paramObj2 = new Object[3*data.length];
- // Handle with for loop
- int pos = 0;
- for(int i = 0; i < data.length; i++) {
- paramCls2[pos] = String.class;
- paramObj2[pos++] = data[i].name;
- paramCls2[pos] = float.class;
- paramObj2[pos++] = data[i].value;
- paramCls2[pos] = int.class;
- paramObj2[pos++] = data[i].year;
- }
- //System.out.println(Arrays.toString(paramObj2));
- Object retObj = rmiCall.remoteCall(objectId, methodId2, retType2, null, paramCls2, paramObj2);
- // RETURN STRUCT
- // Get the length of the struct first
- int structsize1 = (int) retObj;
- // Construct the struct
- Class<?>[] retCls = new Class<?>[3*structsize1];
- Class<?>[] retClsVal = new Class<?>[3*structsize1];
- pos = 0;
- for(int i=0; i < structsize1; i++) {
- retCls[pos] = String.class;
- retClsVal[pos++] = null;
- retCls[pos] = float.class;
- retClsVal[pos++] = null;
- retCls[pos] = int.class;
- retClsVal[pos++] = null;
- }
- Object[] retObj2 = rmiCall.getStructObjects(retCls,
- retClsVal);
- StructJ[] dataRet = new StructJ[structsize1];
- for (int i=0; i < structsize1; i++) {
- dataRet[i] = new StructJ();
- }
- pos = 0;
- for(int i=0; i < structsize1; i++) {
- dataRet[i].name = (String) retObj2[pos++];
- dataRet[i].value = (float) retObj2[pos++];
- dataRet[i].year = (int) retObj2[pos++];
- }
-
- return dataRet;
- }
-
-
- public EnumJ[] handleEnum(EnumJ[] en) {
-
- int methodId = 12;
- Class<?> retType = int[].class;
- // Handle with for loop
- int paramInt[] = new int[en.length];
- for(int i = 0; i < en.length; i++) {
- paramInt[i] = en[i].ordinal();
- }
-
- Class<?>[] paramCls = new Class<?>[] { int[].class };
- Object[] paramObj = new Object[] { paramInt };
-
- // if no return value just
- // rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- // This is with return value:
- Object retObj =
- rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
- int[] retEnumInt = (int[]) retObj;
- int enumsize1 = retEnumInt.length;
- // Encoder/decoder
- EnumJ[] enumJ = EnumJ.values();
- EnumJ[] enRetVal = new EnumJ[enumsize1];
- for(int i = 0; i < enumsize1; i++) {
- enRetVal[i] = enumJ[retEnumInt[i]];
- }
- return enRetVal;
- }
-
-
- public static void main(String[] args) throws Exception {
-
- CommunicationHandler comHan = new CommunicationHandler(true);
- int numOfPorts = TestClass_Stub.numCallbackObjects();
- int[] ports = comHan.getCallbackPorts(numOfPorts);
-
- int port = 5010;
- String address = "localhost";
- int rev = 0;
-
- System.out.println("Allocated ports: " + Arrays.toString(ports));
-
- TestClass_Stub tcstub = new TestClass_Stub(port, address, rev, ports);
- System.out.println("Return value: " + tcstub.setAndGetA(123));
- System.out.println("Return value: " + tcstub.setACAndGetA("string", 123));
- System.out.println("Return value: " + tcstub.sumArray(new String[] { "123", "456", "987" }));
-
- /*CallBackInterface cb1 = new CallBack(23);
- CallBackInterface cb2 = new CallBack(33);
- CallBackInterface cb3 = new CallBack(43);
- CallBackInterface[] cb = { cb1, cb2, cb3 };
- tcstub.registerCallback(cb);
- System.out.println("Return value from callback: " + tcstub.callBack());
- CallBackInterface cb4 = new CallBack(10);
- CallBackInterface cb5 = new CallBack(11);
- CallBackInterface cb6 = new CallBack(12);
- CallBackInterface[] cbt = { cb4, cb5, cb6 };
- tcstub.registerCallback(cbt);
- System.out.println("Return value from callback: " + tcstub.callBack());*/
-
- StructJ[] data = new StructJ[2];
- for (int i=0; i<2; i++) {
- data[i] = new StructJ();
- }
- data[0].name = "Rahmadi";
- data[0].value = 0.123f;
- data[0].year = 2016;
- //data[1].name = "Trimananda";
- //data[1].value = 0.223f;
- //data[1].year = 2017;
-
- for (StructJ str : data) {
- System.out.println("Name: " + str.name);
- System.out.println("Value: " + str.value);
- System.out.println("Year: " + str.year);
- }
- StructJ[] strj = tcstub.handleStruct(data);
- for (StructJ str : strj) {
- System.out.println("Name: " + str.name);
- System.out.println("Value: " + str.value);
- System.out.println("Year: " + str.year);
- }
-
-
- EnumJ[] en = { EnumJ.APPLE, EnumJ.ORANGE, EnumJ.APPLE, EnumJ.GRAPE };
- EnumJ[] res = tcstub.handleEnum(en);
- System.out.println("Enum members: " + Arrays.toString(res));
- }
-}
-
-
/** Class IoTSlave is a communication class
* that interacts with IoTSlave.java to set up C++
- * objects in Sentinel.
+ * objects in Vigilia.
*
* @author Rahmadi Trimananda <rtrimana @ uci.edu>
* @version 1.0
}
} catch (IOException ex) {
- System.out.println("ClassRuntimeInstrumenterMaster@RunInstrumentation: IOException: "
- + ex.getMessage());
+ System.out.println("ClassRuntimeInstrumenterMaster@RunInstrumentation: IOException: " + ex.getMessage());
ex.printStackTrace();
}
}
/** Class CommunicationHandler is a class that maintains
* a data structure that preserves a collection of host name,
* port numbers, and objects that are running
- * +-----------------+----+--------+------------------+--------------+----------------+
- * | HOST-ADDRESS | ...|IN-PORT | RMIREGISTRY-PORT | RMISTUB-PORT | ACTIVE OBJECTS |
- * +-----------------+----+--------+------------------+--------------+----------------+
- * | XXX.XXX.XXX.XXX | | XXXXX | XXXXX | XXXXX | XXXXXXXXXXXXXX |
- * | | | XXXXX | XXXXX | XXXXX | XXXXXXXXXXXXXX |
- * | | | XXXXX | XXXXX | XXXXX | XXXXXXXXXXXXXX |
- * | | ...| ... | ... | ... | ... |
- * +-----------------+----+--------+------------------+--------------+----------------+
+ * +-----------------+----+--------+------------------+--------------+----+----------------+
+ * | HOST-ADDRESS | ...|IN-PORT | RMIREGISTRY-PORT | RMISTUB-PORT | ...| ACTIVE OBJECTS |
+ * +-----------------+----+--------+------------------+--------------+----+----------------+
+ * | XXX.XXX.XXX.XXX | | XXXXX | XXXXX | XXXXX | | XXXXXXXXXXXXXX |
+ * | | | XXXXX | XXXXX | XXXXX | | XXXXXXXXXXXXXX |
+ * | | | XXXXX | XXXXX | XXXXX | | XXXXXXXXXXXXXX |
+ * | | ...| ... | ... | ... | ...| ... |
+ * +-----------------+----+--------+------------------+--------------+----+----------------+
* In this case we use ACTIVE OBJECTS names as the key
* So ACTIVE OBJECTS maps to numbers and these numbers map to each other
* entry in hashmaps (HostAddress can be repetitive)
* ProximitySensorPS1 - 1
* TempSensorTS1 - 2
* ...
- * IN-PORT / RMIREGISTRY-PORT / RMISTUB-PORT / HOST-ADDRESS: 0 - XXXXX
- * 1 - XXXXX
- * 2 - XXXXX
- * +-------------+
- * | DEVICE-PORT |
- * +-------------+
- * | XXXXX |
- * | XXXXX |
- * | XXXXX |
- * | ... |
- * +-------------+
- * We add a Set structure to handle all the other ports that are used by devices
- * when communicating with their respective drivers
*
* @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
* @version 1.0
private Map<Integer, Integer> hmRMIRegPort;
private Map<Integer, Integer> hmRMIStubPort;
private Set<Integer> hsDevicePort;
- private Set<Integer> hsAllPorts;
private Map<Integer, Integer> hmAdditionalPort;
private int iNumOfObjects;
private int iNumOfHosts;
private boolean bVerbose;
- // TODO: THIS IS HACKING FOR IOTSEC
- // Replace random
- private int comPortCount = 10000;
- private int rmiRegCount = 20000;
- private int rmiStubCount = 30000;
- private int additionalCount = 40000;
-
/**
* CommunicationHandler class constants
*/
private final int INT_MIN_PORT = 10000;
/**
- * Empty constructor
+ * Constructor
*/
public CommunicationHandler(boolean _bVerbose) {
hmRMIRegPort = new HashMap<Integer, Integer>();
hmRMIStubPort = new HashMap<Integer, Integer>();
hsDevicePort = new HashSet<Integer>();
- hsAllPorts = new HashSet<Integer>();
hmAdditionalPort = new HashMap<Integer, Integer>();
iNumOfObjects = 0;
iNumOfHosts = 0;
int iComPort = 0;
do {
iComPort = random.nextInt(INT_MAX_PORT - INT_MIN_PORT + 1) + INT_MIN_PORT;
- //System.out.println("DEBUG: Assigning comPort: " + comPortCount);
- //iComPort = comPortCount++;
- // Check port existence in HashMap
+ // Check port existence in HashMap
} while (portIsAvailable(iComPort) == false);
hmComPort.put(iNumOfObjects, iComPort);
- // hsAllPorts tracks all the existing and used port numbers
- hsAllPorts.add(iComPort);
int iRMIRegPort = 0;
do {
iRMIRegPort = random.nextInt(INT_MAX_PORT - INT_MIN_PORT + 1) + INT_MIN_PORT;
- //System.out.println("DEBUG: Assigning regPort: " + rmiRegCount);
- //iRMIRegPort = rmiRegCount++;
- // Check port existence in HashMap
+ // Check port existence in HashMap
} while (portIsAvailable(iRMIRegPort) == false);
hmRMIRegPort.put(iNumOfObjects, iRMIRegPort);
- hsAllPorts.add(iRMIRegPort);
int iRMIStubPort = 0;
do {
iRMIStubPort = random.nextInt(INT_MAX_PORT - INT_MIN_PORT + 1) + INT_MIN_PORT;
- //System.out.println("DEBUG: Assigning stubPort: " + rmiStubCount);
- //iRMIStubPort = rmiStubCount++;
- // Check port existence in HashMap
+ // Check port existence in HashMap
} while (portIsAvailable(iRMIStubPort) == false);
hmRMIStubPort.put(iNumOfObjects, iRMIStubPort);
- hsAllPorts.add(iRMIStubPort);
iNumOfObjects++;
}
public void addDevicePort(int iDevPort) {
hsDevicePort.add(iDevPort);
- // Track this port number
- hsAllPorts.add(iDevPort);
}
/**
int iAdditionalPort = 0;
do {
iAdditionalPort = random.nextInt(INT_MAX_PORT - INT_MIN_PORT + 1) + INT_MIN_PORT;
- //System.out.println("DEBUG: Assigning additionalPort: " + additionalCount);
- //iAdditionalPort = additionalCount++;
- // Check port existence in HashMap
+ // Check port existence in HashMap
} while (portIsAvailable(iAdditionalPort) == false);
hmAdditionalPort.put(iNumOfObjects, iAdditionalPort);
- // Track this port number
- hsAllPorts.add(iAdditionalPort);
iNumOfObjects++;
} else {
return true;
}
- //if (hsAllPorts.contains(iPortNumber)) {
- // return false;
- //} else {
- // return true;
- //}
}
/**
private static final String STR_SHELL_HEADER = "#!/bin/sh";
private static final String STR_JAVA_PATH = "/usr/bin/java";
private static final String STR_MAC_POL_PATH = "tomoyo/";
- private static final String STR_TMP = "tmp";
- private static final String STR_ARP = "arp";
+ private static final String STR_TMP = "tmp";
+ private static final String STR_ARP = "arp";
private static int INT_SIZE = 4; // send length in the size of integer (4 bytes)
private static final int INT_DNS_PORT = 53;
else
throw new Error("IoTMaster: Unknown value for STR_MAC_TO_IP_TRANSLATION: " + STR_MAC_TO_IP_TRANSLATION);
processJailConfig = new ProcessJailConfig();
- //processJailConfig.setAddressListObject(routerConfig.getAddressListObject());
objInitHand = new ObjectInitHandler(BOOL_VERBOSE);
objAddInitHand = new ObjectAddressInitHandler(BOOL_VERBOSE);
mapClassNameToCrim = new HashMap<String,Object>();
System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
ex.printStackTrace();
}
- System.out.println("IoTMaster: Reading " + strCfgField +
+ RuntimeOutput.print("IoTMaster: Reading " + strCfgField +
" from config file: " + strCfgFileName + " with value: " +
- prop.getProperty(strCfgField, null));
+ prop.getProperty(strCfgField, null), BOOL_VERBOSE);
// NULL is returned if the property isn't found
return prop.getProperty(strCfgField, null);
}
* @params strFieldName String field name
* @params strIoTSlaveObjectHostAdd String slave host address
* @params inStream ObjectInputStream communication
- * @params inStream ObjectOutputStream communication
+ * @params outStream ObjectOutputStream communication
* @params strLanguage String language
* @return void
*/
if (commHan.getComPort(strDeviceAddressKey) == null) {
commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
}
-
- // TODO: DEBUG!!!
- System.out.println("\n\n DEBUG: InstrumentSetDevice: Object Name: " + strObjName);
- System.out.println("DEBUG: InstrumentSetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
- System.out.println("DEBUG: InstrumentSetDevice: Device address: " + strDeviceAddressKey + "\n\n");
-
// Send address one by one
if(strLanguage.equals(STR_JAVA)) {
Message msgGetIoTSetObj = null;
}
int iRows = setInstrumenter.numberOfRows();
RuntimeOutput.print("IoTMaster: Number of rows for IoTZigbeeAddress: " + iRows, BOOL_VERBOSE);
-
- // TODO: DEBUG!!!
- System.out.println("\n\nDEBUG: InstrumentZigbeeDevice: Object Name: " + strObjName);
- System.out.println("DEBUG: InstrumentZigbeeDevice: Port number: " + commHan.getComPort(strZigbeeGWAddressKey));
- System.out.println("DEBUG: InstrumentZigbeeDevice: Device address: " + strZigbeeGWAddress + "\n\n");
-
// Transfer the address
for(int iRow=0; iRow<iRows; iRow++) {
arrFieldValues = setInstrumenter.fieldValues(iRow);
// Extract the interface name for RMI
// e.g. ProximitySensorInterface, TempSensorInterface, etc.
-
String strObjCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
strObjClassInterfaceName = parseConfigFile(strObjCfgFile, STR_INTERFACE_CLS_CFG);
strObjStubClsIntfaceName = parseConfigFile(strObjCfgFile, STR_INT_STUB_CLS_CFG);
} else {
// If this is a new object ... then create one
// Get host address for IoTSlave from LoadBalancer
- //strIoTSlaveObjectHostAdd = lbIoT.selectHost();
strIoTSlaveObjectHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
if (strIoTSlaveControllerHostAdd == null)
throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd,
strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
// Configure MAC policies for objects
- //String strFileName = STR_MAC_POL_PATH + strObjClassName + STR_MAC_POLICY_EXT;
String strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
processJailConfig.configureProcessJailDeviceDriverPolicies(strIoTSlaveObjectHostAdd, strObjName, strObjClassName,
commHan.addAdditionalPort(strUniqueDev);
}
}
-
- // TODO: DEBUG!!!
- System.out.println("\n\n DEBUG: InstrumentPolicySetDevice: Object Name: " + strObjName);
- System.out.println("DEBUG: InstrumentPolicySetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
- System.out.println("DEBUG: InstrumentPolicySetDevice: Device address: " + strDeviceAddressKey + "\n\n");
-
// Send routing policy to router for device drivers and devices
// ROUTING POLICY: RMI communication - RMI registry and stub ports
if((iDestDeviceDriverPort == -1) && (!strProtocol.equals(STR_NO_PROTOCOL))) {
// Send the file to the compute node
String strCmdSend = "scp " + shellFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_RUNTIME_DIR;
runCommand(strCmdSend);
- System.out.println("IoTMaster: Sending shell file: " + strCmdSend);
+ RuntimeOutput.print("IoTMaster: Sending shell file: " + strCmdSend, BOOL_VERBOSE);
return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
}
strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE);
if(strLanguageDriver == null) // Check nullness for the second time - report if it is still null
throw new Error("IoTMaster: Language specification missing in config file: " + sCfgFile);
- // PROFILING
- long start = 0;
- long result = 0;
- // PROFILING
- start = System.currentTimeMillis();
-
// Construct ssh command line
// e.g. ssh rtrimana@dw-2.eecs.uci.edu cd <path>;
// java -cp $CLASSPATH:./*.jar
else
throw new Error("IoTMaster: Language specification not recognized: " + strLanguageDriver);
RuntimeOutput.print("IoTMaster: Language for " + strObjName + " is " + strLanguageDriver, BOOL_VERBOSE);
-
RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
// Start a new thread to start a new JVM
createThread(strSSHCommand);
outStream = new BufferedOutputStream(socket.getOutputStream());
recvAck(inStream);
}
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to start JVM for " + strObjName + ": " + result + "\n\n");
-
- // PROFILING
- start = System.currentTimeMillis();
-
if(strLanguageDriver.equals(STR_JAVA)) {
sendFileToJavaSlaveDriver(serverSocket, inStream, outStream, strObjName,
strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses,
outStream, inStream);
}
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to send JAR file for " + strObjName + ": " + result + "\n\n");
-
- // PROFILING
- start = System.currentTimeMillis();
-
// Instrument the class source code and look for IoTSet for device addresses
// e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
RuntimeOutput.print("IoTMaster: Instantiating for " + strObjClassName + " with objectID " + strFieldObjectID, BOOL_VERBOSE);
createDriverObjectCpp(outStream, inStream);
//endSessionCpp(outStream);
}
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to create object " + strObjName + " and instrument IoTDeviceAddress: " + result + "\n\n");
-
// Closing streams
outStream.close();
inStream.close();
reinitializeIoTSetFieldCpp(outStream, inStream);
} else if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTRELATION) {
// == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTRELATION
- // TODO: createNewIoTRelation needs to be created here!
createNewIoTRelationCpp(str, outStream, inStream);
List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
recvAck(inStream);
}
RuntimeOutput.print("IoTMaster: Communication established!", BOOL_VERBOSE);
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> From start until after SSH for main controller: " + result);
- // PROFILING
- start = System.currentTimeMillis();
-
// Send files for every controller class
// e.g. AcmeProximity.jar and AcmeProximity.zip
String strControllerClassName = strObjControllerName + STR_CLS_FILE_EXT;
processJailConfig.combineAdditionalMACPolicy(strContMACCfg, strObjControllerName, strObjControllerName);
}
}
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> From IoTSlave start until main controller object is created: " + result);
- System.out.println(" ==> Including file transfer times!\n\n");
- // PROFILING
- start = System.currentTimeMillis();
-
// == END INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
// Instrumenting one file
RuntimeOutput.print("IoTMaster: Opening class file: " + strControllerClassName, BOOL_VERBOSE);
// SetInstrumenter vs. RelationInstrumenter
String strFieldName = map.getKey();
String strClassName = map.getValue().getClass().getName();
-
- System.out.println("\n\nDEBUG: Instrumenting IoTSet and IoTRelation objects!!!");
- System.out.println("DEBUG: Field name: " + strFieldName);
- System.out.println("DEBUG: Class name: " + strFieldName + "\n\n");
-
if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
String strTempFileName = "./" + strObjControllerName + STR_MAC_POLICY_EXT;
processJailConfig.combineControllerMACPolicies(strIoTSlaveControllerHostAdd, strObjControllerName, strTempFileName);
processJailConfig.flush();
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to instrument device driver objects: " + result + "\n\n");
- System.out.println(" ==> #Objects: " + commHan.getActiveControllerObjectList().size() + "\n\n");
-
- // PROFILING
- start = System.currentTimeMillis();
-
// ROUTING POLICY: implement basic policies to reject all other irrelevant traffics
for(String s: commHan.getHosts()) {
setHostBasicPolicies(s);
// See if firewall policy is configured to be "on" or "off"
if (STR_POLICY_ON.equals(STR_YES))
createPolicyThreads(STR_ROUTER_ADD, setAddresses);
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to send policy files and deploy them : " + result + "\n\n");
-
- // PROFILING
- start = System.currentTimeMillis();
-
// Separating object creations and Set/Relation initializations
createDriverObjects();
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to instantiate objects: " + result + "\n\n");
- // PROFILING
- start = System.currentTimeMillis();
-
// Sets and relations initializations
if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
initializeSetsAndRelationsJava(inStream, outStream);
else
initializeSetsAndRelationsCpp(inStream, outStream);;
-
- // PROFILING
- result = System.currentTimeMillis()-start;
- System.out.println("\n\n ==> Time needed to initialize sets and relations: " + result + "\n\n");
-
if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
// == COMMUNICATION WITH IOTSLAVE CONTROLLER TO EXECUTE INIT METHOD
commMasterToSlave(new MessageSimple(IoTCommCode.INVOKE_INIT_METHOD), "Invoke init() method!", inStream, outStream);
/**
* LoadBalancer class constants
*/
-// private static final String STR_TABLE_COMPUTE_NODE = "IoTComputeNodePC";
private static final String STR_TABLE_COMPUTE_NODE = "IoTComputeNode";
/**
*/
private static final String STR_SSH_USERNAME_ROUTER = "root";
private static final String STR_SSH_USERNAME_HOST = "iotuser";
- private static final String STR_TCP_PROTOCOL = "tcp";
- private static final String STR_UDP_PROTOCOL = "udp";
- private static final String STR_TCPGW_PROTOCOL = "tcpgw";
- private static final String STR_NO_PROTOCOL = "nopro";
+ private static final String STR_TCP_PROTOCOL = "tcp";
+ private static final String STR_UDP_PROTOCOL = "udp";
+ private static final String STR_TCPGW_PROTOCOL = "tcpgw";
+ private static final String STR_NO_PROTOCOL = "nopro";
private static final String STR_ADD_MAC_EXT = ".tomoyo";
private static final String STR_MAC_POLICY_EXT = ".tomoyo.pol";
*/
public void getAddressList(String strRouterAddress) {
- //HashMap<String,String> hmMACToIPAdd = new HashMap<String,String>();
try {
// We can replace "cat /tmp/dhcp.leases" with "cat /proc/net/arp"
String cmd = "ssh " + STR_SSH_USERNAME_ROUTER + "@" + strRouterAddress +
replace(STR_OBJECT_CLASS_NAME, strObjectClassName).
replace(STR_MASTER_IP_ADDRESS, strMasterIPAddress).
replace(STR_MASTER_COM_PORT, String.valueOf(iComPort));
- //replace(STR_RMI_REG_PORT, String.valueOf(iRMIRegPort)).
- //replace(STR_RMI_STUB_PORT, String.valueOf(iRMIStubPort));
pwConfig.println("\n");
pwConfig.print(strNewPolicyList);
pwConfig.println("network inet stream bind/listen :: " + iRMIRegPort);
public void configureProcessJailInetAddressPolicies(String strConfigHost, String strRouterAddress, String strAddress) {
PrintWriter pwConfig = getPrintWriter(strConfigHost);
- //System.out.println("\n\nDEBUG: Writing the config host address setup!!!\n\n");
pwConfig.println("file read /etc/resolv.conf");
pwConfig.println("file read /etc/hosts");
pwConfig.println("file read /etc/host.conf");
/**
* RouterConfig constants
*/
- private static final String STR_SSH_USERNAME_ROUTER = "root";
- private static final String STR_SSH_USERNAME_RASPBERRYPI = "pi";
- private static final String STR_SSH_USERNAME_HOST = "iotuser";
- private static final String STR_POLICY_FILE_ALL = "_all";
- private static final String STR_POLICY_FILE_EXT = ".policy";
- private static final String STR_INCOMPLETE = "(incomplete)";
+ private static final String STR_SSH_USERNAME_ROUTER = "root";
+ private static final String STR_SSH_USERNAME_RASPBERRYPI = "pi";
+ private static final String STR_SSH_USERNAME_HOST = "iotuser";
+ private static final String STR_POLICY_FILE_ALL = "_all";
+ private static final String STR_POLICY_FILE_EXT = ".policy";
+ private static final String STR_INCOMPLETE = "(incomplete)";
/**
* RouterConfig properties
deployPolicies(strCmdSend);
String strCmdDeploy = "ssh " + STR_SSH_USERNAME_ROUTER + "@" + strConfigHost +
" iptables-restore < ~/" + strConfigHost + STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + "; rm ~/" + strConfigHost +
- STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + "; ";// +
- // TODO: delete these later when we apply tight initial conditions (reject everything but SSH commands)
- //"iptables -F startup_filter_tcp; iptables -F startup_filter_udp; " +
- //"iptables -t filter -D FORWARD -j startup_filter_tcp; iptables -t filter -D FORWARD -j startup_filter_udp;";
+ STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + "; ";
//System.out.println(strCmdDeploy);
deployPolicies(strCmdDeploy);
}
String strCmdSend = "scp " + strConfigHost + STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + " " +
STR_SSH_USERNAME_HOST + "@" + strConfigHost + ":~;";
- System.out.println(strCmdSend);
+ //System.out.println(strCmdSend);
deployPolicies(strCmdSend);
String strCmdDeploy = "ssh " + STR_SSH_USERNAME_HOST + "@" + strConfigHost +
" sudo iptables-restore < ~/" + strConfigHost + STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + "; rm ~/" + strConfigHost +
STR_POLICY_FILE_ALL + STR_POLICY_FILE_EXT + ";";
- System.out.println(strCmdDeploy);
+ //System.out.println(strCmdDeploy);
deployPolicies(strCmdDeploy);
}
*/
public void getAddressListTmp(String strRouterAddress) {
- //HashMap<String,String> hmMACToIPAdd = new HashMap<String,String>();
try {
// We can replace "cat /tmp/dhcp.leases" with "cat /proc/net/arp"
String cmd = "ssh " + STR_SSH_USERNAME_ROUTER + "@" + strRouterAddress +
}
}
- /**
- * getAddressListArp() method gets list of IP addresses from arp command
- * <p>
- * This method sends an inquiry to the router to look for
- * the list of DHCP leased addresses and their mapping to MAC
- * addresses
- *
- * @param strRouterAddress String that contains address of router
- */
- public void getAddressListArp(String strRouterAddress) {
-
- //HashMap<String,String> hmMACToIPAdd = new HashMap<String,String>();
- try {
- // We replace with "cat /usr/sbin/arp"
- String cmd = "ssh " + STR_SSH_USERNAME_RASPBERRYPI + "@" + strRouterAddress +
- " /usr/sbin/arp -n";
- Runtime runtime = Runtime.getRuntime();
- Process process = runtime.exec(cmd);
-
- InputStream inStream = process.getInputStream();
- InputStreamReader isReader = new InputStreamReader(inStream);
- BufferedReader bReader = new BufferedReader(isReader);
- String strRead = null;
- while((strRead = bReader.readLine()) != null){
- String[] str = strRead.split("\\s+");
- // Skip if "(incomplete)" is seen!
- if (str[1].equals(STR_INCOMPLETE))
- continue;
- mapMACtoIPAdd.put(str[2], str[0]);
- }
- } catch (IOException ex) {
- System.out.println("RouterConfig: IOException: " + ex.getMessage());
- ex.printStackTrace();
- }
+ /**
+ * getAddressListArp() method gets list of IP addresses from arp command
+ * <p>
+ * This method sends an inquiry to the router to look for
+ * the list of DHCP leased addresses and their mapping to MAC
+ * addresses
+ *
+ * @param strRouterAddress String that contains address of router
+ */
+ public void getAddressListArp(String strRouterAddress) {
+
+ try {
+ // We replace with "cat /usr/sbin/arp"
+ String cmd = "ssh " + STR_SSH_USERNAME_RASPBERRYPI + "@" + strRouterAddress +
+ " /usr/sbin/arp -n";
+ Runtime runtime = Runtime.getRuntime();
+ Process process = runtime.exec(cmd);
+
+ InputStream inStream = process.getInputStream();
+ InputStreamReader isReader = new InputStreamReader(inStream);
+ BufferedReader bReader = new BufferedReader(isReader);
+ String strRead = null;
+ while((strRead = bReader.readLine()) != null) {
+ String[] str = strRead.split("\\s+");
+ // Skip if "(incomplete)" is seen!
+ if (str[1].equals(STR_INCOMPLETE))
+ continue;
+ mapMACtoIPAdd.put(str[2], str[0]);
+ }
+ } catch (IOException ex) {
+ System.out.println("RouterConfig: IOException: " + ex.getMessage());
+ ex.printStackTrace();
}
+ }
/**
* getIPFromMACAddress() method gets IP from MAC address
strConfigHost + " -d " + strMonitorHost + " -p tcp --dport ssh");
pwConfig.println("-A OUTPUT -j ACCEPT -s " +
strConfigHost + " -d " + strMonitorHost + " -p tcp --sport ssh");
- //pwConfig.println("-A FORWARD -j ACCEPT -p tcp --dport ssh");
- //pwConfig.println("-A FORWARD -j ACCEPT -p tcp --sport ssh");
}
pwConfig.println("-A INPUT -j ACCEPT -p udp --sport domain");
pwConfig.println("-A OUTPUT -j ACCEPT -p udp --dport domain");
pwConfig.println("-A OUTPUT -j ACCEPT -p udp --sport domain");
-
}
}
* @param _isDstPortWildCard Is this destination port a wild card (=can change port number)?\r
*/\r
protected IoTDeviceAddress(String _sAddress, int _iSrcPort, int _iDstPort, boolean _isSrcPortWildCard,\r
- //public IoTDeviceAddress(String _sAddress, int _iSrcPort, int _iDstPort, boolean _isSrcPortWildCard, \r
boolean _isDstPortWildCard) throws UnknownHostException {\r
\r
super(_sAddress);\r
* Class constructor (pass the reference to this immutable wrapper)
*/
protected IoTSet(Set<T> s) {
- //public IoTSet(Set<T> s) {
set = s;
}
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
} catch (IOException ex) {
- System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
+ RuntimeOutput.print("IoTMaster: Error reading config file: " + strCfgFileName, BOOL_VERBOSE);
ex.printStackTrace();
}
- System.out.println("IoTMaster: Extracting information from config file: " + strCfgFileName);
+ RuntimeOutput.print("IoTMaster: Extracting information from config file: " + strCfgFileName, BOOL_VERBOSE);
// Initialize constants from config file
STR_JAR_FILE_PATH = prop.getProperty("JAR_FILE_PATH");
STR_OBJ_CLS_PFX = prop.getProperty("OBJECT_CLASS_PREFIX");
CAPAB_BASED_RMI = true;
}
- System.out.println("JAR_FILE_PATH=" + STR_JAR_FILE_PATH);
- System.out.println("OBJECT_CLASS_PREFIX=" + STR_OBJ_CLS_PFX);
- System.out.println("INTERFACE_PREFIX=" + STR_INTERFACE_PFX);
- System.out.println("SKEL_CLASS_SUFFIX=" + SKEL_CLASS_SUFFIX);
- System.out.println("STUB_CLASS_SUFFIX=" + STUB_CLASS_SUFFIX);
- System.out.println("CAPAB_BASED_RMI=" + CAPAB_BASED_RMI);
- System.out.println("IoTMaster: Information extracted successfully!");
+ RuntimeOutput.print("JAR_FILE_PATH=" + STR_JAR_FILE_PATH, BOOL_VERBOSE);
+ RuntimeOutput.print("OBJECT_CLASS_PREFIX=" + STR_OBJ_CLS_PFX, BOOL_VERBOSE);
+ RuntimeOutput.print("INTERFACE_PREFIX=" + STR_INTERFACE_PFX, BOOL_VERBOSE);
+ RuntimeOutput.print("SKEL_CLASS_SUFFIX=" + SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
+ RuntimeOutput.print("STUB_CLASS_SUFFIX=" + STUB_CLASS_SUFFIX, BOOL_VERBOSE);
+ RuntimeOutput.print("CAPAB_BASED_RMI=" + CAPAB_BASED_RMI, BOOL_VERBOSE);
+ RuntimeOutput.print("IoTMaster: Information extracted successfully!", BOOL_VERBOSE);
}
/**
inStream.close();
socket.close();
RuntimeOutput.print("IoTSlave: Closing!", BOOL_VERBOSE);
- // We have to continuously loop because we are preserving our stubs and skeletons
- //while(true) { }
} catch (IOException |
ClassNotFoundException |
+++ /dev/null
-package iotruntime.stub;
-
-import iotruntime.slave.IoTDeviceAddress;
-
-/** IoTJSONStub abstract class that all the stubs are going
- * to implement
- *
- * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
- * @version 1.0
- * @since 2016-04-20
- */
-public abstract class IoTJSONStub {
-
- protected IoTDeviceAddress iotDevAddress;
-
- /**
- * Class constructor
- *
- * @param iotdevAddress IoTDeviceAddress object
- */
- public IoTJSONStub(IoTDeviceAddress _iotDevAddress) {
-
- this.iotDevAddress = _iotDevAddress;
- }
-
- public abstract void registerCallback(Object objCallback);
-}
-
e.printStackTrace();
}
}
- System.out.println(uri);
+ //System.out.println(uri);
try {
String strJSONString = sbResponse.toString();
Class[][] cr = new Class[1][];
} catch (JSONException ex) {
ex.printStackTrace();
- //throw new Error("IoTRemoteCall: Exiting");
logger.log(Level.WARNING, "package format error", ex.getMessage());
return null;
}
return retval;
} catch (JSONException ex) {
ex.printStackTrace();
- //throw new Error("IoTRemoteCall: Exiting");
logger.log(Level.WARNING, "package format error", ex.getMessage());
return null;
}
e.printStackTrace();
logger.log(Level.WARNING, "package format errors", e.getMessage());
return null;
- //throw new Error("IoTRemoteCall: Exiting");
}
}
/**
* Decode object from JSON
*/
- private static Object decodeObject(JSONObject jsonObj, Class[] tarr) {
+ private static Object decodeObject(JSONObject jsonObj, Class[] tarr) {
try {
String type = jsonObj.getString("type");
e.printStackTrace();
logger.log(Level.WARNING, "package format error", e.getMessage());
return null;
- //throw new Error("IoTRemoteCall: Exiting");
}
}
-
+
+
+ /**
+ * foo and Fooimpl are test class and interface
+ */
interface foo {
int add(int a, int b);
int setRoomID(Integer id);
+++ /dev/null
-package iotruntime.stub;
-
-// Java libraries
-import java.io.BufferedWriter;
-import java.io.PrintWriter;
-import java.io.FileWriter;
-import java.io.IOException;
-
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.ProtocolException;
-import java.net.URL;
-
-import java.lang.Class;
-import java.lang.reflect.*;
-
-
-/** IoTStubGenerator class that takes an interface,
- * instrument it using Java Reflection, and generate
- * static code that uses IoTRemoteCall as a stub object
- *
- * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
- * @version 1.0
- * @since 2016-04-14
- */
-public class IoTStubCodeGenerator {
-
- /**
- * IoTStubCodeGenerator properties
- */
- PrintWriter pw;
- String strInterfaceName;
- String strNewClassName;
- String strCallbackIntName;
-
- /**
- * Constructor
- */
- public IoTStubCodeGenerator(String[] strArgs) throws Exception {
-
- this.strInterfaceName = strArgs[0];
- if (strArgs.length == 1) {
- // If callback interface is not specified
- this.strCallbackIntName = "Object";
- } else {
- this.strCallbackIntName = strArgs[1];
- }
- strNewClassName = strInterfaceName + "Implementation";
- FileWriter fw = new FileWriter(strNewClassName + ".java");
- pw = new PrintWriter(new BufferedWriter(fw));
- }
-
- /**
- * Instrument interface class
- */
- public void instrumentInterfaceClass() {
-
- // Write the imports
- generateImports();
- // Write the class header
- println("public final class " + strNewClassName +
- " extends IoTJSONStub " +
- " implements " + strInterfaceName + " {");
- println("");
- generateFields();
- println("");
- generateConstructor();
- println("");
-
- try {
- Class<?>cls = Class.forName(strInterfaceName);
- for (Method mtd : cls.getDeclaredMethods()) {
- generateMethod(mtd);
- println("");
- }
- } catch (ClassNotFoundException ex) {
- ex.printStackTrace();
- }
- generateMethodCallback();
-
- //Close class
- println("}");
- pw.close();
- }
-
- /**
- * Generate import statements
- */
- private void generateImports() {
- // Write the class properties
- println("import iotruntime.stub.IoTRemoteCall;");
- println("import iotruntime.stub.IoTJSONStub;");
- println("import iotruntime.slave.IoTDeviceAddress;");
- println("");
- }
-
- /**
- * Generate fields
- */
- private void generateFields() {
- // Write the class properties
- println("private IoTRemoteCall iotremotecall;");
- println("private " + strCallbackIntName + " callbackObject;");
- }
-
- /**
- * Generate constructor
- */
- private void generateConstructor() {
- // Write the constructor
- println("public " + strNewClassName +
- "(IoTDeviceAddress _iotDevAdd) {");
- println("super(_iotDevAdd);");
- println("this.iotremotecall = new IoTRemoteCall();");
- print("String[] arrMethodName = { \"");
- // Get the interface class
- try {
- Class<?>cls = Class.forName(strInterfaceName);
- Method[] method = cls.getDeclaredMethods();
- for (Method mtd: method) {
- print(mtd.getName());
- // Check if this is the last element
- if (!mtd.equals(method[method.length-1])) {
- print("\", \"");
- }
- }
- println("\" };");
- println("this.iotremotecall.startHttpServer(arrMethodName, " +
- "iotDevAddress.getDestinationPortNumber());");
- } catch (ClassNotFoundException ex) {
- ex.printStackTrace();
- }
- println("}");
- }
-
- /**
- * Generate method body
- */
- private void generateMethod(Method mtd) {
-
- Class<?> clsReturn = mtd.getReturnType();
- // Write the method declaration
- print("public " + clsReturn.getSimpleName() + " " + mtd.getName() + "(");
- Parameter[] params = mtd.getParameters();
- // Write the method params
- for (Parameter param:params) {
- print(param.getType().getSimpleName() + " " + param.getName());
- // Check if this is the last element
- if (!param.equals(params[params.length-1])) {
- print(", ");
- }
- }
- println(") {");
- // Write the method body
- // Handle return value
- println("String strMethodName = \"" + mtd.getName() + "\";");
- // Handle inputs
- print("Object[] arrInpValue = { ");
- for (Parameter param:params) {
- print(param.getName());
- // Check if this is the last element
- if (!param.equals(params[params.length-1])) {
- print(", ");
- }
- }
- println(" };");
- print("String[] arrInpType = { \"");
- for (Parameter param:params) {
- print(param.getType().getSimpleName());
- // Check if this is the last element
- if (!param.equals(params[params.length-1])) {
- print("\", \"");
- }
- }
- println("\" };");
- println("Object _retval=iotremotecall.callMethod(strMethodName, iotDevAddress.getHostAddress(), iotDevAddress.getDestinationPortNumber(), arrInpValue, arrInpType, \""+ clsReturn.getSimpleName()+ "\");");
- if (!clsReturn.equals(Void.class)) {
- println("return ("+clsReturn.getSimpleName()+") _retval;");
- }
-
- println("}");
- }
-
- private void generateMethodCallback() {
-
- // Write the method
- println("public void registerCallback(Object objCallback) {");
- println("this.callbackObject = (" + strCallbackIntName + ") objCallback;");
- println("}");
- }
-
-
- boolean newline=true;
- int tablevel=0;
-
- private void print(String str) {
- if (newline) {
- int tab=tablevel;
- if (str.equals("}"))
- tab--;
- for(int i=0; i<tab; i++)
- pw.print("\t");
- }
- pw.print(str);
- updatetabbing(str);
- newline=false;
- }
-
- private void println(String str) {
- if (newline) {
- int tab = tablevel;
- if (str.equals("}"))
- tab--;
- for(int i=0; i<tab; i++)
- pw.print("\t");
- }
- pw.println(str);
- updatetabbing(str);
- newline = true;
- }
-
- private void updatetabbing(String str) {
- tablevel+=count(str,'{')-count(str,'}');
- }
-
- private int count(String str, char key) {
- char[] array = str.toCharArray();
- int count = 0;
- for(int i=0; i<array.length; i++) {
- if (array[i] == key)
- count++;
- }
- return count;
- }
-
- public static void main(String[] args) throws Exception {
- // args[0] = normal interface name
- // args[1] = callback interface name
- IoTStubCodeGenerator stub = new IoTStubCodeGenerator(args);
- stub.instrumentInterfaceClass();
- }
-}
private final int iSrcPort;
private final int iDstPort;
private DatagramSocket socket; // the socket interface that we are guarding
- private boolean didClose; // make sure that the clean up was done correctly
+ private boolean didClose; // make sure that the clean up was done correctly
private final IoTZigbeeAddress zigbeeAddress;
}
}
- //made by changwoo
+ // Created by Changwoo
public void sendChangeSwtichRequest(int packetId, int clusterId, int profileId, int value, int deviceEndpoint) throws IOException {
String message = "type: zcl_change_switch_request\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- //made by Jiawei
+ // Created by Jiawei
public void sendLockOrUnlockDoorRequest(int packetId, int clusterId, int profileId, int deviceEndpoint, int value) throws IOException {
String message = "type: zcl_lock_or_unlock_door_request\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- //made by Jiawei
- public void sendReadDoorStatusRequest(int packetId, int clusterId, int profileId, int deviceEndpoint, int framecontrol, int commandframe, int attribute_id) throws IOException {
+ // Created by Jiawei
+ public void sendReadDoorStatusRequest(int packetId, int clusterId, int profileId, int deviceEndpoint, int framecontrol,
+ int commandframe, int attribute_id) throws IOException {
String message = "type: zcl_read_door_status_request\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
message += "framecontrol: " + String.format("%02x", framecontrol) + "\n";
socket.send(sendPacket);
}
- //made by changwoo
+ // Created by Changwoo
public void sendBroadcastingRouteRecordRequest(int packetId) throws IOException {
String message = "type: zdo_broadcast_route_record_request\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- //made by changwoo
+ // Created by Changwoo
public void sendEnrollmentResponse(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
String message = "type: zcl_enrollment_response\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- //made by changwoo
+ // Created by Changwoo
public void sendWriteAttributesCommand(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
String message = "type: zcl_write_attributes\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- //made by changwoo
+ // Created by Changwoo
public void sendManagementPermitJoiningRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
String message = "type: management_permit_joining_request\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
socket.send(sendPacket);
}
- public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int src_endpoint, int dest_endpoint, int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
+ public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int src_endpoint, int dest_endpoint,
+ int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
String message = "type: zcl_configure_reporting\n";
message += "packet_id: " + String.format("%04x", packetId) + "\n";
message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
socket.send(sendPacket);
}
- public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int dest_endpoint, int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
- sendConfigureReportingCommand(packetId, clusterId, profileId, 0x00, dest_endpoint, attributeId, dataType, minReportingInterval, maxReportingInterval, reportableChange);
+ public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int dest_endpoint, int attributeId, int dataType,
+ int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
+ sendConfigureReportingCommand(packetId, clusterId, profileId, 0x00, dest_endpoint, attributeId, dataType, minReportingInterval,
+ maxReportingInterval, reportableChange);
}
public void registerCallback(IoTZigbeeCallback callbackTo) {
} else {
IoTZigbeeMessage callbackMessage = null;
- //made by changwoo
+ // Created by Changwoo
if (packetData.get("type").equals("zcl_zone_status_change_notification")){
int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
if(packetData.get("attributes").equals("success")) successOrFail=true;
callbackMessage = new IoTZigbeeMessageZclZoneStatusChangeNotification(packetId, clusterId, profileId, status, successOrFail);
- //made by changwoo
+ // Created by Changwoo
} else if (packetData.get("type").equals("zcl_write_attributes_response")) {
int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
- List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
+ List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new
+ ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
String[] attributes = packetData.get("attributes").split(";");
for (String attr : attributes) {
parts[0] = parts[0].trim();
parts[1] = parts[1].trim();
- IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
+ IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new
+ IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
attrList.add(at);
} else {
parts[0] = parts[0].trim();
parts[1] = parts[1].trim();
parts[2] = parts[2].trim();
parts[3] = parts[3].trim();
- IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
+ IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new
+ IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16),
+ Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
attrList.add(at);
}
}
if (packetData.get("attributes").equals("all_success")) {
callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
} else {
- List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
+ List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new
+ ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
String[] attributes = packetData.get("attributes").split(";");
for (String attr : attributes) {
parts[0] = parts[0].trim();
parts[1] = parts[1].trim();
parts[2] = parts[2].trim();
- IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
+ IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new
+ IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16),
+ parts[1].equals("success"), parts[2].equals("reported"));
attrList.add(at);
}
callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
parts[0] = parts[0].trim();
parts[1] = parts[1].trim();
parts[2] = parts[2].trim();
- IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
+ IoTZigbeeMessageZclReportAttributes.Attribute at = new
+ IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16),
+ Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
attrList.add(at);
}
}
}
-
-
} catch (Exception e) {
e.printStackTrace();
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-