Files
SDS/src/com/flaremicrosystems/sds/SDSObject.java
T
Flare Microsystems a97769e934 Initial commit
2022-02-03 20:04:49 -08:00

99 lines
2.8 KiB
Java

package com.flaremicrosystems.sds;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public abstract class SDSObject<T> {
T value;
static ArrayList<Integer> ids = new ArrayList<Integer>();
static ArrayList<Class<?>> objects = new ArrayList<Class<?>>();
static ArrayList<Class<?>> dataTypes = new ArrayList<Class<?>>();
static final int OPCODE_BYTES = 4;
static final int LENGTH_BYTES = 4;
static {
registerDataStore(0, SDSBooleanType.class, Boolean.class);
registerDataStore(1, SDSByteType.class, Byte.class);
registerDataStore(2, SDSShortType.class, Short.class);
registerDataStore(3, SDSIntType.class, Integer.class);
registerDataStore(4, SDSCharType.class, Character.class);
registerDataStore(5, SDSLongType.class, Long.class);
registerDataStore(6, SDSFloatType.class, Float.class);
registerDataStore(7, SDSDoubleType.class, Double.class);
registerDataStore(8, SDSStringType.class, String.class);
registerDataStore(9, SDSListType.class, ArrayList.class);
registerDataStore(10, SDSNameMapType.class, HashMap.class);
registerDataStore(11, SDSBinaryDataType.class, byte[].class);
registerDataStore(12, SDSNullType.class, null);
}
public SDSObject() {
}
public SDSObject(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public boolean isNull()
{
return false;
}
public abstract int getByteLength();
public void setValue(T newVal) {
value = newVal;
}
@Override
public String toString()
{
return this.value.toString();
}
public void store(DataOutputStream out) throws IOException {
int id = ids.get(objects.indexOf(this.getClass()));
out.writeInt(id);
int length = getByteLength();
out.writeInt(length);
}
public static void registerDataStore(int id, Class<?> obj, Class<?> dataType) {
ids.add(id);
objects.add(obj);
dataTypes.add(dataType);
}
public SDSObject<?> load(DataInputStream in) throws IOException, SDSUndefinedException {
return this;
}
public static SDSObject<?> readObject(DataInputStream in) throws IOException, SDSUndefinedException {
int id = in.readInt();
int length = in.readInt();
if (!ids.contains(id))
{
in.read(new byte[length]);
throw new SDSUndefinedException("Unknown identifier: " + id);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
Class<SDSObject> obj = (Class<SDSObject>) objects.get(ids.get(id));
try {
return obj.newInstance().load(in);
} catch (InstantiationException e) {
e.printStackTrace();
throw new SDSTotalFailureException(e);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new SDSTotalFailureException(e);
}
}
}