Commit b4194b42 authored by Stefan Michel's avatar Stefan Michel

an gui angebunden muss noch getestet werden

parent 58f97409
......@@ -6,6 +6,7 @@ import controller.TerrainController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import model.DatabaseManager;
import model.Terrain;
import model.ThreadManager;
import view.MainViewCreationFX;
......@@ -21,6 +22,7 @@ public class Main extends Application {
private Terrain terrain;
private TerrainController terrainController;
private HamsterController hamsterController;
private DatabaseManager databaseManager;
public static final List<String> activePrograms = new ArrayList<>();
private IOController ioController;
ThreadManager threadManager;
......@@ -38,11 +40,13 @@ public class Main extends Application {
IOController ioController = new IOController(terrain);
HamsterController hamsterController = new HamsterController(terrain);
ThreadManager threadManager = new ThreadManager(terrain, ioController);
DatabaseManager databaseManager = new DatabaseManager();
terrain.setHamsterName(name);
ioController.setUpHamster(name);
Stage newStage = new Stage();
Scene scene = new Scene(new MainViewCreationFX(terrain, terrainController, ioController, hamsterController, threadManager), 1000, 500);
Scene scene = new Scene(new MainViewCreationFX(terrain, terrainController, ioController, hamsterController,
threadManager, databaseManager), 1000, 500);
newStage.setScene(scene);
newStage.setTitle(terrain.getHamsterName());
newStage.show();
......@@ -59,6 +63,8 @@ public class Main extends Application {
ioController = new IOController(terrain);
hamsterController = new HamsterController(terrain);
threadManager = new ThreadManager(terrain, ioController);
databaseManager = new DatabaseManager();
//TEST-INIT
terrain.setHamsterPostion(0, 0);
......@@ -69,7 +75,8 @@ public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new MainViewCreationFX(terrain, terrainController, ioController, hamsterController, threadManager), 1000, 500);
Scene scene = new Scene(new MainViewCreationFX(terrain, terrainController, ioController, hamsterController,
threadManager, databaseManager), 1000, 500);
primaryStage.setScene(scene);
primaryStage.setTitle(terrain.getHamsterName());
primaryStage.show();
......
package controller;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import model.DatabaseManager;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ChooseEntryDialogBox {
private List<String> exampleList;
private TextArea textArea;
private TerrainController terrainController;
private DatabaseManager databaseManager;
public ChooseEntryDialogBox(List<String> exampleList, TextArea textArea, TerrainController terrainController, DatabaseManager databaseManager) {
this.exampleList = exampleList;
this.textArea = textArea;
this.terrainController = terrainController;
this.databaseManager = databaseManager;
setFileNameDialogBox();
}
/* angepasst von http://code.makery.ch/blog/javafx-dialogs-official/ */
private void setFileNameDialogBox() {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("suche nach Tag");
dialog.setHeaderText("Suche nach einem bestimmten Tag");
// Set the button types.
ButtonType okayButtonType = new ButtonType("Bestaetigen", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Abbrechen", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okayButtonType, cancelButtonType);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
ComboBox<String> comboBox = new ComboBox<>(FXCollections.observableArrayList(exampleList));
comboBox.setPromptText(exampleList.get(0));
grid.add(new Label("Tag:"), 0, 0);
grid.add(comboBox, 1, 0);
Node okayButton = dialog.getDialogPane().lookupButton(okayButtonType);
okayButton.setDisable(false);
dialog.getDialogPane().setContent(grid);
Platform.runLater(comboBox::requestFocus);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == okayButtonType) {
return comboBox.getValue();
}
return null;
});
Optional<String> result = dialog.showAndWait();
result.ifPresent(res -> {
Map.Entry<String, String> entry = databaseManager.queryExampleById(Integer.parseInt(res));
textArea.setText(entry.getKey());
terrainController.loadTerrainFromString(entry.getValue());
});
}
}
package controller;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import model.DatabaseManager;
import model.Terrain;
import java.util.Optional;
public class DataBaseEntryDialogBox {
private DatabaseManager databaseManager;
private TerrainController terrainController;
private String text;
public DataBaseEntryDialogBox(DatabaseManager databaseManager, Terrain terrain, TerrainController terrainController,
String text) {
this.databaseManager = databaseManager;
this.terrainController = terrainController;
this.text = text;
setFileNameDialogBox(terrain);
}
/* angepasst von http://code.makery.ch/blog/javafx-dialogs-official/ */
private void setFileNameDialogBox(Terrain terrain) {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("setze die Tags");
dialog.setHeaderText("Setzen Sie beliebig viele Tags \n (mit einer Leerstelle werden Tags getrennt)");
// Set the button types.
ButtonType okayButtonType = new ButtonType("Bestaetigen", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Abbrechen", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okayButtonType, cancelButtonType);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField filename = new TextField();
filename.setPromptText("Dateiname");
grid.add(new Label("Dateiname:"), 0, 0);
grid.add(filename, 1, 0);
// Enable/Disable login button depending on whether a username was entered.
Node okayButton = dialog.getDialogPane().lookupButton(okayButtonType);
okayButton.setDisable(true);
filename.textProperty().addListener((observable, oldValue, newValue) -> {
okayButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(filename::requestFocus);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == okayButtonType) {
return filename.getText();
}
return null;
});
Optional<String> result = dialog.showAndWait();
result.ifPresent(res -> {
boolean worked;
res = res.trim();
String[] tags = res.split(" ");
terrainController.parseXML(terrain.getName());
System.out.println(terrainController.loadXMLToString(terrain.getName()));
worked = databaseManager.insertExample(text.trim(), terrainController.loadXMLToString(terrain.getName()), tags);
if (!worked)
new Alert(Alert.AlertType.ERROR, "Fehler!"
+ " Hast du dieses Beispiel schonmal gespeichert?", okayButtonType).show();
else
new Alert(Alert.AlertType.CONFIRMATION, "Beispiel gespeichert!", okayButtonType).show();
});
}
private boolean checkString(String s) {
return !s.isEmpty() && Character.isAlphabetic(s.charAt(0)) && s.matches("[A-Za-z0-9]+");
}
}
package controller;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import model.DatabaseManager;
import model.Terrain;
import java.util.List;
import java.util.Optional;
public class GetEntryByTagDialogBox {
private DatabaseManager databaseManager;
private TerrainController terrainController;
private TextArea textArea;
public GetEntryByTagDialogBox(DatabaseManager databaseManager, Terrain terrain, TerrainController terrainController, TextArea textArea) {
this.databaseManager = databaseManager;
this.terrainController = terrainController;
this.textArea = textArea;
setFileNameDialogBox(terrain);
}
/* angepasst von http://code.makery.ch/blog/javafx-dialogs-official/ */
private void setFileNameDialogBox(Terrain terrain) {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("suche nach Tag");
dialog.setHeaderText("Suche nach einem bestimmten Tag");
// Set the button types.
ButtonType okayButtonType = new ButtonType("Bestaetigen", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Abbrechen", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okayButtonType, cancelButtonType);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField filename = new TextField();
filename.setPromptText("Tag");
grid.add(new Label("Tag:"), 0, 0);
grid.add(filename, 1, 0);
Node okayButton = dialog.getDialogPane().lookupButton(okayButtonType);
okayButton.setDisable(true);
filename.textProperty().addListener((observable, oldValue, newValue) -> {
okayButton.setDisable(newValue.trim().isEmpty() || newValue.contains(" "));
});
dialog.getDialogPane().setContent(grid);
Platform.runLater(filename::requestFocus);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == okayButtonType) {
return filename.getText();
}
return null;
});
Optional<String> result = dialog.showAndWait();
result.ifPresent(res -> {
List<String> exampleList = databaseManager.queryByTag(res.trim());
if (exampleList.isEmpty()) {
new Alert(Alert.AlertType.ERROR, "Suche hat keine Ergebnis gefunden").show();
} else {
new ChooseEntryDialogBox(exampleList, textArea, terrainController, databaseManager);
}
});
}
}
......@@ -6,6 +6,7 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
......@@ -76,9 +77,12 @@ public class TerrainController {
}
}
public void parseXML() {
public void parseXMLAndGetTerrainName() {
String terrainName = new SetTerrainNameDialogBox().setTerrainNameDialogBox();
parseXML(terrainName);
}
public void parseXML(String terrainName) {
try (FileOutputStream fileOutputStream = new FileOutputStream("terrains/" + terrainName + ".xml")) {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(fileOutputStream);
......@@ -145,7 +149,6 @@ public class TerrainController {
} catch (IOException e) {
e.printStackTrace();
}
}
//abgewandelt aus https://stackoverflow.com/questions/7392646/parsing-xml-in-java-gettextcontent-and-getnodevalue-only-return-n-t-an
......@@ -173,52 +176,89 @@ public class TerrainController {
DocumentBuilder parser = dbf.newDocumentBuilder();
File input = new File(path);
Document document = parser.parse(input);
Element docElement = document.getDocumentElement();
loadTerrainFromXMLDoc(parser.parse(input));
} catch (ParserConfigurationException e) {
e.printStackTrace();
terrain = rollback;
} catch (SAXException e) {
e.printStackTrace();
terrain = rollback;
} catch (IOException e) {
e.printStackTrace();
terrain = rollback;
}
}
//TODO: setHamsterCorns hinzufuegen
terrain.setName(getValueByTag("name", docElement));
terrain.setHamsterName(getValueByTag("hamstername", docElement));
terrain.setMaxCols(Integer.parseInt(getValueByTag("maxcols", docElement)));
terrain.setMaxRows(Integer.parseInt(getValueByTag("maxrows", docElement)));
terrain.setHamsterPostion(Integer.parseInt(getValueByTag("hamstercol", docElement)), Integer.parseInt(getValueByTag("hamsterrow", docElement)));
terrain.setHamsterDirection(Integer.parseInt(getValueByTag("hamsterdirection", docElement)));
public void loadTerrainFromString(String string) {
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(string)));
loadTerrainFromXMLDoc(doc);
} catch (Exception e) {
int[][] map = new int[terrain.getMaxCols()][terrain.getMaxRows()];
}
}
public void loadTerrainFromXMLDoc(Document document) {
Element docElement = document.getDocumentElement();
NodeList columnList = docElement.getElementsByTagName("map").item(0).getChildNodes();
//TODO: setHamsterCorns hinzufuegen
terrain.setName(getValueByTag("name", docElement));
terrain.setHamsterName(getValueByTag("hamstername", docElement));
terrain.setMaxCols(Integer.parseInt(getValueByTag("maxcols", docElement)));
terrain.setMaxRows(Integer.parseInt(getValueByTag("maxrows", docElement)));
terrain.setHamsterPostion(Integer.parseInt(getValueByTag("hamstercol", docElement)), Integer.parseInt(getValueByTag("hamsterrow", docElement)));
terrain.setHamsterDirection(Integer.parseInt(getValueByTag("hamsterdirection", docElement)));
for (int i = 0; i < columnList.getLength(); i++) {
NodeList rows = columnList.item(i).getChildNodes();
for (int j = 0; j < rows.getLength(); j++) {
Node node = rows.item(j);
int[][] map = new int[terrain.getMaxCols()][terrain.getMaxRows()];
if (node.getNodeType() == Node.ELEMENT_NODE) {
int column = Integer.parseInt(columnList.item(i).getAttributes().getNamedItem("index").getNodeValue());
int row = Integer.parseInt(node.getAttributes().getNamedItem("index").getNodeValue());
System.out.print("Value [" + column + "] [" + row + "] : ");
map[column][row] = Integer.parseInt(node.getTextContent());
NodeList columnList = docElement.getElementsByTagName("map").item(0).getChildNodes();
System.out.println(node.getTextContent());
}
for (int i = 0; i < columnList.getLength(); i++) {
NodeList rows = columnList.item(i).getChildNodes();
for (int j = 0; j < rows.getLength(); j++) {
Node node = rows.item(j);
if (node.getNodeType() == Node.ELEMENT_NODE) {
int column = Integer.parseInt(columnList.item(i).getAttributes().getNamedItem("index").getNodeValue());
int row = Integer.parseInt(node.getAttributes().getNamedItem("index").getNodeValue());
System.out.print("Value [" + column + "] [" + row + "] : ");
map[column][row] = Integer.parseInt(node.getTextContent());
System.out.println(node.getTextContent());
}
System.out.println();
}
System.out.println();
}
terrain.setMap(map);
terrain.setMap(map);
} catch (ParserConfigurationException e) {
e.printStackTrace();
terrain = rollback;
} catch (SAXException e) {
e.printStackTrace();
terrain = rollback;
} catch (IOException e) {
}
public String loadXMLToString(String name) {
try {
// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
// Document document = docBuilder.parse("terrains/" + name + ".xml");
// return document.getDocumentElement().toString();
//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File("terrains/" + name + ".xml")));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line.trim());
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
terrain = rollback;
}
return null;
}
/**
......
package model;
import java.util.List;
import java.util.Map;
public class DatabaseManager {
DerbyDatabase database = new DerbyDatabase();
private DerbyDatabase database;
public DatabaseManager() {
database = new DerbyDatabase();
}
public boolean insertExample(String code, String terrain, String... tags) {
return database.updateExample(code, terrain, tags);
}
public List<String> queryByTag(String tag) {
return database.queryExamples(tag);
}
public Map.Entry<String, String> queryExampleById(int id) {
return database.queryExampleById(id);
}
}
package model;
import java.sql.*;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
......@@ -17,7 +19,7 @@ public class DerbyDatabase {
String dbName = "StefanHamsterDB";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
String createExampleTable = "CREATE TABLE Example (e_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), code VARCHAR(128), terrain VARCHAR(128))";
String createExampleTable = "CREATE TABLE Example (e_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), code VARCHAR(1000), terrain VARCHAR(8000))";
String createTagTable = "CREATE TABLE Tags (t_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), name VARCHAR (64))";
String createExampleTagsTable = "CREATE TABLE ExampleTags (e_id INT NOT NULL , t_id INT NOT NULL)";
......@@ -32,39 +34,23 @@ public class DerbyDatabase {
"WHERE t.name IN (?)";
String queryExampleId = "SELECT E_ID FROM EXAMPLE WHERE CODE = ? AND TERRAIN = ?";
String queryTag = "SELECT T_ID FROM tags WHERE name = ?";
String queryExampleById = "SELECT CODE, TERRAIN FROM EXAMPLE WHERE E_ID = ?";
public static void main(String[] args) {
DerbyDatabase derbyDatabase = new DerbyDatabase();
derbyDatabase.setUpDB();
boolean hase = derbyDatabase.updateExample("bullshit", "hase", "ski", "auto", "handy");
System.out.println(hase);
System.out.println("query result: " + derbyDatabase.queryExamples("ski"));
public DerbyDatabase() {
setUpDB();
}
public void setUpDB() {
private void setUpDB() {
try {
System.out.println("Start");
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
createTables(conn);
ResultSet resultSet = stmt.executeQuery("SELECT * FROM EXAMPLE");
printResultSet(resultSet);
resultSet = stmt.executeQuery("SELECT * FROM TAGS");
printResultSet(resultSet);
printResultSet(stmt.executeQuery("SELECT * FROM EXAMPLETAGS"));
resultSet.close();
stmt.close();
conn.close();
System.out.println("Ende");
} catch (Exception th) {
th.printStackTrace();
}
......@@ -231,6 +217,26 @@ public class DerbyDatabase {
return false;
}
}
public Map.Entry<String, String> queryExampleById(int id) {
Map.Entry<String, String> entry = null;
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionURL);
PreparedStatement preparedStatement = conn.prepareStatement(queryExampleById);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
String code = resultSet.getString(1);
String terrain = resultSet.getString(2);
entry = new AbstractMap.SimpleEntry<>(code, terrain);
} catch (Exception e) {
}
return entry;
}
}
......@@ -13,10 +13,7 @@ import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import model.Hamster;
import model.Invisible;
import model.Terrain;
import model.ThreadManager;
import model.*;
import java.io.File;
import java.io.IOException;
......@@ -41,7 +38,8 @@ public class MainViewCreationFX extends VBox implements Observer {
private TerrainController terrainController;
private IOController ioController;
private HamsterController hamsterController;
Label footer;
private DatabaseManager databaseManager;
private Label footer;
private Terrain terrain;
private TextArea textArea;
private ContextMenu contextMenu;
......@@ -50,12 +48,13 @@ public class MainViewCreationFX extends VBox implements Observer {
private Slider slider;
public MainViewCreationFX(Terrain terrain, TerrainController terrainController, IOController ioController,
HamsterController hamsterController, ThreadManager threadManager) {
HamsterController hamsterController, ThreadManager threadManager, DatabaseManager databaseManager) {
this.terrainController = terrainController;
this.ioController = ioController;
this.hamsterController = hamsterController;
this.threadManager = threadManager;
this.databaseManager = databaseManager;
this.terrain = terrain;
terrain.addObserver(this);
......@@ -191,8 +190,12 @@ public class MainViewCreationFX extends VBox implements Observer {
//MenuItems werden mit Grafiken und Accelelatoren gebaut
MenuItem speichern = new MenuItem("_Speichern...");
speichern.setOnAction(event -> {
new DataBaseEntryDialogBox(databaseManager, terrain, terrainController, textArea.getText());
});
MenuItem laden = new MenuItem("_Laden...");
laden.setOnAction(event -> new GetEntryByTagDialogBox(databaseManager, terrain, terrainController, textArea));
return new Menu("_Beispiele", null, speichern, laden);
}
......@@ -242,7 +245,7 @@ public class MainViewCreationFX extends VBox implements Observer {
java.setOnAction(event -> ioController.saveFile("name"));
seri.setOnAction(event -> terrainController.serializeTerrain());
xml.setOnAction(event -> terrainController.parseXML());
xml.setOnAction(event -> terrainController.parseXMLAndGetTerrainName());
Menu laden = new Menu("_Laden");
MenuItem xmlladen = new MenuItem("_XML");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment