Browse Source

overhauling save and load routines

lookup-tables
Stephan Richter 5 years ago
parent
commit
09a7c9f5b7
  1. 2
      pom.xml
  2. 17
      src/main/java/de/srsoftware/web4rail/Application.java
  3. 84
      src/main/java/de/srsoftware/web4rail/Plan.java
  4. 71
      src/main/java/de/srsoftware/web4rail/Route.java
  5. 50
      src/main/java/de/srsoftware/web4rail/moving/Car.java
  6. 13
      src/main/java/de/srsoftware/web4rail/moving/Locomotive.java
  7. 43
      src/main/java/de/srsoftware/web4rail/moving/Train.java
  8. 33
      src/main/java/de/srsoftware/web4rail/tiles/Block.java
  9. 15
      src/main/java/de/srsoftware/web4rail/tiles/StretchableTile.java
  10. 86
      src/main/java/de/srsoftware/web4rail/tiles/Tile.java

2
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>de.srsoftware</groupId> <groupId>de.srsoftware</groupId>
<artifactId>web4rail</artifactId> <artifactId>web4rail</artifactId>
<version>0.3.4</version> <version>0.3.5</version>
<name>Web4Rail</name> <name>Web4Rail</name>
<description>Java Model Railway Control</description> <description>Java Model Railway Control</description>
<url>https://github.com/StephanRichter/Web4Rail</url> <url>https://github.com/StephanRichter/Web4Rail</url>

17
src/main/java/de/srsoftware/web4rail/Application.java

@ -15,8 +15,6 @@ import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.HashMap; import java.util.HashMap;
import java.util.Random;
import java.util.Vector;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -26,9 +24,6 @@ import com.sun.net.httpserver.HttpServer;
import de.keawe.localconfig.Configuration; import de.keawe.localconfig.Configuration;
import de.keawe.tools.translations.Translation; import de.keawe.tools.translations.Translation;
import de.srsoftware.web4rail.moving.Locomotive;
import de.srsoftware.web4rail.moving.Train;
import de.srsoftware.web4rail.tiles.Block;
public class Application { public class Application {
private static Plan plan; private static Plan plan;
@ -52,17 +47,7 @@ public class Application {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
plan = new Plan(); plan = new Plan();
} }
Locomotive BR110 = new Locomotive("BR110");
Locomotive BR130 = new Locomotive("BR130");
Vector<Block> blocks = new Vector<>(plan.blocks());
Random rand = new Random();
Block block1 = blocks.get(rand.nextInt(blocks.size()));
if (block1 != null) block1.train(new Train(BR110));
Block block2 = null;
do {
block2 = blocks.get(rand.nextInt(blocks.size()));
} while (block2 == block1);
if (block2 != null) block2.train(new Train(BR130));
Desktop.getDesktop().browse(URI.create("http://localhost:"+config.getInt(PORT)+"/plan")); Desktop.getDesktop().browse(URI.create("http://localhost:"+config.getInt(PORT)+"/plan"));
} }

84
src/main/java/de/srsoftware/web4rail/Plan.java

@ -1,10 +1,5 @@
package de.srsoftware.web4rail; package de.srsoftware.web4rail;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -19,7 +14,6 @@ import java.util.Map.Entry;
import java.util.Stack; import java.util.Stack;
import java.util.Vector; import java.util.Vector;
import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -46,7 +40,6 @@ import de.srsoftware.web4rail.tiles.EndS;
import de.srsoftware.web4rail.tiles.EndW; import de.srsoftware.web4rail.tiles.EndW;
import de.srsoftware.web4rail.tiles.Eraser; import de.srsoftware.web4rail.tiles.Eraser;
import de.srsoftware.web4rail.tiles.Shadow; import de.srsoftware.web4rail.tiles.Shadow;
import de.srsoftware.web4rail.tiles.Signal;
import de.srsoftware.web4rail.tiles.SignalE; import de.srsoftware.web4rail.tiles.SignalE;
import de.srsoftware.web4rail.tiles.SignalN; import de.srsoftware.web4rail.tiles.SignalN;
import de.srsoftware.web4rail.tiles.SignalS; import de.srsoftware.web4rail.tiles.SignalS;
@ -54,7 +47,6 @@ import de.srsoftware.web4rail.tiles.SignalW;
import de.srsoftware.web4rail.tiles.StraightH; import de.srsoftware.web4rail.tiles.StraightH;
import de.srsoftware.web4rail.tiles.StraightV; import de.srsoftware.web4rail.tiles.StraightV;
import de.srsoftware.web4rail.tiles.Tile; import de.srsoftware.web4rail.tiles.Tile;
import de.srsoftware.web4rail.tiles.Turnout;
import de.srsoftware.web4rail.tiles.Turnout.State; import de.srsoftware.web4rail.tiles.Turnout.State;
import de.srsoftware.web4rail.tiles.Turnout3E; import de.srsoftware.web4rail.tiles.Turnout3E;
import de.srsoftware.web4rail.tiles.TurnoutLE; import de.srsoftware.web4rail.tiles.TurnoutLE;
@ -151,7 +143,7 @@ public class Plan {
remove(erased); remove(erased);
return erased == null ? null : t("Removed {}.",erased); return erased == null ? null : t("Removed {}.",erased);
} }
if (configJson != null) tile.configure(new JSONObject(configJson)); //if (configJson != null) tile.configure(new JSONObject(configJson));
set(x, y, tile); set(x, y, tile);
return t("Added {}",tile.getClass().getSimpleName()); return t("Added {}",tile.getClass().getSimpleName());
} }
@ -257,60 +249,14 @@ public class Plan {
} }
public static Plan load(String filename) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { public static Plan load(String filename) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Plan result = new Plan(); try {
File file = new File(filename+".plan"); Car.loadAll(filename+".cars");
BufferedReader br = new BufferedReader(new FileReader(file)); Train.loadAll(filename+".trains");
while (br.ready()) { } catch (Exception e) {}
String line = br.readLine().trim(); Plan plan = new Plan();
String[] parts = line.split(":",4); Tile.loadAll(filename+".plan",plan);
try { Route.loadAll(filename+".routes",plan);
String x = parts[0]; return plan;
String y = parts[1];
String clazz = parts[2];
result.addTile(clazz, x, y, parts.length>3 ? parts[3] : null);
} catch (Exception e) {
LOG.warn("Was not able to load \"{}\":",line,e);
}
}
br.close();
file = new File(filename+".routes");
if (file.exists()) {
br = new BufferedReader(new FileReader(file));
while (br.ready()) {
String line = br.readLine().trim();
String[] parts = line.split("=",2);
try {
//String id = parts[0];
JSONObject json = new JSONObject(parts[1]);
Route route = new Route();
json.getJSONArray(Route.PATH).forEach(entry -> {
JSONObject pos = (JSONObject) entry;
Tile tile = result.get(pos.getInt("x"),pos.getInt("y"),false);
if (route.path().isEmpty()) {
route.start((Block) tile,null);
} else {
route.add(tile, null);
}
});
json.getJSONArray(Route.SIGNALS).forEach(entry -> {
JSONObject pos = (JSONObject) entry;
Tile tile = result.get(pos.getInt("x"),pos.getInt("y"),false);
route.addSignal((Signal) tile);
});
json.getJSONArray(Route.TURNOUTS).forEach(entry -> {
JSONObject pos = (JSONObject) entry;
Tile tile = result.get(pos.getInt("x"),pos.getInt("y"),false);
route.addTurnout((Turnout) tile, Turnout.State.valueOf(pos.getString(Turnout.STATE)));
});
if (json.has(Route.NAME)) route.name(json.getString(Route.NAME));
result.registerRoute(route);
} catch (Exception e) {
LOG.warn("Was not able to load \"{}\":",line,e);
}
}
br.close();
} else LOG.debug("{} not found.",file);
return result;
} }
private Tag menu() throws IOException { private Tag menu() throws IOException {
@ -460,16 +406,10 @@ public class Plan {
private String saveTo(String name) throws IOException { private String saveTo(String name) throws IOException {
if (name == null || name.isEmpty()) throw new NullPointerException("Name must not be empty!"); if (name == null || name.isEmpty()) throw new NullPointerException("Name must not be empty!");
Car.saveAll(name+".cars"); Car.saveAll(name+".cars");
Tile.saveAll(this.tiles,name+".tiles"); Tile.saveAll(tiles,name+".plan");
Train.saveAll(name+".trains"); // refers to cars, blocks Train.saveAll(name+".trains"); // refers to cars, blocks
Route.saveAll(routes,name+".routes"); // refers to tiles
File file = new File(name+".routes"); return t("Plan saved as \"{}\".",name);
BufferedWriter br = new BufferedWriter(new FileWriter(file));
for (Route route: routes.values()) {
br.append(route.id()+"="+route.json()+"\n");
}
br.close();
return t("Plan saved as \"{}\".",file);
} }
public void set(int x,int y,Tile tile) throws IOException { public void set(int x,int y,Tile tile) throws IOException {

71
src/main/java/de/srsoftware/web4rail/Route.java

@ -1,5 +1,7 @@
package de.srsoftware.web4rail; package de.srsoftware.web4rail;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -140,10 +142,10 @@ public class Route {
public void finish() throws IOException { public void finish() throws IOException {
startBlock.train(null); startBlock.train(null);
endBlock.train(train.heading(endDirection.inverse()));
train.route = null; train.route = null;
unlock(); unlock();
endBlock.train(train.heading(endDirection.inverse()));
} }
public String id() { public String id() {
@ -151,12 +153,12 @@ public class Route {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i=0; i<path.size();i++) { for (int i=0; i<path.size();i++) {
Tile tile = path.get(i); Tile tile = path.get(i);
if (i>0) sb.append(""); if (i>0) sb.append("-");
if (tile instanceof Block) { if (tile instanceof Block) {
sb.append(((Block)tile).name); sb.append(((Block)tile).name);
if (i>0) break; // Kontakt nach dem Ziel-Block nicht mitnehmen if (i>0) break; // Kontakt nach dem Ziel-Block nicht mitnehmen
} else { } else {
sb.append(tile.x+":"+tile.y); sb.append(tile.id());
} }
} }
id = sb.toString(); id = sb.toString();
@ -170,22 +172,21 @@ public class Route {
} }
return true; return true;
} }
public String json() { public String json() {
JSONObject props = new JSONObject(); JSONObject props = new JSONObject();
JSONArray path = new JSONArray(); Vector<String> tileIds = new Vector<String>();
for (Tile t : this.path) path.put(new JSONObject(Map.of("x",t.x,"y",t.y))); for (Tile t : this.path) tileIds.add(t.id());
props.put(PATH, path); props.put(PATH, tileIds);
JSONArray signals = new JSONArray(); Vector<String> signalIds = new Vector<String>(); // list all signals affecting this route
for (Tile t : this.signals) signals.put(new JSONObject(Map.of("x",t.x,"y",t.y))); for (Tile t : this.signals) signalIds.add(t.id());
props.put(SIGNALS, signals); props.put(SIGNALS, signalIds);
JSONArray turnouts = new JSONArray(); JSONArray turnouts = new JSONArray();
for (Entry<Turnout, State> entry : this.turnouts.entrySet()) { for (Entry<Turnout, State> entry : this.turnouts.entrySet()) {
Turnout t = entry.getKey(); Turnout t = entry.getKey();
turnouts.put(new JSONObject(Map.of("x",t.x,"y",t.y,Turnout.STATE,entry.getValue()))); turnouts.put(new JSONObject(Map.of(Turnout.ID,t.id(),Turnout.STATE,entry.getValue())));
} }
props.put(TURNOUTS, turnouts); props.put(TURNOUTS, turnouts);
@ -193,6 +194,11 @@ public class Route {
return props.toString(); return props.toString();
} }
public static void loadAll(String string, Plan plan) {
// TODO Auto-generated method stub
}
public Route lock(Train train) throws IOException { public Route lock(Train train) throws IOException {
this.train = train; this.train = train;
@ -278,22 +284,14 @@ public class Route {
return form; return form;
} }
public Route start(Block block,Direction from) { public static void saveAll(HashMap<String, Route> routes, String filename) throws IOException {
// add those fields to clone, too! BufferedWriter file = new BufferedWriter(new FileWriter(filename));
contacts = new Vector<Contact>(); for (Entry<String, Route> entry : routes.entrySet()) {
signals = new Vector<Signal>(); Route route = entry.getValue();
path = new Vector<Tile>(); file.write(route.json()+"\n");
turnouts = new HashMap<>(); }
startBlock = block; file.close();
startDirection = from;
path.add(block);
return this;
}
@Override
public String toString() {
return getClass().getSimpleName()+"("+name()+")";
} }
public void setLast(State state) { public void setLast(State state) {
@ -306,6 +304,18 @@ public class Route {
for (Signal signal : signals) signal.state(state == null ? "go" : state); for (Signal signal : signals) signal.state(state == null ? "go" : state);
return this; return this;
} }
public Route start(Block block,Direction from) {
// add those fields to clone, too!
contacts = new Vector<Contact>();
signals = new Vector<Signal>();
path = new Vector<Tile>();
turnouts = new HashMap<>();
startBlock = block;
startDirection = from;
path.add(block);
return this;
}
public Block startBlock() { public Block startBlock() {
return (Block) path.get(0); return (Block) path.get(0);
@ -314,6 +324,11 @@ public class Route {
protected static String t(String txt, Object...fills) { protected static String t(String txt, Object...fills) {
return Translation.get(Application.class, txt, fills); return Translation.get(Application.class, txt, fills);
} }
@Override
public String toString() {
return getClass().getSimpleName()+"("+name()+")";
}
public Route unlock() throws IOException { public Route unlock() throws IOException {
setSignals(Signal.STOP); setSignals(Signal.STOP);

50
src/main/java/de/srsoftware/web4rail/moving/Car.java

@ -1,6 +1,8 @@
package de.srsoftware.web4rail.moving; package de.srsoftware.web4rail.moving;
import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
@ -13,7 +15,7 @@ public class Car {
private static final String ID = "id"; private static final String ID = "id";
private static final String NAME = "name"; private static final String NAME = "name";
private static final String LENGTH = "length"; private static final String LENGTH = "length";
private static HashMap<String,Car> cars = new HashMap<String, Car>(); static HashMap<String,Car> cars = new HashMap<String, Car>();
public int length; public int length;
private String name; private String name;
private String id; private String id;
@ -24,9 +26,27 @@ public class Car {
public Car(String name, String id) { public Car(String name, String id) {
this.name = name; this.name = name;
this.id = id == null ? ""+new Date().getTime() : id; if (id == null) {
cars.put(this.id, this); try { // make sure multiple consecutive creations get different ids
Thread.sleep(1);
} catch (InterruptedException e) {}
id = ""+new Date().getTime();
}
this.id = id;
cars.put(id, this);
}
public static Car get(String nameOrId) {
HashMap<String, Car> cs = cars;
Car car = cars.get(nameOrId);
if (car == null) {
for (Car c : cars.values()) {
if (c.name.equals(nameOrId)) car = c;
}
}
return car;
} }
public String id() { public String id() {
return id; return id;
@ -44,10 +64,32 @@ public class Car {
return name; return name;
} }
public static void loadAll(String filename) throws IOException {
cars.clear();
BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine();
while (line != null) {
JSONObject json = new JSONObject(line);
String name = json.getString(Car.NAME);
String id = json.getString(Car.ID);
Car car = json.has(Locomotive.LOCOMOTIVE) ? new Locomotive(name, id) : new Car(name,id);
car.load(json);
line = file.readLine();
}
file.close();
}
protected void load(JSONObject json) {
if (json.has(ID)) id = json.getString(ID);
if (json.has(LENGTH)) length = json.getInt(LENGTH);
}
public static void saveAll(String filename) throws IOException { public static void saveAll(String filename) throws IOException {
BufferedWriter file = new BufferedWriter(new FileWriter(filename)); BufferedWriter file = new BufferedWriter(new FileWriter(filename));
for (Entry<String, Car> entry: cars.entrySet()) { for (Entry<String, Car> entry: cars.entrySet()) {
file.write(entry.getValue().json()+"\n"); Car c = entry.getValue();
file.write(c.json()+"\n");
} }
file.close(); file.close();
} }

13
src/main/java/de/srsoftware/web4rail/moving/Locomotive.java

@ -5,13 +5,17 @@ import org.json.JSONObject;
public class Locomotive extends Car { public class Locomotive extends Car {
private static final String REVERSE = "reverse"; private static final String REVERSE = "reverse";
private static final String LOCOMOTIVE = "locomotive"; public static final String LOCOMOTIVE = "locomotive";
private boolean reverse = false; private boolean reverse = false;
public Locomotive(String name) { public Locomotive(String name) {
super(name); super(name);
} }
public Locomotive(String name, String id) {
super(name,id);
}
@Override @Override
public JSONObject json() { public JSONObject json() {
JSONObject json = super.json(); JSONObject json = super.json();
@ -20,7 +24,12 @@ public class Locomotive extends Car {
json.put(LOCOMOTIVE, loco); json.put(LOCOMOTIVE, loco);
return json; return json;
} }
@Override
protected void load(JSONObject json) {
super.load(json);
if (json.has(REVERSE)) reverse = json.getBoolean(REVERSE);
}
public void setSpeed(int v) { public void setSpeed(int v) {
// TODO Auto-generated method stub // TODO Auto-generated method stub

43
src/main/java/de/srsoftware/web4rail/moving/Train.java

@ -1,6 +1,8 @@
package de.srsoftware.web4rail.moving; package de.srsoftware.web4rail.moving;
import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
@ -38,8 +40,6 @@ public class Train {
private static final String NAME = "name"; private static final String NAME = "name";
private String name = null; private String name = null;
private static final String BLOCK = "block";
private Block block = null;
private static final String ROUTE = "route"; private static final String ROUTE = "route";
public Route route; public Route route;
@ -56,7 +56,8 @@ public class Train {
private static final String LOCOS = "locomotives"; private static final String LOCOS = "locomotives";
private Vector<Locomotive> locos = new Vector<Locomotive>(); private Vector<Locomotive> locos = new Vector<Locomotive>();
private Block block = null;
private class Autopilot extends Thread{ private class Autopilot extends Thread{
@Override @Override
public void run() { public void run() {
@ -90,16 +91,21 @@ public class Train {
private Autopilot autopilot = null; private Autopilot autopilot = null;
public Train(Locomotive loco) { public Train(Locomotive loco) {
id = new Date().getTime(); this(loco,null);
}
public Train(Locomotive loco, Long id) {
if (id == null) id = new Date().getTime();
this.id = id;
add(loco); add(loco);
trains.put(id, this); trains.put(id, this);
} }
private JSONObject json() { private JSONObject json() {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put(ID, id); json.put(ID, id);
json.put(NAME,name); json.put(NAME,name);
if (block != null) json.put(BLOCK, block.id());
if (route != null) json.put(ROUTE, route.id()); if (route != null) json.put(ROUTE, route.id());
if (direction != null) json.put(DIRECTION, direction); if (direction != null) json.put(DIRECTION, direction);
json.put(PUSH_PULL, pushPull); json.put(PUSH_PULL, pushPull);
@ -154,6 +160,11 @@ public class Train {
this.block = block; this.block = block;
} }
public static Train get(long id) {
return trains.get(id);
}
public Train heading(Direction dir) { public Train heading(Direction dir) {
direction = dir; direction = dir;
return this; return this;
@ -165,6 +176,28 @@ public class Train {
for (Car car : cars) result += car.length; for (Car car : cars) result += car.length;
return result; return result;
} }
public static void loadAll(String filename) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine();
while (line != null) {
JSONObject json = new JSONObject(line);
long id = json.getLong(ID);
Train train = new Train(null,id);
train.load(json);
line = file.readLine();
}
file.close();
}
private void load(JSONObject json) {
pushPull = json.getBoolean(PUSH_PULL);
for (Object id : json.getJSONArray(LOCOS)) add((Locomotive) Car.get((String)id));
for (Object id : json.getJSONArray(CARS)) add(Car.get((String)id));
}
public String name() { public String name() {
String result = (name != null ? name : locos.firstElement().name()); String result = (name != null ? name : locos.firstElement().name());

33
src/main/java/de/srsoftware/web4rail/tiles/Block.java

@ -14,11 +14,13 @@ import de.srsoftware.web4rail.tags.Checkbox;
public abstract class Block extends StretchableTile{ public abstract class Block extends StretchableTile{
private static final String NAME = "name"; private static final String NAME = "name";
private static final String ALLOW_TURN = "allowTurn";
public String name = "Block"; public String name = "Block";
private Train train;
private static final String ALLOW_TURN = "allowTurn";
public boolean turnAllowed = false; public boolean turnAllowed = false;
private static final String TRAIN = "train";
@Override @Override
public JSONObject config() { public JSONObject config() {
JSONObject config = super.config(); JSONObject config = super.config();
@ -27,16 +29,31 @@ public abstract class Block extends StretchableTile{
} }
@Override @Override
public void configure(JSONObject config) { public boolean free() {
super.configure(config); return train == null && super.free();
if (config.has(NAME)) name = config.getString(NAME);
} }
@Override @Override
public boolean free() { public JSONObject json() {
return train == null && super.free(); JSONObject json = super.json();
json.put(NAME, name);
json.put(ALLOW_TURN, turnAllowed);
if (train != null) json.put(TRAIN, train.id);
return json;
} }
@Override
protected Tile load(JSONObject json) throws IOException {
super.load(json);
name = json.has(NAME) ? json.getString(NAME) : "Block";
turnAllowed = json.has(ALLOW_TURN) && json.getBoolean(ALLOW_TURN);
if (json.has(TRAIN)) {
Train tr = Train.get(json.getLong(TRAIN));
train(tr);
}
return this;
}
@Override @Override
public Tag propForm() { public Tag propForm() {
Tag form = super.propForm(); Tag form = super.propForm();

15
src/main/java/de/srsoftware/web4rail/tiles/StretchableTile.java

@ -1,5 +1,6 @@
package de.srsoftware.web4rail.tiles; package de.srsoftware.web4rail.tiles;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -19,9 +20,17 @@ public abstract class StretchableTile extends Tile {
} }
@Override @Override
public void configure(JSONObject config) { public JSONObject json() {
super.configure(config); JSONObject json = super.json();
if (config.has(LENGTH)) setLength(config.getInt(LENGTH)); if (length > 1) json.put(LENGTH, length);
return json;
}
@Override
protected Tile load(JSONObject json) throws IOException {
super.load(json);
if (json.has(LENGTH)) length = json.getInt(LENGTH);
return this;
} }
@Override @Override

86
src/main/java/de/srsoftware/web4rail/tiles/Tile.java

@ -1,9 +1,12 @@
package de.srsoftware.web4rail.tiles; package de.srsoftware.web4rail.tiles;
import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -31,20 +34,20 @@ import de.srsoftware.web4rail.tags.Radio;
public abstract class Tile { public abstract class Tile {
private static final String ID = "id"; public static final String ID = "id";
private static final String TYPE = "type"; private static final String TYPE = "type";
private static final String LOCKED = "locked"; private static final String LOCKED = "locked";
private static final String POS = "pos"; private static final String POS = "pos";
private static final String X = "x"; private static final String X = "x";
private static final Object Y = "y"; private static final String Y = "y";
public int x = -1,y = -1; public int x = -1,y = -1;
private static final String ROUTE = "route"; private static final String ROUTE = "route";
protected Route route; protected Route route;
private static final String OCCUPIED = "occupied"; private static final String OCCUPIED = "occupied";
private Train train; protected Train train;
private static final String ONEW_WAY = "one_way"; private static final String ONEW_WAY = "one_way";
protected Direction oneWay = null; protected Direction oneWay = null;
@ -63,17 +66,6 @@ public abstract class Tile {
if (train != null) classes.add(OCCUPIED); if (train != null) classes.add(OCCUPIED);
return classes; return classes;
} }
public JSONObject json() {
JSONObject json = new JSONObject();
json.put(ID, id());
json.put(TYPE, getClass().getSimpleName());
JSONObject pos = new JSONObject(Map.of(X,x,Y,y));
json.put(POS, pos);
if (route != null) json.put(ROUTE, route.id());
if (oneWay != null) json.put(ONEW_WAY, oneWay);
return json;
}
public void add(Route route) { public void add(Route route) {
this.routes.add(route); this.routes.add(route);
@ -95,9 +87,6 @@ public abstract class Tile {
return new HashMap<>(); return new HashMap<>();
} }
public void configure(JSONObject config) {}
public boolean free() { public boolean free() {
return route == null; return route == null;
} }
@ -107,20 +96,64 @@ public abstract class Tile {
} }
public String id() { public String id() {
return "tile-"+x+"-"+y; return x+":"+y;
}
private static void inflate(String clazz, JSONObject json, Plan plan) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException {
clazz = Tile.class.getName().replace(".Tile", "."+clazz);
Tile tile = (Tile) Tile.class.getClassLoader().loadClass(clazz).getDeclaredConstructor().newInstance();
tile.plan(plan);
tile.load(json);
plan.set(tile.x, tile.y, tile);
}
public JSONObject json() {
JSONObject json = new JSONObject();
json.put(TYPE, getClass().getSimpleName());
JSONObject pos = new JSONObject(Map.of(X,x,Y,y));
json.put(POS, pos);
if (route != null) json.put(ROUTE, route.id());
if (oneWay != null) json.put(ONEW_WAY, oneWay);
return json;
} }
public int len() { public int len() {
return 1; return 1;
} }
public static void loadAll(String filename, Plan plan) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine();
while (line != null) {
JSONObject json = new JSONObject(line);
String clazz = json.getString(TYPE);
try {
Tile.inflate(clazz,json,plan);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
line = file.readLine();
}
file.close();
}
protected Tile load(JSONObject json) throws IOException {
JSONObject pos = json.getJSONObject(POS);
x = pos.getInt(X);
y = pos.getInt(Y);
return this;
}
public void lock(Route route) throws IOException { public void lock(Route route) throws IOException {
this.route = route; this.route = route;
plan.place(this); plan.place(this);
} }
public void plan(Plan plan) { public Tile plan(Plan plan) {
this.plan = plan; this.plan = plan;
return this;
} }
public Tile position(int x, int y) { public Tile position(int x, int y) {
@ -309,4 +342,19 @@ public abstract class Tile {
} }
return this; return this;
} }
/*
if (clazz == null) throw new NullPointerException(TILE+" must not be null!");
Class<Tile> tc = Tile.class;
clazz = tc.getName().replace(".Tile", "."+clazz);
Tile tile = (Tile) tc.getClassLoader().loadClass(clazz).getDeclaredConstructor().newInstance();
if (tile instanceof Eraser) {
Tile erased = get(x,y,true);
remove(erased);
return erased == null ? null : t("Removed {}.",erased);
}
if (configJson != null) tile.configure(new JSONObject(configJson));
set(x, y, tile);
return t("Added {}",tile.getClass().getSimpleName());
}*/
} }

Loading…
Cancel
Save