Skip to content

Instantly share code, notes, and snippets.

@buie
Created October 25, 2015 04:24
Show Gist options
  • Save buie/5b686006f40c551bd630 to your computer and use it in GitHub Desktop.
Save buie/5b686006f40c551bd630 to your computer and use it in GitHub Desktop.
package cellsociety_team20;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cell.Cell;
import parameter.IParameter;
import simulation.Simulation;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLEditor {
//simulation parameters
private int mySimulationMode;
private String myAuthor;
private double mySimulationSpeed;
private int myDefaultState;
private int myCellShape;
private int myGridEdge;
private int myGridOutlineVisible;
private int myRandomlyGenerated;
private int myNumCellsOccupied;
private int myOccupiedCellState;
private Map<String, String> mySimParameters;
private String myInputFileName;
private Grid grid;
/**
* @param inputFileName
*/
public XMLEditor(String inputFileName) {
myInputFileName = inputFileName;
readGridFromFile();
}
public XMLEditor(File inputFile) {
myInputFileName = inputFile.getAbsolutePath();
readGridFromFile();
}
/**
*
*/
public void readGridFromFile() {
initializeDefaults();
try {
File inputFile = new File(myInputFileName);
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
if(doc == null){
throw new IllegalArgumentException("File not found.");
}
doc.getDocumentElement().normalize();
Element rootNode = (Element) doc.getElementsByTagName("grid").item(0);
int gridHeight = Integer.parseInt(rootNode.getAttribute("h"));
int gridWidth = Integer.parseInt(rootNode.getAttribute("w"));
Element simulationElement = (Element) doc.getElementsByTagName("simulation").item(0);
if(simulationElement != null){
mySimulationMode = Integer.parseInt(simulationElement.getAttribute("mode"));
} else throw new IllegalArgumentException("No simulation mode set");
extractParameters(doc);
if(myRandomlyGenerated == 1) {
grid = new GridSquare(gridWidth, gridHeight, myDefaultState, myNumCellsOccupied, myOccupiedCellState, true);
}
grid = new GridSquare(gridWidth, gridHeight, new Cell(myDefaultState));
grid.setWrap(myGridEdge);
populateGrid(doc);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void writeGridToFile(Grid grid, File outputFile, Simulation currentSim){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("grid");
doc.appendChild(root);
root.setAttribute("w", Integer.toString(grid.getGridWidth()));
root.setAttribute("h", Integer.toString(grid.getGridHeight()));
Element simulation = doc.createElement("simulation");
simulation.setAttribute("mode", Integer.toString(mySimulationMode));
root.appendChild(simulation);
writeSimulationParametersToXML(doc, simulation, currentSim);
writeGridToXML(doc, root, grid);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource dp = new DOMSource(doc);
StreamResult result = new StreamResult(outputFile);
transformer.transform(dp, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
private void writeGridToXML(Document doc, Element root, Grid grid){
for (cell.Cell cell : grid.getCellIterator()) {
if(cell.getState() != myDefaultState) {
Element curCell = doc.createElement("cell");
curCell.setAttribute("x", Integer.toString(cell.getX()));
curCell.setAttribute("y", Integer.toString(cell.getY()));
curCell.appendChild(doc.createTextNode(Integer.toString(cell.getState())));
root.appendChild(curCell);
}
}
}
private void writeSimulationParametersToXML(Document doc, Element sim, Simulation currentSim){
writeStringToXML(doc, "author", sim, myAuthor);
writeDoubleToXML(doc, "simulationSpeed", sim, mySimulationSpeed);
writeIntegerToXML(doc, "defaultState", sim, myDefaultState);
writeSimulationSubParametersToXML(doc, writeStringToXML(doc, "parameters", sim, ""), currentSim);
writeIntegerToXML(doc, "cellShape", sim, myCellShape);
writeIntegerToXML(doc, "gridEdge", sim, myGridEdge);
writeIntegerToXML(doc, "gridOutlineVisible", sim, myGridOutlineVisible);
writeIntegerToXML(doc, "randomlyGenerated", sim, myRandomlyGenerated);
}
private void writeSimulationSubParametersToXML(Document doc, Element params, Simulation currentSim){
List<IParameter> parameterList = currentSim.getParameters();
for(IParameter param : parameterList){
Element e = doc.createElement("param");
e.setAttribute("name", param.getName());
e.appendChild(doc.createTextNode(param.toString()));
params.appendChild(e);
}
}
private void writeDoubleToXML(Document doc, String tag, Element parent, double contents){
Element e = doc.createElement(tag);
e.appendChild(doc.createTextNode(Double.toString(contents)));
parent.appendChild(e);
}
private void writeIntegerToXML(Document doc, String tag, Element parent, int contents){
Element e = doc.createElement(tag);
e.appendChild(doc.createTextNode(Integer.toString(contents)));
parent.appendChild(e);
}
private Element writeStringToXML(Document doc, String tag, Element parent, String contents){
Element e = doc.createElement(tag);
e.appendChild(doc.createTextNode(contents));
parent.appendChild(e);
return e;
}
private void initializeDefaults(){
mySimulationSpeed = 1;
myDefaultState = 0;
myCellShape = 0;
myGridEdge = 0;
myGridOutlineVisible = 1;
myRandomlyGenerated = 0;
}
private void populateGrid(Document doc) {
NodeList cells = doc.getElementsByTagName("cell");
for (int i = 0; i < cells.getLength(); i++) {
Node currentCell = cells.item(i);
Element eElement = (Element) currentCell;
if (eElement.getNodeName() == "cell") {
int xPos = Integer.parseInt(eElement.getAttribute("x"));
int yPos = Integer.parseInt(eElement.getAttribute("y"));
if((xPos >= grid.getGridWidth()) || (yPos >= grid.getGridHeight())){
throw new IllegalArgumentException("Attempting to place cell out of grid bounds");
}
int cellState = Integer.parseInt(eElement.getTextContent());
if(Double.isNaN(cellState)){
throw new IllegalArgumentException("Invalid cell state");
}
grid.setGridCell(xPos, yPos, cellState, mySimulationMode);
}
}
}
private void extractParameters(Document doc) {
myAuthor = getStringFromXML(doc, "author");
mySimulationSpeed = getDoubleFromXML(doc, "simulationSpeed");
myDefaultState = getIntegerFromXML(doc, "defaultState");
myCellShape = getIntegerFromXML(doc, "cellShape");
myGridEdge = getIntegerFromXML(doc, "gridEdge");
myGridOutlineVisible = getIntegerFromXML(doc, "gridOutlineVisible");
myRandomlyGenerated = getIntegerFromXML(doc, "randomlyGenerated");
if(myRandomlyGenerated != 0) {
myNumCellsOccupied = getIntegerFromXML(doc, "numCellsOccupied");
myOccupiedCellState = getIntegerFromXML(doc, "occupiedCellState");
}
Node param;
String name;
String value;
Map<String, String> extracted = new HashMap<String, String>();
Node params = doc.getElementsByTagName("parameters").item(0);
if (params != null) {
for (int i=0; i<params.getChildNodes().getLength(); i++) {
param = params.getChildNodes().item(i);
if (!param.hasAttributes()) {
continue;
}
name = param.getAttributes().getNamedItem("name").getTextContent();
value = param.getTextContent();
extracted.put(name, value);
System.out.println(String.format("Param '%s' => '%s'", name, value));
}
}
mySimParameters = extracted;
}
private int getIntegerFromXML(Document doc, String field) {
System.out.println("Attempting to read in " + field);
return Integer.parseInt(doc.getElementsByTagName(field).item(0).getTextContent());
}
private double getDoubleFromXML(Document doc, String field) {
return Double.parseDouble((doc.getElementsByTagName(field).item(0)).getTextContent());
}
private String getStringFromXML(Document doc, String field) {
return doc.getElementsByTagName(field).item(0).getTextContent();
}
/**
* @return
*/
public Grid getGrid() {
return grid;
}
/**
*
*/
public void printGrid() {
grid.printGrid();
}
/**
* @return
*/
public int getSimulationMode() {
return mySimulationMode;
}
/**
* @return
*/
public double getSimulationSpeed() {
return mySimulationSpeed;
}
public Map<String, String> getSimParameters() {
return mySimParameters;
}
/**
*
*/
public void dumpConfigurations() {
System.out.println("Simulation mode " + mySimulationMode);
System.out.println("Author " + myAuthor);
System.out.println("Simulation speed " + mySimulationSpeed);
System.out.println("Default state " + myDefaultState);
System.out.println("Cell shape " + myCellShape);
System.out.println("Grid edge mode " + myGridEdge);
System.out.println("Grid outline visibility " + myGridOutlineVisible);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment