Android Open Source - ProjectSierra Base Factory






From Project

Back to project page ProjectSierra.

License

The source code is released under:

GNU General Public License

If you think the Android project ProjectSierra listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
Copyright 2014 Seth Traverse/*from  ww  w.  j  a v a2s.  com*/

This file is part of Project Sierra.

Project Sierra 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.

Project Sierra 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 Project Sierra.  If not, see <http://www.gnu.org/licenses/>.
 */
package ca.viaware.api.sql.factory;

import java.util.ArrayList;

import ca.viaware.api.logging.Log;
import ca.viaware.api.sql.Database;
import ca.viaware.api.sql.DatabaseResults;
import ca.viaware.api.sql.DatabaseRow;
import ca.viaware.api.sql.exceptions.ViaWareSQLException;
import ca.viaware.api.sql.factory.obj.DatabaseObject;

public abstract class BaseFactory<T extends DatabaseObject> {

  private ArrayList<T> objectCache;
  private String table;
  private Database database;
  
  /**
   * Construct a base factory. Takes an initialized database and a table name.<p>
   * @param database Initialized database
   * @param table Table name
   */
  public BaseFactory(Database database, String table) {
    objectCache = new ArrayList<T>();
    this.table = table;
    this.database = database;
  }
  
  /**
   * Initialize the factory. Basically just creates the table if it doesn't exist.
   */
  public void init() {
    Log.info("Initializing factory on table \"" + getTable() + "\"");
    generateTable();
  }
  
  public ArrayList<T> getCache() {
    return objectCache;
  }
  
  public Database getDatabase() {
    return database;
  }
  
  public String getTable() {
    return table;
  }
  
  /**
   * The recommended method for adding objects to the database.<p>
   * Automatically inserts and gets the generated primary key, returning
     * the object for convenience.
   * @param object
   */
  public T insertAndAdd(T object) {
    insert(object);
    int newId = getDatabase().getLastInsertedID();
    object.setId(newId);
    add(object);
        return object;
  }
  
  /**
   * Add an object to the cache, does not call the insert function. <p>
   * This function should only be used by subclasses to implement their own
   * caching systems. This function does do a little bit of checking to try and
     * prevent uninitialized objects from going into the cache. Just don't do it.
   * keys.
   * @param object
   */
  protected void add(T object){
    if (object.getId() == -1) {
      Log.error("Cannot add object into cache that is not initialized with a unique ID");
      return;
    }
    objectCache.add(object);
  }
  
  /**
   * Get database object using unique primary key of column name 'id'<p>
   * Tries the cache first, then goes on to try the database if it isn't in the cache
   * @param id Unique primary key
   * @return
   */
  public T get(int id) {
    for (T object : objectCache) {
      if (object.getId() == id) {
        return object;
      }
    }
    //Not in cache, use database.
    try {
      DatabaseResults result = getDatabase().query("SELECT * FROM " + getTable() + " WHERE id=?", id);
      if (result.getRowCount() > 0) {
        T object = loadFromQuery(result.getRow(0));
        add(object);
        return object;
      }
    } catch (ViaWareSQLException e) {
      e.printStackTrace();
    }
    return null;
  }
  
  public ArrayList<T> getAll() {
    try {
      DatabaseResults result = getDatabase().query("SELECT * FROM " + getTable());
      objectCache.clear();
      for (int i = 0; i < result.getRowCount(); i++) {
        T object = loadFromQuery(result.getRow(i));
        add(object);
      }
    } catch (ViaWareSQLException e) {
      e.printStackTrace();
    }
    return objectCache;
  }
  
  /**
   * Deletes all objects in the cache and in the database.<br>
   * Use with caution, no going back after this!
   */
  public void deleteAll() {
    Log.info("Deleting all objects managed by factory in table \"" + getTable() + "\"...");
    objectCache.clear();
    try {
      getDatabase().query("DELETE FROM " + getTable());
    } catch (ViaWareSQLException e) {
      e.printStackTrace();
    }
  }
  
  /**
   * Forces an update on all cached objects.
   */
  public void saveAll() {
    Log.info("Forcing update on all cached objects...");
    for (T object : objectCache) {
      update(object);
    }
  }
  
  /**
   * Prints the table using the DatabaseResults toString function<p>
   * Warning: This is inefficient as it reads all data from the table
   * without using the cache. This should only be used for debug purposes.
   */
  public void printTable() {
    try {
      DatabaseResults results = getDatabase().query("SELECT * FROM " + getTable());
      System.out.println(results);
    } catch (ViaWareSQLException e) {
      e.printStackTrace();
    }
  }
  
  /**
   * Generate the table if it does not exist
   */
  protected abstract void generateTable();
  
  /**
   * Load a database object from query.
   * @param row
   * @return
   */
  public abstract T loadFromQuery(DatabaseRow row);
  
  public abstract void update(T object);
  public abstract void insert(T object);
  
  public void remove(T object) {
    try {
      getDatabase().query("DELETE FROM " + getTable() + " WHERE id=?", object.getId());
      objectCache.remove(object);
    } catch (ViaWareSQLException e) {
      e.printStackTrace();
    }
  }
  
}




Java Source Code List

ca.viaware.api.audio.AudioUtils.java
ca.viaware.api.gui.base.VButton.java
ca.viaware.api.gui.base.VFrame.java
ca.viaware.api.gui.base.VLabel.java
ca.viaware.api.gui.base.VListElement.java
ca.viaware.api.gui.base.VList.java
ca.viaware.api.gui.base.VMenuBar.java
ca.viaware.api.gui.base.VMenuItem.java
ca.viaware.api.gui.base.VMenu.java
ca.viaware.api.gui.base.VPanel.java
ca.viaware.api.gui.base.VPopupMenu.java
ca.viaware.api.gui.base.VScrollPane.java
ca.viaware.api.gui.base.VScrollingList.java
ca.viaware.api.gui.base.VTextBox.java
ca.viaware.api.gui.base.event.CloseListener.java
ca.viaware.api.logging.Log.java
ca.viaware.api.net.ConnectionHandlerRunnerThread.java
ca.viaware.api.net.ConnectionHandler.java
ca.viaware.api.net.ConnectionListenerThread.java
ca.viaware.api.parse.CommandParser.java
ca.viaware.api.sql.DatabaseFactory.java
ca.viaware.api.sql.DatabaseResults.java
ca.viaware.api.sql.DatabaseRow.java
ca.viaware.api.sql.Database.java
ca.viaware.api.sql.exceptions.ViaWareSQLException.java
ca.viaware.api.sql.factory.BaseFactory.java
ca.viaware.api.sql.factory.obj.DatabaseObject.java
ca.viaware.api.utils.StringUtils.java
ca.viaware.game.Globals.java
ca.viaware.game.ProjectSierra.java
ca.viaware.game.android.AndroidLauncher.java
ca.viaware.game.assets.TilesetLoader.java
ca.viaware.game.assets.TilesetManager.java
ca.viaware.game.assets.Tileset.java
ca.viaware.game.desktop.DesktopLauncher.java
ca.viaware.game.entities.MapObject.java
ca.viaware.game.entity.Entity.java
ca.viaware.game.entity.MovingEntity.java
ca.viaware.game.entity.events.MoveEvent.java
ca.viaware.game.rendering.Renderable.java
ca.viaware.game.screens.GameScreen.java
ca.viaware.game.world.Map.java
ca.viaware.mapmaker.ConstructionKit.java
ca.viaware.mapmaker.gui.components.SidebarButton.java
ca.viaware.mapmaker.gui.windows.assets.editor.EditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.animation.AnimationEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.clothing.ClothingEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.consumable.ConsumableEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.dialog.DialogEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.effect.EffectEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.intelligence.IntelligenceEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.living.LivingEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.quest.QuestEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.sound.SoundEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.weapon.WeaponEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.editor.worldstatic.StaticEditorWindow.java
ca.viaware.mapmaker.gui.windows.assets.explorer.AssetExplorerWindow.java
ca.viaware.mapmaker.gui.windows.control.ControlWindow.java
ca.viaware.mapmaker.gui.windows.world.editor.DesignPanel.java
ca.viaware.mapmaker.gui.windows.world.editor.SidebarListener.java
ca.viaware.mapmaker.gui.windows.world.editor.SidebarPanel.java
ca.viaware.mapmaker.gui.windows.world.editor.WorldEditorWindow.java
ca.viaware.mapmaker.gui.windows.world.explorer.TopBar.java
ca.viaware.mapmaker.gui.windows.world.explorer.WorldExplorerWindow.java
ca.viaware.mapmaker.gui.windows.world.explorer.WorldListElement.java
ca.viaware.mapmaker.obj.GameManager.java
ca.viaware.mapmaker.obj.asset.AssetManager.java
ca.viaware.mapmaker.obj.asset.AssetType.java
ca.viaware.mapmaker.obj.asset.GameAsset.java
ca.viaware.mapmaker.obj.asset.render.AnimationAsset.java
ca.viaware.mapmaker.obj.asset.render.TextureAsset.java
ca.viaware.mapmaker.obj.asset.sys.DialogAsset.java
ca.viaware.mapmaker.obj.asset.sys.EffectAsset.java
ca.viaware.mapmaker.obj.asset.sys.IntelligenceAsset.java
ca.viaware.mapmaker.obj.asset.sys.QuestAsset.java
ca.viaware.mapmaker.obj.asset.sys.SoundAsset.java
ca.viaware.mapmaker.obj.asset.world.ClothingAsset.java
ca.viaware.mapmaker.obj.asset.world.ConsumableAsset.java
ca.viaware.mapmaker.obj.asset.world.LivingAsset.java
ca.viaware.mapmaker.obj.asset.world.StaticAsset.java
ca.viaware.mapmaker.obj.asset.world.WeaponAsset.java
ca.viaware.mapmaker.obj.world.MapObject.java
ca.viaware.mapmaker.obj.world.WorldManager.java
ca.viaware.mapmaker.obj.world.World.java
ca.viaware.tileset.Globals.java
ca.viaware.tileset.Region.java
ca.viaware.tileset.TilesetCreator.java
ca.viaware.tileset.gui.BasicButton.java
ca.viaware.tileset.gui.LabelAndTextPanel.java
ca.viaware.tileset.gui.RawImagePanel.java
ca.viaware.tileset.gui.RawImageWindow.java
ca.viaware.tileset.gui.SidebarPanel.java
ca.viaware.tileset.gui.listeners.SidebarListener.java
ca.viaware.tileset.utils.FileUtils.java
ca.viaware.tileset.utils.Utils.java