Move around existing Java class to convert into Python modules.

This commit is contained in:
Dorian 2014-07-30 18:30:14 -04:00
parent c51123767c
commit 5d2ecec3fb
33 changed files with 0 additions and 2019 deletions

View File

@ -1,81 +0,0 @@
/*****************************************************************************
GameActivity.java - The activity that handles the actual checkers games.
*****************************************************************************
*****************************************************************************
This file is part of justCheckers.
justCheckers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
justCheckers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with justCheckers. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package org.justcheckers.android;
import org.justcheckers.game.Game;
import org.justcheckers.game.Rulebook;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class GameActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the user interface for the main menu.
// Weirdness in orientation values in Galaxy Tab.
// http://www.ceveni.com/2009/08/how-to-get-screen-orientation-in.html
int screenOrientation =
this.getWindowManager().getDefaultDisplay().getOrientation();
//TODO: Cleaner per device implementation. Developed on Samsung Galaxy S Vibrant.
if (screenOrientation == 1) {
// Counter-clockwise landscape
this.setContentView(R.layout.game_screen_landscape);
} else if (screenOrientation == 3) {
// Clockwise landscape
this.setContentView(R.layout.game_screen_landscape);
} else if (screenOrientation == 0) {
// Portrait for Samsung Galaxy devices.
this.setContentView(R.layout.game_screen_portrait);
}
}
public void onClick(View view) {
//TODO: Stub
}
/**
* Starts a new game with the specified rulebook.
*
* @param rules
* The rules for the new game.
*/
public static void startGame(Rulebook rules) {
Game currentGame = new Game(rules.getCheckersVariant());
/* Instead of specialized UI commands, just a single method
that updates the UI with the current state of the game. */
// ui.setCurrentGame(currentGame);
//
// // Current until different game types are added.
// ui.clearBoard();
// ui.placePieces();
}
}

View File

@ -1,140 +0,0 @@
/*****************************************************************************
MenuActivity.java - The activity that provides the main menu for the app.
*****************************************************************************
*****************************************************************************
This file is part of justCheckers.
justCheckers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
justCheckers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with justCheckers. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package org.justcheckers.android;
import org.justcheckers.common.GlobalConstants;
import org.justcheckers.common.LoggingAndStatistics;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MenuActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the user interface for the main menu.
this.setContentView(R.layout.main_menu);
// Link up all the UI elements with their listeners.
Button menuButton = (Button) this.findViewById(R.id.game_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.game_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.website_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.settings_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.about_us_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.license_button);
menuButton.setOnClickListener(this);
menuButton = (Button) this.findViewById(R.id.quit_button);
menuButton.setOnClickListener(this);
// TODO: Move logging info in a better place.
// LoggingAndStatistics.logApplicationInfo(this);
LoggingAndStatistics.logDeviceAndSystemInfo();
}
public void onClick(View view) {
// Determine which view fired off this event.
switch (view.getId()) {
case R.id.game_button:
this.startGame();
break;
case R.id.website_button:
this.launchWebsite();
break;
case R.id.settings_button:
this.displaySettings();
break;
case R.id.about_us_button:
this.displayInfo(GlobalConstants.FLAG_INFORMATION_DISPLAY_ABOUT_US);
break;
case R.id.license_button:
this.displayInfo(GlobalConstants.FLAG_INFORMATION_DISPLAY_LICENSE);
break;
case R.id.quit_button:
this.quitApp();
break;
};
}
/**
* Quits the application.
*/
private void quitApp() {
this.finish();
}
/**
* Displays an information screen.
*/
private void displayInfo(int infoToDisplay) {
// Validate info.
if ((infoToDisplay != GlobalConstants.FLAG_INFORMATION_DISPLAY_ABOUT_US) &&
(infoToDisplay != GlobalConstants.FLAG_INFORMATION_DISPLAY_LICENSE)) {
infoToDisplay = GlobalConstants.FLAG_INFORMATION_DISPLAY_ABOUT_US;
}
Intent launchDisplay = new Intent(this, InfoActivity.class);
launchDisplay.putExtra(GlobalConstants.EXTRA_INFORMATION_DISPLAY_FLAG,
infoToDisplay);
startActivity(launchDisplay);
}
/**
* Displays the settings for the application.
*/
private void displaySettings() {
Intent launchDisplay = new Intent(this, SettingsActivity.class);
startActivity(launchDisplay);
}
/**
* Starts an external browser to visit the project's website.
*/
private void launchWebsite() {
String url = this.getString(R.string.project_website);
Intent launcher = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(launcher);
}
/**
* Starts a new game or continues an existing one.
*/
private void startGame() {
Intent launchDisplay = new Intent(this, GameActivity.class);
startActivity(launchDisplay);
}
}

View File

@ -1,40 +0,0 @@
/*****************************************************************************
SettingsActivity.java - The activity for adjustings settings in the app.
*****************************************************************************
*****************************************************************************
This file is part of justCheckers.
justCheckers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
justCheckers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with justCheckers. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package org.justcheckers.android;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addPreferencesFromResource(R.layout.settings_screen);
this.getListView().setBackgroundResource(R.drawable.backdrop);
this.getListView().setCacheColorHint(Color.TRANSPARENT);
}
}

View File

@ -1,61 +0,0 @@
/*
Gradle Build for justCheckers - Core
---------------------------------------------
Author: Dorian Pula (dorian.pula@amber-penguin-software.ca)
License: AGPL v3.
Gradle docs:
http://www.gradle.org/docs/current/userguide/userguide_single.html
*/
apply plugin: 'java'
sourceCompatibility = 1.6
targetCompatibility = 1.6
// Description of the project
description = 'justcheckers-core'
version = '0.3'
project.ext {
appName = 'justcheckers-core'
}
// Setup build script repositories starting with Maven repositories
repositories {
maven {
url 'http://repo1.maven.org/maven2'
}
}
// Dependency management
dependencies {
compile 'jdom:jdom:0.7'
compile 'org.slf4j:slf4j-api:1.7.5'
testCompile 'org.testng:testng:6.8'
}
// At the end of day we just need a JAR and a WAR.
ext.sharedManifest = manifest {
attributes(
'App-Name' : project.appName,
'App-Version' : version,
'Build-User' : System.properties['user.name'],
'Build-Time' : new Date().format('yyyy-MMMM-dd HH:mm:ss'),
'Build-OS' : System.properties['os.name'] + ' - version ' + System.properties['os.version'],
'Build-Sys' : System.properties['os.arch'],
'Java-Version' : System.properties['java.version'],
'Java-Vendor' : System.properties['java.vendor'],
'Java-VM' :
System.properties['java.vm.vendor'] + ' ' + System.properties['java.vm.name'] + ' v'
+ System.properties['java.vm.version'])
}
// Build the JAR.
jar {
enabled = true
includeEmptyDirs = false
manifest = sharedManifest
}

View File

@ -1,41 +0,0 @@
/*****************************************************************************
GlobalConstants.java - Constants for the entire application.
*****************************************************************************
*****************************************************************************
This file is part of justCheckers.
justCheckers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
justCheckers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with justCheckers. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package org.justcheckers.common;
/**
* Organizational class to keep all the constants in.
* @author Dorian Pula
*
*/
public class GlobalConstants {
/** Flag for the information screen to display a "About Us". */
public final static int FLAG_INFORMATION_DISPLAY_ABOUT_US = 0;
/** Flag for the information screen to display the license of the app. */
public final static int FLAG_INFORMATION_DISPLAY_LICENSE = 1;
/**
* The extras key that contains the information screens needs to display
* the right information.
*/
public final static String EXTRA_INFORMATION_DISPLAY_FLAG = "info-display";
}

View File

@ -1,84 +0,0 @@
package org.justcheckers.xml;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Holds the justCheckers configuration settings.
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
final public class ConfigSettings extends Settings{
//---------------------------//
// Class Fields //
//---------------------------//
private static ConfigSettings cs = null;
//---------------------------//
// Class Methods //
//---------------------------//
//======= PUBLIC ============//
/**
* Accessor method for obtaining the one
* and only instance of this class
*/
public static ConfigSettings getInstance(){
if(cs==null) cs = new ConfigSettings(new DefaultConfigSettings());
return cs;
}
/**
* Load the default config settings.
*/
public static void loadDefault(){
cs = new ConfigSettings(new DefaultConfigSettings());
}
//======= PRIVATE CONSTRUCTORS ========//
private ConfigSettings(){
super();
}
private ConfigSettings(DefaultConfigSettings cus){
super(cus.getTextMap(),cus.getAttributeMap());
}
//======= PRIVATE INNER CLASS ============//
/* The default class from which to get settings */
private static class DefaultConfigSettings extends Settings.DefaultSettings{
private String userHome = System.getProperty("user.home");
private String userDir = System.getProperty("user.dir");
private String [][] text =
{
{"configsettings.directory.configFile",userDir+"/config.xml"},
{"configsettings.directory.settings",userHome+"/settings/"},
{"configsettings.directory.skins",userDir+"/skins/"},
{"configsettings.directory.sounds",userDir+"/sounds/"},
{"configsettings.directory.language",userDir+"/language/"},
};
private String [][] attribute =
{
{"configsettings.general.id","3"},
{"configsettings.general.id2","5"},
{"configsettings.language.default","english"},
{"configsettings.appearance.pretty","true"},
};
DefaultConfigSettings(){
super();
super.setFields(text,attribute);
}
}//end of default class
}

View File

@ -1,295 +0,0 @@
package org.justcheckers.xml;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Concrete child class of the XML_IO class. Use its load() and save() methods
* to write XML into/write out XML from, the associated ConfigSettings object.
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
public class ConfigSettingsIO extends XML_IO{
//---------------------------//
// Class Methods //
//---------------------------//
//---------------------------------------------------------------------
// -- Interface -------------------------------------------------------
//---------------------------------------------------------------------
/**
* Causes the XML data held within the File object referenced by the member
* variable "file" (inherited from XML_IO) to be loaded into the ConfigSettings
* object associated with this class. The reading in of XML data and subsequent
* transformation is dealt with by the inner reader class of this class.
*/
public void load(){
try{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(getFile());
Element rootElement = doc.getRootElement();
ConfigSettingsIOReader csior = new ConfigSettingsIOReader();
csior.visit(rootElement);
}
// catch(IOException e){
// String msg = "Problem : " + e.getMessage();
// Log.e("ConfigSettingsIO", msg);
// }
catch(JDOMException e){
String msg = "Problem : " + getFile().toString()
+ " is not a well formed XML document";
// TODO Clean up...
Logger log = LoggerFactory.getLogger(UserSettingsIO.class);
log.error("ConfigSettingsIO", msg);
}
}
/**
* Causes the data held within the ConfigSettings object associated with
* this class to be saved as XML format into the File object referenced by
* the member variable "file". Transformation of ConfigSettings data into XML
* format and subsequent writing to file is handled by the inner writer
* class of this class.
*/
public void save(){
try{
ConfigSettingsIOWriter csiow = new ConfigSettingsIOWriter();
Document doc = csiow.createXMLDocument();
XMLOutputter outputter = new XMLOutputter("",true);
PrintWriter pw = new PrintWriter(
new BufferedWriter(
new FileWriter(getFile())));
outputter.output(doc,pw);
}
catch(IOException e){
String msg = "Problem : couldn't output to the given file : "
+ getFile().toString();
// TODO Clean up...
Logger log = LoggerFactory.getLogger(ConfigSettingsIO.class);
log.error("ConfigSettingsIO", msg);
}
}
//---------------------------------------------------------------------
// -- Contructors -----------------------------------------------------
//---------------------------------------------------------------------
/**
* The constructor used to initiate the ConfigSettingsIO
* object with a given file object
* @param fileObject The file object with which
* to initiate this ConfigSettingsIO.
*/
public ConfigSettingsIO(File fileObject){
super(fileObject,ConfigSettings.getInstance());
}
public ConfigSettingsIO(File fileObject, ConfigSettings cs){
super(fileObject,cs);
}
public ConfigSettingsIO(URL urlObject){
super(urlObject, ConfigSettings.getInstance());
}
public ConfigSettingsIO(URL urlObject, ConfigSettings cs){
super(urlObject,cs);
}
///////////////////////////////////
// INNER CLASS : READER //
///////////////////////////////////
private class ConfigSettingsIOReader extends XML_IO.XMLFileReader{
/*
* Loads text information held in an Element object
* into the ConfigSettings object
*/
protected void loadElementIntoSettings(Element e){
String text = e.getTextTrim();
if(text!=null && text.length()!=0){
ConfigSettings.getInstance().setElementText(toFullSettingName(e),text);
}
}
/*
* Loads Attribute information held in an Element object
* into the ConfigSettings object
*/
protected void loadAttributesIntoSettings(Element e){
List attributes = e.getAttributes();
ConfigSettings cs = ConfigSettings.getInstance();
for(int k=0;k<attributes.size();k++){
Attribute current = (Attribute)attributes.get(k);
String total = toFullSettingName(e) + "" + current.getName();
cs.setElementAttribute(total,current.getValue());
}
}
/** Adds the correct number on the end of the settings key.
Thus a.b.c.d becomes a.b.c.d.x where x=1,2,3...Checks if the key
a.b.c.d.1 exists. If so, looks for a.b.c.d.2, etc. in the settings class,
and so on, until it has a new key. This method thus allows multi Elements
with the same name to be stored uniquely. Without this, for example,
game moves would all have the same key e.g. gamesettings.game.move
*/
protected String correctKeyForNumber(String uncorrectedKey){
int i = 1;
String correctedKey = uncorrectedKey + "" + i;
//is there a key with this name?
boolean reachedEnd = (ConfigSettings.getInstance().getElementText(correctedKey) == null);
while(!reachedEnd){
i++;
int lastDotIndex = correctedKey.lastIndexOf('.');
correctedKey = correctedKey.substring(0,lastDotIndex+1) + i;
reachedEnd = (ConfigSettings.getInstance().getElementText(correctedKey) == null);
}
return correctedKey;
}
} //end of inner class ConfigSettingsIOReader
///////////////////////////////////
// INNER CLASS : WRITER //
///////////////////////////////////
private class ConfigSettingsIOWriter extends XML_IO.XMLFileWriter{
/* Creates and returns the Document root Element */
public Element createRootElement(){
ConfigSettings cs = ConfigSettings.getInstance();
Iterator textEntries = cs.getTextEntries().iterator();
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
return new Element((String)settingKeyTokens.get(0));
}
/* Adds org.jdom.Comment objects to the current Document */
public void addComments(Document doc){
String text = "This file is important. Do not delete it,"
+ " do not displace it, do not rename it. Do any of these things"
+ " and as the universe is our witness we'll fry your ass, your"
+ " hard drive, sleep with your girlfriend (and she'll enjoy it,"
+ " believe us!), have you fired from your job, and transfer your"
+ " bank accounts to our names. Yes; this program is that good.";
doc.addContent(new Comment(text));
}
/* Create the JDOM tree from the ConfigSettings class */
public void addElements(Element rootElement){
ConfigSettings cs = ConfigSettings.getInstance();
Iterator textEntries = cs.getTextEntries().iterator();
//iterator returns Map.Entry objects
while(textEntries.hasNext()){
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element parent = rootElement;
Element child = null;
for(int k=1;k<settingKeyTokens.size();k++){
String childName = (String)settingKeyTokens.get(k);
child = getChildElement(parent,childName);
if(child==null){
child = new Element(childName);
parent.addContent(child);
if(isLastToken(k,settingKeyTokens.size())){
child.addContent(settingValue);
}
}
parent = child;
}
}
}
/* Adds org.jdom.Attribute objects to the DOM tree Elements */
public void addAttributes(Element root){
Iterator attributeEntries =
ConfigSettings.getInstance().getAttributeEntries().iterator();
while(attributeEntries.hasNext()){
Map.Entry me = (Map.Entry)attributeEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element e = getElement(settingKeyTokens,root);
e.setAttribute((String)settingKeyTokens.get(
settingKeyTokens.size()-1),settingValue);
}
}
//Checks whether the token from the StringTokenizer operation
private boolean isLastToken(int k, int listSize){
return (k==listSize-1);
}
//Navigates down the jdom tree until it reaches the element
//to which we wish to attach an attribute. Returns that element.
private Element getElement(ArrayList tokens, Element root){
Element e = root;
for(int k=1;k<tokens.size()-1;k++){
e = e.getChild((String)tokens.get(k));
}
return e;
}
/*
* Does this parent Element already have a child with this name attached?
* If so, return it, else return null
*/
private Element getChildElement(Element parent, String childName){
return parent.getChild(childName);
}
/* Splits a Setting key of the form a.b.c.d into it's
respective parts, delimited by the "." */
private ArrayList splitSettingKey(String key){
ArrayList l = new ArrayList();
StringTokenizer st = new StringTokenizer(key, "",false);
while(st.hasMoreTokens()){
l.add(st.nextToken());
}
return l;
}
}//end of inner class ConfigSettingsIOWriter
}//end of class ConfigSettingsIO

View File

@ -1,68 +0,0 @@
package org.justcheckers.xml;
import java.util.HashMap;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Holds the current game settings (Players, moves, etc).
* Currently, only one game may be open at a time.
* Future versions may allow more than one game to be open at
* a given moment.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
final public class GameSettings extends Settings{
//---------------------------//
// Class Fields //
//---------------------------//
private HashMap text = new HashMap(), attribute = new HashMap();
private static GameSettings gs = null;
//---------------------------//
// Class Methods //
//---------------------------//
//======= PUBLIC ============//
/**
* Accessor method for reaching the one and only instance of this class.
* @return Reference to the GameSettings object
*/
public static GameSettings getInstance(){
if(gs==null) gs = new GameSettings();
return gs;
}
/*
================ NOTE : ===============================================
=======================================================================
For GameSettings, we need in addition to the inherited Settings methods
methods that will be used to fill this object when a new game is started.
To be able to code these required methods (there will be more than the two
I give as example below) we need to agree on a format for games XML files.
public void addMove(CheckersMove cm){...}
public void addPlayer(Player p){...}
...
...
...
=========================================================================
*/
// -- Private Constructors -----------------------------------------------
private GameSettings(){
super();
}
}

View File

@ -1,297 +0,0 @@
package org.justcheckers.xml;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/* **************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Concrete child class of the @link(XML_IO) class. Represents an
* "intelligent" XML file that can read XML data into/write data from
* the @link(GameSettings) information associated with this class.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
public class GameSettingsIO extends XML_IO{
//---------------------------//
// Class Methods //
//---------------------------//
//---------------------------------------------------------------------
// -- Interface -------------------------------------------------------
//---------------------------------------------------------------------
/**
* Causes the XML data held within the File object referenced by the member
* variable "file" (inherited from XML_IO) to be loaded into the GameSettings
* object associated with this class. The reading in of XML data and subsequent
* transformation is dealt with by the inner reader class of this class.
*/
public void load(){
try{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(getFile());
Element rootElement = doc.getRootElement();
GameSettingsIOReader gsior = new GameSettingsIOReader();
gsior.visit(rootElement);
}
//catch(IOException e){
// String msg = "Problem : " + e.getMessage();
// Log.e("GameSettingsIO", msg);
//}
catch(JDOMException e){
String msg = "Problem : " + getFile().toString()
+ " is not a well formed XML document";
// TODO Clean up...
Logger log = LoggerFactory.getLogger(GameSettingsIO.class);
log.error("GameSettingsIO", msg);
}
}
/**
* Causes the data held within the GameSettings object associated with
* this class to be saved as XML format into the File object referenced by
* the member variable "file". Transformation of GameSettings data into XML
* format and subsequent writing to file is handled by the inner writer
* class of this class.
*/
public void save(){
try{
GameSettingsIOWriter gsiow = new GameSettingsIOWriter();
Document doc = gsiow.createXMLDocument();
XMLOutputter outputter = new XMLOutputter("",true);
PrintWriter pw = new PrintWriter(
new BufferedWriter(
new FileWriter(getFile())));
outputter.output(doc,pw);
}
catch(IOException e){
String msg = "Problem : couldn't output to the given file : "
+ getFile().toString();
// TODO Clean up...
Logger log = LoggerFactory.getLogger(GameSettingsIO.class);
log.error("GameSettingsIO", msg);
}
}
//---------------------------------------------------------------------
// -- Contructors -----------------------------------------------------
//---------------------------------------------------------------------
/**
* The constructor used to initiate the GameSettingsIO
* object with a given file object
* @param fileObject The file object with which
* to initiate this GameSettingsIO.
*/
public GameSettingsIO(File fileObject){
super(fileObject,GameSettings.getInstance());
}
public GameSettingsIO(File fileObject, GameSettings cs){
super(fileObject,cs);
}
public GameSettingsIO(URL urlObject){
super(urlObject, GameSettings.getInstance());
}
public GameSettingsIO(URL urlObject, GameSettings cs){
super(urlObject,cs);
}
///////////////////////////////////
// INNER CLASS : READER //
///////////////////////////////////
private class GameSettingsIOReader extends XML_IO.XMLFileReader{
/*
* Loads text information held in an Element object
* into the GameSettings object
*/
protected void loadElementIntoSettings(Element e){
String text = e.getTextTrim();
if(text!=null && text.length()!=0){
GameSettings.getInstance().setElementText(toFullSettingName(e),text);
}
}
/*
* Loads Attribute information held in an Element object
* into the GameSettings object
*/
protected void loadAttributesIntoSettings(Element e){
List attributes = e.getAttributes();
GameSettings gs = GameSettings.getInstance();
for(int k=0;k<attributes.size();k++){
Attribute current = (Attribute)attributes.get(k);
String total = toFullSettingName(e) + "" + current.getName();
gs.setElementAttribute(total,current.getValue());
}
}
/** Adds the correct number on the end of the settings key.
Thus a.b.c.d becomes a.b.c.d.x where x=1,2,3...Checks if the key
a.b.c.d.1 exists. If so, looks for a.b.c.d.2, etc. in the settings class,
and so on, until it has a new key. This method thus allows multi Elements
with the same name to be stored uniquely. Without this, for example,
game moves would all have the same key e.g. gamesettings.game.move
*/
protected String correctKeyForNumber(String uncorrectedKey){
int i = 1;
String correctedKey = uncorrectedKey + "" + i;
//is there a key with this name?
boolean reachedEnd = (GameSettings.getInstance().getElementText(correctedKey) == null);
while(!reachedEnd){
i++;
int lastDotIndex = correctedKey.lastIndexOf('.');
correctedKey = correctedKey.substring(0,lastDotIndex+1) + i;
reachedEnd = (GameSettings.getInstance().getElementText(correctedKey) == null);
}
return correctedKey;
}
} //end of inner class GameSettingsIOReader
///////////////////////////////////
// INNER CLASS : WRITER //
///////////////////////////////////
private class GameSettingsIOWriter extends XML_IO.XMLFileWriter{
/* Creates and returns the Document root Element */
public Element createRootElement(){
GameSettings gs = GameSettings.getInstance();
Iterator textEntries = gs.getTextEntries().iterator();
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
return new Element((String)settingKeyTokens.get(0));
}
/* Adds org.jdom.Comment objects to the current Document */
public void addComments(Document doc){
String text = "This file is important. Do not delete it,"
+ " do not displace it, do not rename it. Do any of these things"
+ " and as the universe is our witness we'll fry your ass, your"
+ " hard drive, sleep with your girlfriend (and she'll enjoy it,"
+ " believe us!), have you fired from your job, and transfer your"
+ " bank accounts to our names. Yes; this program is that good.";
doc.addContent(new Comment(text));
}
/* Create the JDOM tree from the GameSettings class */
public void addElements(Element rootElement){
GameSettings gs = GameSettings.getInstance();
Iterator textEntries = gs.getTextEntries().iterator();
//iterator returns Map.Entry objects
while(textEntries.hasNext()){
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element parent = rootElement;
Element child = null;
for(int k=1;k<settingKeyTokens.size();k++){
String childName = (String)settingKeyTokens.get(k);
child = getChildElement(parent,childName);
if(child==null){
child = new Element(childName);
parent.addContent(child);
if(isLastToken(k,settingKeyTokens.size())){
child.addContent(settingValue);
}
}
parent = child;
}
}
}
/* Adds org.jdom.Attribute objects to the DOM tree Elements */
public void addAttributes(Element root){
Iterator attributeEntries =
GameSettings.getInstance().getAttributeEntries().iterator();
while(attributeEntries.hasNext()){
Map.Entry me = (Map.Entry)attributeEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element e = getElement(settingKeyTokens,root);
e.setAttribute((String)settingKeyTokens.get(
settingKeyTokens.size()-1),settingValue);
}
}
//Checks whether the token from the StringTokenizer operation
private boolean isLastToken(int k, int listSize){
return (k==listSize-1);
}
//Navigates down the jdom tree until it reaches the element
//to which we wish to attach an attribute. Returns that element.
private Element getElement(ArrayList tokens, Element root){
Element e = root;
for(int k=1;k<tokens.size()-1;k++){
e = e.getChild((String)tokens.get(k));
}
return e;
}
/*
* Does this parent Element already have a child with this name attached?
* If so, return it, else return null
*/
private Element getChildElement(Element parent, String childName){
return parent.getChild(childName);
}
/* Splits a Setting key of the form a.b.c.d into it's
respective parts, delimited by the "." */
private ArrayList splitSettingKey(String key){
ArrayList l = new ArrayList();
StringTokenizer st = new StringTokenizer(key, "",false);
while(st.hasMoreTokens()){
l.add(st.nextToken());
}
return l;
}
}//end of inner class GameSettingsIOWriter
}//end of class GameSettingsIO

View File

@ -1,124 +0,0 @@
package org.justcheckers.xml;
import java.util.Set;
import java.util.HashMap;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Defines a common template for all classes that
* store some sort of Settings. Text, Attribute and Element
* are references to the XML objects as implemented
* by the JDOM API (http://www.jdom.org).
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
public abstract class Settings{
//---------------------------//
// Class Fields //
//---------------------------//
protected HashMap text = null, attribute = null;
//---------------------------//
// Class Methods //
//---------------------------//
//---------------------------------------------------------------------
// -- Interface -------------------------------------------------------
//---------------------------------------------------------------------
public static void loadDefault(){}
//get/set methods on the HashMaps
public String getElementText(String key){
if(!text.containsKey(key)) return null;
return (String)text.get(key);
}
public void setElementText(String key, String value){
text.put(key,value);
}
public String getElementAttribute(String key){
if(!attribute.containsKey(key)) return null;
return (String)attribute.get(key);
}
public void setElementAttribute(String key, String value){
attribute.put(key,value);
}
public String getSetting(String key){
if(text.containsKey(key)) return getElementText(key);
else if(attribute.containsKey(key)) return getElementAttribute(key);
return null;
}
public Set getTextEntries(){return text.entrySet();}
public Set getAttributeEntries(){return attribute.entrySet();}
//---------------------------------------------------------------------
// -- Constructors ----------------------------------------------------
//---------------------------------------------------------------------
protected Settings(){
text = new HashMap();
attribute = new HashMap();
}
/**
* Initiate the two class HashMap member objects with the parameters
* @param t The HashMap with which to initiate the "text" member
* @param a The HashMap with which to initiate the "attribute" member
*/
protected Settings(HashMap t, HashMap a){
text = t;
attribute = a;
}
////////////////////////////////////
// INNER CLASS : Default Settings //
////////////////////////////////////
/**
* The outer Settings object employs this nested one to obtain default values
* for its member HashMap objects "text" and "attribute".
*/
protected abstract static class DefaultSettings{
//------ Class Fields -----------
protected String [][] text = {};
protected String [][] attribute = {};
//------ Class Methods ----------
protected void setFields(String [][] text, String [][] attribute){
this.text = text;
this.attribute = attribute;
}
public HashMap getTextMap(){
HashMap hm = new HashMap(text.length);
for(int k=0;k<text.length;k++){
hm.put(text[k][0],text[k][1]);
}
return hm;
}
public HashMap getAttributeMap(){
HashMap hm = new HashMap(attribute.length);
for(int k=0;k<attribute.length;k++){
hm.put(attribute[k][0],attribute[k][1]);
}
return hm;
}
}
}

View File

@ -1,92 +0,0 @@
package org.justcheckers.xml;
import java.util.HashMap;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Stores the user preferences in the application memory.
* Implements the singleton pattern.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
final public class UserSettings extends Settings{
//---------------------------//
// Class Fields //
//---------------------------//
private static UserSettings us = null;
private HashMap text = null, attribute = null;
//---------------------------//
// Class Methods //
//---------------------------//
// -- Interface ---------------------------------------------------------
/**
* Accessor method for obtaining the one and only instance of this class
*/
public static UserSettings getInstance(){
if(us==null) loadDefault();
return us;
}
/**
* Load the default user settings.
*/
public static void loadDefault(){
us = new UserSettings(new DefaultUserSettings());
//somehow would have to log that properties have changed
//so that things can be updated e.g. the UI, or whatever
}
// -- Private Constructors -----------------------------------------------
private UserSettings(){
super();
}
private UserSettings(DefaultUserSettings dus){
super(dus.getTextMap(), dus.getAttributeMap());
}
//////////////////////////////////////
// INNER CLASS : DefaultSettings //
//////////////////////////////////////
private static class DefaultUserSettings extends Settings.DefaultSettings{
private String [][] text =
{
{"usersettings.general.splashOnLaunch","true"},
{"usersettings.general.maxActiveGames","3"},
{"usersettings.audio.activateBkgdOnLaunch","false"},
{"usersettings.audio.defaultBkgdSong","song1.wav"},
{"usersettings.audio.appSoundsActive","true"},
{"usersettings.language.current","english"},
{"usersettings.appearance.fullScreenOnLaunch","true"},
{"usersettings.appearance.activePieceSet","pieceset1"},
};
private String [][] attribute =
{
{"usersettings.general.id","3"},
{"usersettings.general.id2","5"},
{"usersettings.language.default","english"},
{"usersettings.appearance.pretty","true"},
};
DefaultUserSettings(){
super();
super.setFields(text,attribute);
}
}
}

View File

@ -1,302 +0,0 @@
package org.justcheckers.xml;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/* **************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Concrete child class of the @link(XML_IO) class. Represents an
* "intelligent" XML file that can read XML data into/write data from
* the @link(UserSettings) information associated with this class.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
public class UserSettingsIO extends XML_IO {
//---------------------------//
// Class Methods //
//---------------------------//
//---------------------------------------------------------------------
// -- Interface -------------------------------------------------------
//---------------------------------------------------------------------
/**
* Causes the XML data held within the File object referenced by the member
* variable "file" (inherited from XML_IO) to be loaded into the UserSettings
* object associated with this class. The reading in of XML data and subsequent
* transformation is dealt with by the inner reader class of this class.
*/
public void load(){
try{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(getFile());
Element rootElement = doc.getRootElement();
UserSettingsIOReader usior = new UserSettingsIOReader();
usior.visit(rootElement);
}
// catch(IOException e){
// String msg = "Problem : " + e.getMessage();
// Log.e("UserSettingsIO", msg);
// }
catch(JDOMException e){
String msg = "Problem : " + getFile().toString()
+ " is not a well formed XML document";
// TODO Clean up...
Logger log = LoggerFactory.getLogger(UserSettingsIO.class);
log.error("UserSettingsIO", msg);
}
}
/**
* Causes the data held within the UserSettings object associated with
* this class to be saved as XML format into the File object referenced by
* the member variable "file". Transformation of UserSettings data into XML
* format and subsequent writing to file is handled by the inner writer
* class of this class.
*/
public void save(){
try{
UserSettingsIOWriter usiow = new UserSettingsIOWriter();
Document doc = usiow.createXMLDocument();
XMLOutputter outputter = new XMLOutputter("",true);
PrintWriter pw = new PrintWriter(
new BufferedWriter(
new FileWriter(getFile())));
outputter.output(doc,pw);
}
catch(IOException e){
String msg = "Problem : couldn't output to the given file : "
+ getFile().toString();
// TODO Clean up...
Logger log = LoggerFactory.getLogger(UserSettingsIO.class);
log.error("UserSettingsIO", msg);
}
}
//---------------------------------------------------------------------
// -- Contructors -----------------------------------------------------
//---------------------------------------------------------------------
/**
* The constructor used to initiate the UserSettingsIO
* object with a given file object
* @param fileObject The file object with which
* to initiate this UserSettingsIO.
*/
public UserSettingsIO(File fileObject){
super(fileObject,UserSettings.getInstance());
}
public UserSettingsIO(File fileObject, UserSettings us){
super(fileObject,us);
}
public UserSettingsIO(URL urlObject){
super(urlObject,UserSettings.getInstance());
}
public UserSettingsIO(URL urlObject, UserSettings us){
super(urlObject,us);
}
///////////////////////////////////
// INNER CLASS : READER //
///////////////////////////////////
private class UserSettingsIOReader extends XML_IO.XMLFileReader{
/*
* Loads text information held in an Element object
* into the UserSettings object
*/
protected void loadElementIntoSettings(Element e){
String text = e.getTextTrim();
if(text!=null && text.length()!=0){
String fullName = toFullSettingName(e);
UserSettings.getInstance().setElementText(fullName,text);
System.out.println("element: " + fullName + " = " + text);
}
}
/*
* Loads Attribute information held in an Element object
* into the UserSettings object
*/
protected void loadAttributesIntoSettings(Element e){
List attributes = e.getAttributes();
UserSettings us = UserSettings.getInstance();
for(int k=0;k<attributes.size();k++){
Attribute current = (Attribute)attributes.get(k);
String total = toFullSettingName(e) + "" + current.getName();
us.setElementAttribute(total,current.getValue());
System.out.println("attribute: " + total + " = " + current.getValue());
}
}
/** Adds the correct number on the end of the settings key.
Thus a.b.c.d becomes a.b.c.d.x where x=1,2,3...Checks if the key
a.b.c.d.1 exists. If so, looks for a.b.c.d.2, etc. in the settings class,
and so on, until it has a new key. This method thus allows multi Elements
with the same name to be stored uniquely. Without this, for example,
game moves would all have the same key e.g. gamesettings.game.move
*/
protected String correctKeyForNumber(String uncorrectedKey){
int i = 1;
String correctedKey = uncorrectedKey + "" + i;
//is there a key with this name?
boolean reachedEnd = (UserSettings.getInstance().getElementText(correctedKey) == null);
while(!reachedEnd){
i++;
int lastDotIndex = correctedKey.lastIndexOf('.');
correctedKey = correctedKey.substring(0,lastDotIndex+1) + i;
reachedEnd = (UserSettings.getInstance().getElementText(correctedKey) == null);
}
return correctedKey;
}
} //end of inner class UserSettingsIOReader
///////////////////////////////////
// INNER CLASS : WRITER //
///////////////////////////////////
private class UserSettingsIOWriter extends XML_IO.XMLFileWriter{
/* Creates and returns the Document root Element */
public Element createRootElement(){
UserSettings us = UserSettings.getInstance();
Iterator textEntries = us.getTextEntries().iterator();
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
return new Element((String)settingKeyTokens.get(0));
}
/* Adds org.jdom.Comment objects to the current Document */
public void addComments(Document doc){
String text = "This file is important. Do not delete it,"
+ " do not displace it, do not rename it. Do any of these things"
+ " and as the universe is our witness we'll fry your ass, your"
+ " hard drive, sleep with your girlfriend (and she'll enjoy it,"
+ " believe us!), have you fired from your job, and transfer your"
+ " bank accounts to our names. Yes; this program is that good.";
doc.addContent(new Comment(text));
}
/* Create the JDOM tree from the UserSettings class */
public void addElements(Element rootElement){
UserSettings us = UserSettings.getInstance();
Iterator textEntries = us.getTextEntries().iterator();
//iterator returns Map.Entry objects
while(textEntries.hasNext()){
Map.Entry me = (Map.Entry)textEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element parent = rootElement;
Element child = null;
for(int k=1;k<settingKeyTokens.size();k++){
String childName = (String)settingKeyTokens.get(k);
child = getChildElement(parent,childName);
if(child==null){
child = new Element(childName);
parent.addContent(child);
if(isLastToken(k,settingKeyTokens.size())){
child.addContent(settingValue);
}
}
parent = child;
}
}
}
/* Adds org.jdom.Attribute objects to the DOM tree Elements */
public void addAttributes(Element root){
Iterator attributeEntries =
UserSettings.getInstance().getAttributeEntries().iterator();
while(attributeEntries.hasNext()){
Map.Entry me = (Map.Entry)attributeEntries.next();
String settingKey = (String)me.getKey();
String settingValue = (String)me.getValue();
ArrayList settingKeyTokens = splitSettingKey(settingKey);
Element e = getElement(settingKeyTokens,root);
e.setAttribute((String)settingKeyTokens.get(
settingKeyTokens.size()-1),settingValue);
}
}
//Checks whether the token from the StringTokenizer operation
private boolean isLastToken(int k, int listSize){
return (k==listSize-1);
}
//Navigates down the jdom tree until it reaches the element
//to which we wish to attach an attribute. Returns that element.
private Element getElement(ArrayList tokens, Element root){
Element e = root;
for(int k=1;k<tokens.size()-1;k++){
e = e.getChild((String)tokens.get(k));
}
return e;
}
/*
* Does this parent Element already have a child with this name attached?
* If so, return it, else return null
*/
private Element getChildElement(Element parent, String childName){
return parent.getChild(childName);
}
/* Splits a Setting key of the form a.b.c.d into it's
respective parts, delimited by the "." */
private ArrayList splitSettingKey(String key){
ArrayList l = new ArrayList();
StringTokenizer st = new StringTokenizer(key, "",false);
while(st.hasMoreTokens()){
l.add(st.nextToken());
}
return l;
}
}//end of inner class UserSettingsIOWriter
}//end of class UserSettingsIO

View File

@ -1,102 +0,0 @@
//********************************************************************
// VisitDOM.java -- Abstract class for traversing XML documents.
// ********************************************************************
// ********************************************************************
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// ********************************************************************
package org.justcheckers.xml;
import java.util.Iterator;
import org.jdom.Element;
import org.jdom.Text;
/**
* An abstract class that provides a framework to do any processing of a
* DOM tree created with the JDOM package ( http://www.jdom.org ). It
* provides a recursive traverse with data processing methods that run
* before traversal, after traversal and at each Element object and Text
* object encountered. The default methods are do-nothing place-holders.
* These methods can be over-ridden in a child class that extends this one,
* doing what ever data processing needs to be done. Other methods and
* fields can also be added to child classes as needed.
*
* @author Dan D'Alimonte
*/
public abstract class VisitDOM {
// -- Interface ---------------------------------------------------------
/**
* Actions to preform before the traversal of the DOM tree begins.
* @param e The root Element of the tree.
*/
protected void preRoot(Element e) {}
/**
* Actions to preform after the traversal has been completed.
* @param e The root Element of the tree.
*/
protected void postRoot(Element e) {}
/**
* Actions to preform when an Element object is encountered in the DOM tree.
* @param e The Element object to process.
*/
protected void elementHandler(Element e) {}
/**
* Actions to preform when a Text object is encountered in the DOM tree.
* @param t The Text object to process.
*/
protected void textHandler(Text t) {}
// -- Contructors -------------------------------------------------------
/**
* Construct a new VisitDOM instance.
*/
public VisitDOM() {}
// -- Public methods ----------------------------------------------------
/**
* Preform the taversal on the DOM tree, visiting each node and
* processing them in turn.
* @param root The root Element of the tree to preform the traversal on.
*/
public void visit(Element root) {
preRoot(root);
elementHandler(root);
recurse(root);
postRoot(root);
}
// -- Protected Methods -------------------------------------------------
/**
* Traverses to children of Elements, calling appropriate data processing
* methods on the child objects, recursing deeper if needed.
* @param e The element whose children are to be processed.
*/
protected void recurse(Element e) {
Iterator iElement = e.getChildren().iterator();
while (iElement.hasNext()) {
Object next = iElement.next();
if (next instanceof Element) {
elementHandler((Element)next);
recurse((Element)next);
}
else if ( next instanceof Text ) {
textHandler((Text)next);
}
}
}
}

View File

@ -1,25 +0,0 @@
package org.justcheckers.xml;
import java.io.File;
import java.io.FileFilter;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* XMLFileFilter returns only File objects that represent XML files.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*
*/
public class XMLFileFilter implements FileFilter{
public boolean accept(File f){
return f.toString().endsWith(".xml");
}
}

View File

@ -1,267 +0,0 @@
package org.justcheckers.xml;
import java.io.File;
import java.net.URL;
import java.util.Iterator;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Text;
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/**
* Abstract version of an "intelligent" XML file. Objects of this class know
* how to read/write the @see(Settings) information they are associated with,
* into justCheckers memory/out to disk. The user creates a child object of
* this class giving the name and location of the File object to be represented
* by this class.
*
* NOTE :
* For the time being, data may only be outputted to XML files stored locally.
*
* @author Brinick Simmons (brinick@users.sourceforge.net)
*/
public abstract class XML_IO{
//---------------------------//
// Class Fields //
//---------------------------//
//protected URL url;
protected File file;
protected Settings settings;
//---------------------------//
// Class Methods //
//---------------------------//
//---------------------------------------------------------------------
// -- Interface -------------------------------------------------------
//---------------------------------------------------------------------
/**
* Causes the XML data held within the File object referenced by the class
* member variable "file" to be loaded into the Settings object associated
* with this class. The reading in of XML data and subsequent transformation
* is dealt with by the inner reader class of this class.
*/
public abstract void load();
/**
* Causes the data held within the Settings object associated with this class
* to be saved as XML format into the File object referenced by the class
* member variable "file". Transformation of Settings data to XML format and
* subsequent writing to File is handled by the inner writer class of this
* class.
*/
public abstract void save();
/** Sets the member variable File object to the parameter object passed in.
* @param f The File object with which to set the class member variable "file"
*/
protected void setFile(File f){file = f;}
/** Gets the member variable File object.
* @return The File object held in the class member variable "file".
*/
protected File getFile(){return file;}
/* Place holder for a later version */
// protected void setFile(URL u){}
// protected URL getFile(){}
/** Sets the member variable Settings object to the parameter object passed in.
* @param s The Settings object with which to set the class member variable "settings"
*/
protected void setSettings(Settings s){settings = s;}
/** Gets the member variable Settings object.
* @return The Settings object held in the class member variable "settings".
*/
protected Settings getSettings(){return settings;}
//---------------------------------------------------------------------
// -- Constructors ----------------------------------------------------
//---------------------------------------------------------------------
protected XML_IO(){}
protected XML_IO(File f, Settings s){file = f; settings=s;}
protected XML_IO(URL u, Settings s){}
///////////////////////////////////
// INNER CLASS : READER //
///////////////////////////////////
/**
* An abstract class that provides a framework to do any processing of a
* DOM tree created with the JDOM package ( http://www.jdom.org ). It
* provides a recursive traverse with data processing methods that run
* before traversal, after traversal and at each Element object and Text
* object encountered. The default methods are do-nothing place-holders.
* These methods can be over-ridden in a child class that extends this one,
* doing what ever data processing needs to be done. Other methods and
* fields can also be added to child classes as needed.
*
* @author Dan D'Alimonte (skwirl@users.sourceforge.net)
*/
protected abstract class XMLFileReader{
// -- Interface ---------------------------------------------------------
/**
* Actions to preform before the traversal of the DOM tree begins.
* @param e The root Element of the tree.
*/
protected void preRoot( Element e ) {}
/**
* Actions to preform after the traversal has been completed.
* @param e The root Element of the tree.
*/
protected void postRoot( Element e ) {}
/**
* Actions to preform when an Element object is encountered in the DOM tree.
* @param e The Element object to process.
*/
protected void elementHandler( Element e ) {
loadElementIntoSettings(e);
loadAttributesIntoSettings(e);
}
protected abstract void loadElementIntoSettings(Element e);
protected abstract void loadAttributesIntoSettings(Element e);
/**
* Actions to preform when a Text object is encountered in the DOM tree.
* @param t The Text object to process.
*/
protected void textHandler( Text t ) {}
// -- Constructors -------------------------------------------------------
/**
* Construct a new VisitDOM instance.
*/
public XMLFileReader() {}
// -- Public methods ----------------------------------------------------
/**
* Preform the traversal on the DOM tree, visiting each node and
* processing them in turn.
* @param root The root Element of the tree to preform the traversal on.
*/
public void visit( Element root ) {
preRoot( root );
elementHandler( root );
recurse( root );
postRoot( root );
}
// -- Protected Methods -------------------------------------------------
/**
* Traverses to children of Elements, calling appropriate data processing
* methods on the child objects, recursing deeper if needed.
* @param e The element whose children are to be processed.
*/
protected void recurse( Element e ) {
Iterator iElement = e.getChildren().iterator();
while ( iElement.hasNext() ) {
Object next = iElement.next();
if ( next instanceof Element ) {
elementHandler( (Element)next );
recurse( (Element)next );
}
else if ( next instanceof Text ) {
textHandler( (Text)next );
}
}
}
/*
* Returns the full path name in the form a.b.c.d
* of an Element object d
*/
protected String toFullSettingName(Element e){
String path = e.getName();
Element currentElement = e;
while(!currentElement.isRootElement()){
currentElement = currentElement.getParent();
path = currentElement.getName() + "" + path;
}
return correctKeyForNumber(path);
}
protected abstract String correctKeyForNumber(String path);
}
///////////////////////////////////
// INNER CLASS : WRITER //
///////////////////////////////////
/**
* Abstract framework for creating a DOM tree
* (using the JDOM API http://www.jdom.org) from an
* in-application memory "Settings" class.
* The default methods are do-nothing place-holders
* that should be over-ridden by a child class.
* @author Brinick Simmons
* @see UserSettings
* @see GameSettings
*/
protected abstract class XMLFileWriter{
/**
* Creates and returns a JDOM Document object
* @return org.jdom.Document object storing Settings information
*/
protected Document createXMLDocument(){
Element root = createRootElement();
Document doc = new Document(root);
addComments(doc);
addElements(root);
addAttributes(root);
return doc;
}
/**
* Creates the root org.jdom.Element for the Document in memory
* @return The newly created root Element
*/
abstract protected Element createRootElement();
/**
* Adds org.jdom.Comment objects to the Document
* @param d The Document to which Comments will be added
*/
protected void addComments(Document d){}
/**
* Builds the tree structure of org.jdom.Element objects in the Document.
* @param root The tree root Element to which all other
* Elements are (in)directly attached.
*/
protected void addElements(Element root){}
/**
* Adds any org.jdom.Attribute objects to the appropriate Element objects.
* @param root The tree root Element.
*/
protected void addAttributes(Element root){}
}
}

View File

View File