code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.clockworkmages.games.anno1186.scripting; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.gui.GameUiUtil; public class ScriptingService { private ScriptEngine jsEngine; @Injected private PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper; @Injected private EnemyScriptingWrapper enemyScriptingWrapper; @Injected private PlotScriptingWrapper plotScriptingWrapper; @Injected private SituationScriptingWrapper situationScriptingWrapper; @Injected private UtilScriptingWrapper utilScriptingWrapper; public ScriptingService() { ScriptEngineManager sem = new ScriptEngineManager(); jsEngine = sem.getEngineByName("JavaScript"); } public boolean conditionIsMet(String condition) { Map<String, Object> model = getDefaultModel(); return conditionIsMet(condition, model); } public void execute(String script) { Map<String, Object> model = getDefaultModel(); execute(script, model); } public Object eval(String condition) { Map<String, Object> model = getDefaultModel(); return eval(condition, model); } public Map<String, Object> getDefaultModel() { return getDefaultModel(false); } /** * @param forEnemy * <b>true</b> is the chaacter that we're executing the Effect or * checking the Condition for is an enemy. If so, we need to * reverse the assignement of model values for "me" and "enemy" * attributes. * @return */ public Map<String, Object> getDefaultModel(boolean forEnemy) { Map<String, Object> model = new HashMap<String, Object>(); model.put("me", forEnemy ? enemyScriptingWrapper : playerCharacterScriptingWrapper); model.put("enemy", forEnemy ? playerCharacterScriptingWrapper : enemyScriptingWrapper); model.put("plot", plotScriptingWrapper); model.put("situation", situationScriptingWrapper); model.put("util", utilScriptingWrapper); model.put("input", GameBeansContext.getBean(GameGuiService.class) .getOptionTextInput().getText()); return model; } public void execute(String expression, Map<String, Object> model) { eval(expression, model); } public boolean conditionIsMet(String expression, Map<String, Object> model) { if (expression == null || expression.isEmpty()) { return true; } return (Boolean) eval(expression, model); } public Object eval(String expression, Map<String, Object> model) { for (Entry<String, Object> entry : model.entrySet()) { jsEngine.put(entry.getKey(), entry.getValue()); } try { return jsEngine.eval(expression); } catch (Exception e) { GameUiUtil.logError("Invalid expression: " + expression, e); return false; } } }
Java
package org.clockworkmages.games.anno1186.scripting; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; public class PlotScriptingWrapper { @Injected private GameStateService gameStateService; public String get(String plotId) { String plotValue = gameStateService.getGameState().getPlot() .get(plotId); return plotValue; } public boolean is(String plotId) { String plotValue = gameStateService.getGameState().getPlot() .get(plotId); return Boolean.TRUE.toString().equals(plotValue); } public void set(String plotId) { gameStateService.getGameState().getPlot() .put(plotId, Boolean.TRUE.toString()); } public void set(String plotId, String plotValue) { gameStateService.getGameState().getPlot().put(plotId, plotValue); } }
Java
package org.clockworkmages.games.anno1186.scripting; import org.clockworkmages.games.anno1186.GameCharacterService; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.character.GameCharacter; public class EnemyScriptingWrapper extends GameCharacterScriptingWrapper { @Injected private GameStateService gameStateService; @Injected private GameDataService gameDataService; @Injected private GameGuiService gameGuiService; @Injected private UtilScriptingWrapper utilScriptingWrapper; @Injected private GameCharacterService gameCharacterService; @Override protected GameCharacter getGameCharacter() { return gameStateService.getEnemy(); } @Override protected GameDataService getGameDataService() { return gameDataService; } @Override protected GameGuiService getGameGuiService() { return gameGuiService; } @Override protected GameStateService getGameStateService() { return gameStateService; } @Override protected UtilScriptingWrapper getUtilScriptingWrapper() { return utilScriptingWrapper; } @Override public GameCharacterService getGameCharacterService() { return gameCharacterService; } protected boolean isMe() { return false; } }
Java
package org.clockworkmages.games.anno1186.scripting; import java.util.HashMap; import java.util.Map; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.situation.Situation; public class SituationScriptingWrapper { @Injected private GameStateService gameStateService; public void addState(String stateId) { GameState gameState = gameStateService.getGameState(); Situation situation = gameState.getCurrentSituation(); String situationId = situation.getId(); Map<String, String> state = gameState.getSituationState().get( situationId); if (state == null) { state = new HashMap<String, String>(); gameState.getSituationState().put(situationId, state); } state.put(stateId, ""); } public void setState(String stateId, String value) { GameState gameState = gameStateService.getGameState(); Situation situation = gameState.getCurrentSituation(); String situationId = situation.getId(); Map<String, String> state = gameState.getSituationState().get( situationId); if (state == null) { state = new HashMap<String, String>(); gameState.getSituationState().put(situationId, state); } state.put(stateId, value); } public boolean hasState(String stateId) { GameState gameState = gameStateService.getGameState(); Situation situation = gameState.getCurrentSituation(); String situationId = situation.getId(); Map<String, String> state = gameState.getSituationState().get( situationId); if (state == null) { return false; } return state.containsKey(stateId); } public String getState(String stateId) { GameState gameState = gameStateService.getGameState(); Situation situation = gameState.getCurrentSituation(); String situationId = situation.getId(); Map<String, String> state = gameState.getSituationState().get( situationId); if (state == null) { return null; } return state.get(stateId); } }
Java
package org.clockworkmages.games.anno1186.scripting; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.clockworkmages.games.anno1186.GameCharacterService; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.gui.GameUiUtil; import org.clockworkmages.games.anno1186.model.character.GameCharacter; import org.clockworkmages.games.anno1186.model.character.GenderConstants; import org.clockworkmages.games.anno1186.model.character.Mutation; import org.clockworkmages.games.anno1186.model.character.Skill; import org.clockworkmages.games.anno1186.model.character.Stat; import org.clockworkmages.games.anno1186.model.common.Pair; import org.clockworkmages.games.anno1186.model.effect.Condition; import org.clockworkmages.games.anno1186.model.effect.ConditionStatus; import org.clockworkmages.games.anno1186.model.effect.Perk; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.combat.CombatSituation; import org.clockworkmages.games.anno1186.situations.inventory.InventoryItemSituation; import org.clockworkmages.games.anno1186.util.MathUtil; import org.clockworkmages.games.anno1186.util.RollUtil; public abstract class GameCharacterScriptingWrapper { protected abstract GameCharacter getGameCharacter(); // condition methods /** * Synonym to getEffectiveStat. * * @param statName * @return */ public double getStat(String statName) { return getEffectiveStat(statName); } public double getBaseStat(String statName) { return getStat(statName, getGameCharacter().getBaseStats()); } public double getEffectiveStat(String statName) { return getStat(statName, getGameCharacter().getEffectiveStats()); } public double getDerivate(String statName) { return getStat(statName, getGameCharacter().getDerivates()); } private double getStat(String statName, Map<String, Double> map) { Double statValue = map.get(statName); return statValue == null ? 0 : statValue; } public int getSkillLevel(String skillId) { GameCharacter gameCharacter = getGameCharacter(); Integer skillLevel = gameCharacter.getSkills().get(skillId); return skillLevel == null ? 0 : skillLevel.intValue(); } public int getGold() { GameCharacter gameCharacter = getGameCharacter(); return gameCharacter.getGold(); } public boolean isMale() { int gender = getGameCharacter().getGender(); return gender == GenderConstants.MALE; } public int getGender() { return getGameCharacter().getGender(); } public void setGender(int gender) { getGameCharacter().setGender(gender); } public boolean isUnarmed() { return !getGameCharacter().getEquippedItems().containsKey("RIGHT_HAND"); } // effect methods: public void addGold(int amount) { int newAmount = getGameCharacter().getGold() + amount; if (newAmount < 0) { newAmount = 0; } int difference = newAmount - getGameCharacter().getGold(); if (difference != 0) { getGameCharacter().setGold(newAmount); if (isMe()) { getGameGuiService().getTextPane().addInfoToBuffer( "Your " + (difference > 0 ? "gained" : "lost") + " " + Math.abs(difference) + " gold!\n"); } } } public void setStat(String statName, double value) { getGameCharacter().getBaseStats().put(statName, value); } public void addPerk(String perkId) { GameCharacter gameCharacter = getGameCharacter(); Perk perk = getGameDataService().getGameData().getPerks().get(perkId); if (perk == null) { GameUiUtil.logError("Invalid Perk reference: " + perkId); } else { gameCharacter.getPerks().add(perkId); scheduleRefresh(); } } public void addRandomMutation() { GameCharacter gameCharacter = getGameCharacter(); // TODO Mutation mutation = getGameDataService().getGameData().getMutations() .get("GOAT_HOOVES"); getGameGuiService().getTextPane().addInfoToBuffer( (isMe() ? "You now have " : gameCharacter.getName() + " now has ") + mutation.getName() + "!\n"); scheduleRefresh(); } public void increaseStat(String statId, double increaseBy) { if (increaseBy == 0) { return; } GameCharacter gameCharacter = getGameCharacter(); int roundedStatBefore = gameCharacter.getBaseStats() .containsKey(statId) ? (int) Math.floor(gameCharacter .getBaseStats().get(statId)) : 0; modifyStat(getGameCharacter().getBaseStats(), statId, increaseBy); int roundedStatAfter = (int) Math.floor(gameCharacter.getBaseStats() .get(statId)); if (roundedStatBefore != roundedStatAfter) { int increase = roundedStatAfter - roundedStatBefore; Stat stat = getGameDataService().getGameData().getStats() .get(statId); if (stat != null) { String text = ""; if (stat.isSocialStatus()) { text += stat.getName() + " "; if (roundedStatAfter >= 0) { text += "like " + (isMe() ? "you" : gameCharacter.getName()) + " "; text += " a bit "; if (increaseBy > 0) { text += "more "; } else { text += "less "; } } else { if (roundedStatAfter < 25) { text += "hate " + (isMe() ? "you" : gameCharacter.getName()); } else { text += "dislike " + (isMe() ? "you" : gameCharacter.getName()); } text += " a bit "; if (increaseBy > 0) { text += "less "; } else { text += "more "; } } text += "now!"; } else { text += (isMe() ? "Your " : gameCharacter.getName() + "'s ") + stat.getName() + " " + (increase > 0 ? "increased" : "decreased") + " by " + Math.abs(increase) + "!"; } getGameGuiService().getTextPane().addInfoToBuffer(text + "\n"); } scheduleRefresh(); } } public void increaseSkill(String skillId, int increaseBy) { if (increaseBy == 0) { return; } GameCharacter gameCharacter = getGameCharacter(); Integer currentValue = gameCharacter.getSkills().get(skillId); int newValue; if (currentValue == null) { newValue = increaseBy; } else { newValue = currentValue + increaseBy; } if (newValue < 1) { gameCharacter.getSkills().remove(skillId); } else { gameCharacter.getSkills().put(skillId, newValue); } Skill skill = getGameDataService().getGameData().getSkills() .get(skillId); getGameGuiService().getTextPane().addInfoToBuffer( (isMe() ? "Your " : gameCharacter.getName() + "'s ") + skill.getName() + " skill " + (increaseBy > 0 ? "increased" : "decreased") + " by " + Math.abs(increaseBy) + "!\n"); scheduleRefresh(); } public void modifyDamage(String damageTypeId, double minDamage, double range) { Double oldValueMinimal = getGameCharacter().getDamageMinimals().get( damageTypeId); if (oldValueMinimal == null) { oldValueMinimal = 0d; } double newValueMin = oldValueMinimal + minDamage; getGameCharacter().getDamageMinimals().put(damageTypeId, newValueMin); Double oldValueRange = getGameCharacter().getDamageRanges().get( damageTypeId); if (oldValueRange == null) { oldValueRange = 0d; } double newValueRange = oldValueRange + range; getGameCharacter().getDamageRanges().put(damageTypeId, newValueRange); } public void modifyStat(String statName, double value) { modifyStat(getGameCharacter().getEffectiveStats(), statName, value); } public void modifyDerivate(String statName, double value) { modifyStat(getGameCharacter().getDerivates(), statName, value); } private void modifyStat(Map<String, Double> map, String statName, double value) { Double oldValue = map.get(statName); if (oldValue == null) { oldValue = 0d; } double newValue = oldValue + value; map.put(statName, newValue); scheduleRefresh(); } public void modifyStatPerc(String statName, double percent) { modifyStatPerc(getGameCharacter().getEffectiveStats(), statName, percent); } public void modifyDerivatePerc(String statName, double percent) { modifyStatPerc(getGameCharacter().getDerivates(), statName, percent); } private void modifyStatPerc(Map<String, Double> map, String statName, double percent) { Double oldValue = map.get(statName); if (oldValue == null) { oldValue = 0d; } double newValue = oldValue * (100d + percent) / 100d; map.put(statName, newValue); scheduleRefresh(); } public void gainExperience(int experience) { if (experience != 0) { GameCharacter gameCharacter = getGameCharacter(); gameCharacter.setExperience(gameCharacter.getExperience() + experience); if (isMe()) { getGameGuiService() .addInfo( "You have gained " + experience + " experience points!"); int level = gameCharacter.getLevel(); int experienceNeededToLevelUp = MathUtil .experienceNeededToLevelUp(level + 1); if (experienceNeededToLevelUp <= gameCharacter.getExperience()) { getGameGuiService().addInfo( "You can now advance to a new level!"); } } } } public void restoreAll() { getGameCharacterService().restoreAll(getGameCharacter()); } public boolean skillRoll(String skillId, int difficulty) { int skillChance = skillChance(skillId, difficulty); double roll = getUtilScriptingWrapper().random(100); if (roll < skillChance) { return true; } else { return false; } } public boolean skillRoll(String skillId, int difficulty, String cacheKey) { int skillChance = skillChance(skillId, difficulty); double roll = getUtilScriptingWrapper().situationRandom(100, cacheKey); if (roll < skillChance) { return true; } else { return false; } } /** * Calculate the chance of success of a skill test. * * The chance is equal to (1-0.98^(skillLevel*10+[average value of skill's * ruling stats]*[skill's statModifier]))*100% . * * @param skillId * @param difficulty * difficulty of the test - 0 means average, positive means more * difficult, negative means easier. * * @return */ public int skillChance(String skillId, int difficulty) { GameCharacter gameCharacter = getGameCharacter(); Skill skill = getGameDataService().getGameData().getSkills() .get(skillId); Integer skillLevel = gameCharacter.getSkills().get(skillId); int pow = -difficulty; pow += MathUtil.zeroIfNull(skillLevel) * 10; for (String rulingStat : skill.getRulingStats()) { pow += MathUtil.zeroIfNull(gameCharacter.getEffectiveStats().get( rulingStat)) / skill.getStatModifier() / skill.getRulingStats().size(); } int chance = getUtilScriptingWrapper().chance(pow); return chance; } public boolean statRoll(String statId, int difficulty) { int rollChance = statChance(statId, difficulty); double roll = getUtilScriptingWrapper().random(100); if (roll < rollChance) { return true; } else { return false; } } public boolean statRoll(String statId, int difficulty, String cacheKey) { int rollChance = statChance(statId, difficulty); double roll = getUtilScriptingWrapper().situationRandom(100, cacheKey); if (roll < rollChance) { return true; } else { return false; } } public int statChance(String statId, int difficulty) { GameCharacter gameCharacter = getGameCharacter(); int statValue = gameCharacter.getEffectiveStatAsInt(statId); int pow = -difficulty; pow += MathUtil.zeroIfNull(statValue); int chance = RollUtil.chanceBase50(pow); return chance; } public void addItem(String itemId) { Item item = getGameDataService().getGameData().getItems().get(itemId); if (item == null) { GameUiUtil.logError("Invalid item reference: " + itemId); return; } GameCharacter character = getGameCharacter(); character.getInventory().add(item); getGameGuiService().getTextPane().addInfoToBuffer( item.getName() + " has been added to your inventory!\n"); } public boolean removeItem(String itemId) { GameCharacter character = getGameCharacter(); Iterator<Item> i = character.getInventory().iterator(); while (i.hasNext()) { Item item = i.next(); if (item.getId().equals(itemId)) { i.remove(); getGameGuiService().getTextPane().addInfoToBuffer( item.getName() + " has been removed from your inventory.\n"); return true; } } return false; } public void equipItemNoInv(String itemId) { Item item = getGameDataService().getGameData().getItems().get(itemId); if (item == null) { GameUiUtil.logError("Invalid item reference: " + itemId); return; } GameCharacter character = getGameCharacter(); getGameGuiService().getTextPane().addInfoToBuffer( item.getName() + " equipped!\n"); Item alreadyEquippedItem = character.getEquippedItems().get( item.getEquipmentSlotId()); if (alreadyEquippedItem != null) { // move the item to Inventory character.getInventory().add(alreadyEquippedItem); getGameGuiService().getTextPane().addInfoToBuffer( alreadyEquippedItem.getName() + " has been put back into your inventory!\n"); } getGameCharacter().getEquippedItems().put(item.getEquipmentSlotId(), item); } public void equipItem(String itemId) { boolean isInInventory = removeItem(itemId); if (!isInInventory) { GameUiUtil .logError("Item could not be equipped because it is not in inventory:" + itemId); return; } else { equipItemNoInv(itemId); } } public void unequipItem(String itemId) { GameCharacter character = getGameCharacter(); for (Entry<String, Item> entry : character.getEquippedItems() .entrySet()) { Item item = entry.getValue(); if (item.getId().equals(itemId)) { character.getEquippedItems().remove(entry.getKey()); character.getInventory().add(item); getGameGuiService() .getTextPane() .addInfoToBuffer( item.getName() + " has been unequipped and put back into your inventory.\n"); break; } } } public void removeCurrentItem() { Situation situation = getGameStateService().getGameState() .getPreviousSituation(); Item item = ((InventoryItemSituation) situation).getItem(); removeItem(item.getId()); } public void addCondition(String conditionId, int level, long milliseconds) { long validUntil = getGameStateService().getGameState().getTime() + milliseconds; Condition condition = getGameDataService().getGameData() .getConditions().get(conditionId); if (condition == null) { GameUiUtil.logError("Invalid Condition reference: " + conditionId); return; } else { ConditionStatus conditionStatus = getGameCharacter() .getConditions().get(conditionId); if (conditionStatus == null) { conditionStatus = condition.makeStatus(level, validUntil); getGameCharacter().getConditions().put(conditionId, conditionStatus); } else { if (level > conditionStatus.getLevel()) { conditionStatus.setLevel(level); } if (milliseconds == TimeConstants.DURATION_UNLIMITED) { conditionStatus.setValidUntil(validUntil); } else if (conditionStatus.getValidUntil() == TimeConstants.DURATION_UNLIMITED) { // do nothing } else if (validUntil > conditionStatus.getValidUntil()) { conditionStatus.setValidUntil(validUntil); } } getGameGuiService().addInfo(condition.getDescription()); } } public void incapacitate(String incapacitatedStateId, int difficulty) { if (!this.isMe()) { GameUiUtil .logError("Not (yet?) implemented! Cannot inflict an incapacitated state on an enemy!"); return; } CombatSituation combatSituation = this.getGameStateService() .getCurrentCombatSituation(); Pair<String, Integer> incapacitatedStateIdAndDificulty = new Pair<String, Integer>( incapacitatedStateId, difficulty); combatSituation.setIncapacitatedState(incapacitatedStateIdAndDificulty); } /** * Calculate the character's chances of surviving a lost combat. They're * equal to 100% if the character submitted (health>0%), 50% if the * character lost at 0% health and then diminish, reaching 0% if the * character finished combat at -25% health or less. * * @return */ public boolean survived() { GameCharacter character = getGameCharacter(); double healthPercent = character.getHealth() / character.getMaxHealth(); if (healthPercent > 0) { // apparently the player surrendered return true; } else if (healthPercent > -0.25) { double random = getUtilScriptingWrapper().situationRandom(25, "SURVIVING_DEFEAT"); if (healthPercent * (-100) < random) { return true; } else { return false; } } else { return false; } } public void healthAtLeast1() { GameCharacter character = getGameCharacter(); if (character.getHealth() < 1) { character.setHealth(1d); scheduleRefresh(); } } protected void scheduleRefresh() { getGameCharacter().setStatsAreStale(true); } protected abstract GameDataService getGameDataService(); protected abstract GameStateService getGameStateService(); protected abstract GameGuiService getGameGuiService(); protected abstract GameCharacterService getGameCharacterService(); protected abstract UtilScriptingWrapper getUtilScriptingWrapper(); protected abstract boolean isMe(); }
Java
package org.clockworkmages.games.anno1186.scripting; import org.clockworkmages.games.anno1186.GameCharacterService; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.character.GameCharacter; public class PlayerCharacterScriptingWrapper extends GameCharacterScriptingWrapper { @Injected private GameStateService gameStateService; @Injected private GameDataService gameDataService; @Injected private GameGuiService gameGuiService; @Injected private UtilScriptingWrapper utilScriptingWrapper; @Injected private GameCharacterService gameCharacterService; @Override protected GameCharacter getGameCharacter() { return gameStateService.getGameState().getCharacter(); } @Override protected GameDataService getGameDataService() { return gameDataService; } @Override protected GameGuiService getGameGuiService() { return gameGuiService; } @Override protected GameStateService getGameStateService() { return gameStateService; } @Override protected UtilScriptingWrapper getUtilScriptingWrapper() { return utilScriptingWrapper; } @Override public GameCharacterService getGameCharacterService() { return gameCharacterService; } protected boolean isMe() { return true; } }
Java
package org.clockworkmages.games.anno1186.scripting; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.clockworkmages.games.anno1186.GameAreaService; import org.clockworkmages.games.anno1186.GameData; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.map.tactical.GameArea; import org.clockworkmages.games.anno1186.model.map.tactical.GameAreaDO; import org.clockworkmages.games.anno1186.util.RollUtil; public class UtilScriptingWrapper { @Injected private GameStateService gameStateService; @Injected private GameDataService gameDataService; @Injected private GameAreaService gameAreaService; @Injected private GameGuiService gameGuiService; public double positiveOrZero(double value) { if (value >= 0) { return value; } else { return 0; } } public double random(int range) { return RollUtil.random(range); } /** * A random generator that stores the generated value in a static map so * that the same condition will return the same result for a single * Situation, even if the user switches to the Inventory, Spellbook or Stats * screen and then goes back to the current Situation. * * E.g. the player is in a room in a dungeon and he has a 50% chance to spot * a hidden lever. He rolls succesfully and spos the lever, and get an * aditional Option to pull it. But he goes to the Inventory screen and then * goes back to the Situation (dungeon room) screen. At that point we do not * want to re-roll the perception test, we want to reuse the original * result. * * * @param range * @param id * @return */ public double situationRandom(int range, String cacheKey) { int stackSize = gameStateService.getGameState().getSituationStack() .size(); Map<Integer, Map<String, Double>> situationRandoms = gameStateService .getGameState().getSituationCachedRandoms(); Map<String, Double> cachedValues = situationRandoms.get(stackSize); if (cachedValues == null) { cachedValues = new HashMap<String, Double>(); situationRandoms.put(stackSize, cachedValues); } Double cachedValue = cachedValues.get(cacheKey); if (cachedValue == null) { cachedValue = RollUtil.random(range); cachedValues.put(cacheKey, cachedValue); } return cachedValue; } public int chance(double pow) { return RollUtil.chance(pow); } public int chanceBase50(double pow) { return RollUtil.chanceBase50(pow); } public boolean roll(double pow) { return RollUtil.roll(pow); } public boolean roll(double pow, String cacheKey) { double roll = situationRandom(100, cacheKey); int chance = chance(pow); return roll <= chance; } public boolean rollBase50(double pow) { return RollUtil.rollBase50(pow); } public boolean rollBase50(double pow, String cacheKey) { double roll = situationRandom(100, cacheKey); int chance = chanceBase50(pow); return roll <= chance; } /** * Same as {@link #random(int, String)}, this method generates or gets an * existing value of a random. The values generated by this method are * cached for a duration of one game-day (until the character goes to sleep) * and then get evicted. * * @param range * @param id * @return */ public double dailyRandom(int range, String dailyCacheKey) { Map<String, Double> dailyCachedRandoms = gameStateService .getGameState().getDailyCachedRandoms(); Double cachedValue = dailyCachedRandoms.get(dailyCacheKey); if (cachedValue == null) { cachedValue = Math.random() * range; dailyCachedRandoms.put(dailyCacheKey, cachedValue); } return cachedValue; } public int getHour() { Date date = new Date(gameStateService.getGameState().getTime()); int hour = date.getHours(); return hour; } public boolean isDay() { Date date = new Date(gameStateService.getGameState().getTime()); int hour = date.getHours(); if (hour >= 6 && hour <= 18) { return true; } else { return false; } } public boolean isNight() { Date date = new Date(gameStateService.getGameState().getTime()); int hour = date.getHours(); if (hour <= 5 || hour >= 22) { return true; } else { return false; } } public boolean fetishesEnabled(String... fetishIds) { Set<String> fetishesEnabled = gameStateService.getGameState() .getFetishesEnabled(); for (String fetishId : fetishIds) { if (!fetishesEnabled.contains(fetishId)) { return false; } } return true; } public void goToLocation(String gameAreaId, int x, int y) { GameData gameData = gameDataService.getGameData(); GameAreaDO gameAreaDO = gameData.getGameAreas().get(gameAreaId); GameArea gameArea = gameAreaService.fromDO(gameAreaDO); GameState gameState = gameStateService.getGameState(); gameState.setGameArea(gameArea); gameState.setLocalMapX(x); gameState.setLocalMapY(y); gameGuiService.getLocalMapPanel().repaint(); } }
Java
package org.clockworkmages.games.anno1186; public interface DamageConstants { public double IMMUNE = -1d; public String PHYSICAL = "PHYSICAL", FIRE = "FIRE", FROST = "FROST", HOLY = "HOLY", SPIRIT = "SPIRIT"; }
Java
package org.clockworkmages.games.anno1186; import java.util.List; import org.clockworkmages.games.anno1186.gui.GameUiUtil; import org.clockworkmages.games.anno1186.model.GameMode; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.combat.CombatSituation; public class GameStateService { @Injected private GameDataService gameDataService; private GameState gameState = new GameState(); public GameState getGameState() { return gameState; } public void removeCurrentSituation() { List<Situation> situationStack = gameState.getSituationStack(); if (situationStack.size() > 0) { situationStack.remove(situationStack.size() - 1); } } public void addSituation(String situationId, boolean addToStack) { Situation situation = gameDataService.getGameData().getSituations() .get(situationId); if (situation == null) { GameUiUtil.logError("Invalid Situation reference \"" + situationId + "\" in an Option (current Situation=\"" + gameState.getCurrentSituation().getId() + "\") ."); } addSituation(situation, true); } public void addSituation(Situation situation, boolean addToStack) { List<Situation> situationStack = gameState.getSituationStack(); if (!addToStack) { removeCurrentSituation(); } gameState.setRecentlyAdded(gameState.getSituationStack().size()); situationStack.add(situation); evictSituationCache(situationStack.size()); gameState.setGameMode(GameMode.SITUATION); } /** * Evict the cached values for one of the situations (as apparently a new * Situation has been added that needs a fresh, empty cache). */ public void evictSituationCache(int stackSize) { gameState.getSituationCachedRandoms().remove(stackSize); } public void evictDailyCache() { gameState.getDailyCachedRandoms().clear(); } public boolean isInCombat() { for (Situation situation : gameState.getSituationStack()) { if (situation instanceof CombatSituation) { return true; } } return false; } public NonPlayerCharacter getEnemy() { CombatSituation combatSituation = getCurrentCombatSituation(); if (combatSituation != null) { return combatSituation.getEnemy(); } return null; } public CombatSituation getCurrentCombatSituation() { for (Situation situation : gameState.getSituationStack()) { if (situation instanceof CombatSituation) { return ((CombatSituation) situation); } } return null; } public boolean isCombat() { return gameState.getCurrentSituation() instanceof CombatSituation; } /** * Only to be used when loading a game or starting a new one. * * @param gameState */ public void setGameState(GameState gameState) { this.gameState = gameState; } }
Java
package org.clockworkmages.games.anno1186.util; public class MathUtil { private MathUtil() { } public static int zeroIfNull(Integer i) { if (i == null) { return 0; } else { return i.intValue(); } } public static double zeroIfNull(Double i) { if (i == null) { return 0; } else { return i.intValue(); } } public static double zeroOrMore(double d) { if (d < 0) { return 0d; } else { return d; } } public static int experienceNeededToLevelUp(int level) { // 100 to advance to lv2, 110 to advance to lv3 etc. int experienceNeededToLevelUp = level * 80 + (level + 1) * (level) / 2 * 10; return experienceNeededToLevelUp; } }
Java
package org.clockworkmages.games.anno1186.util; /** * Utility class for calculating chances of rolls based on the value of a Skill * or Stat. */ public class RollUtil { /** * Chance in a 1-100 (%) range, with power=0 resulting in chance=0. The * greater the power, the greater the chance, but the chance can never reach * 100. * * @param power * power * @return */ public static int chance(double power) { double chance = (1 - Math.pow(0.98, power)) * 100; return (int) chance; } /** * Chance in a 1-100 (%) range, with power=0 resulting in chance=50%. * power>0 mans chance increasing (over 50%) and pow<0 means chance * decreasing (below 50%). The greater the power, the greater the chance, * but the chance can never reach 100. * * @param power * power * @return */ public static int chanceBase50(double power) { int sign = power < 0 ? -1 : 1; double chance = 50 + sign * 50 * (1 - Math.pow(0.99, Math.abs(power))); return (int) chance; } /** * Roll with a in a 1-100 (%) range, with pow=0 resulting in chance of a * <b>true</b> result being equal to 0. * * @param power * power * @return */ public static boolean roll(double power) { double roll = random(100); int chance = chance(power); return roll <= chance; } public static boolean rollBase50(double power) { double roll = random(100); int chance = chanceBase50(power); return roll <= chance; } public static double random(int range) { return Math.random() * range; } }
Java
package org.clockworkmages.games.anno1186; import org.clockworkmages.games.anno1186.gui.AnimatedImage; public class GameTimeService implements TimeConstants { @Injected private GameStateService gameStateService; @Injected private GameGuiService gameGuiService; // @Inject // private GameCharacterService gameCharacterService; public void advanceTime(long timePassed) { GameState gameState = gameStateService.getGameState(); long newTime = gameState.getTime() + timePassed; gameState.setTime(newTime); AnimatedImage sunImage = gameGuiService.getTextPane().getSunImage(); AnimatedImage moonImage = gameGuiService.getTextPane().getMoonImage(); double targetSunState = new Double((newTime + 1.5 * HOUR) % DAY) / DAY; double targetMoonState = targetSunState - 0.5; while (targetSunState < sunImage.getState()) { targetSunState = targetSunState + 1; } while (targetMoonState < moonImage.getState()) { targetMoonState = targetMoonState + 1; } sunImage.setTargetState(targetSunState, (targetSunState - sunImage.getState()) * 7000); moonImage.setTargetState(targetMoonState, (targetMoonState - moonImage.getState()) * 7000); // called in SituationService: // if (gameState.getCharacter().isStatsAreStale()) { // gameCharacterService.refreshStats(gameState.getCharacter()); // } // if (gameStateService.isCombat()) { // if (gameState.getEnemy().isStatsAreStale()) { // gameCharacterService.refreshStats(gameState.getEnemy()); // } // } // gameGuiService.getStatsPane().repaint(); } }
Java
package org.clockworkmages.games.anno1186; public interface TimeConstants { long SECOND = 1000; long MINUTE = SECOND * 60; long HOUR = MINUTE * 60; long DAY = HOUR * 24; long COMBAT_TURN = 5 * SECOND; long DURATION_UNLIMITED = -1; }
Java
package org.clockworkmages.games.anno1186; import java.io.File; import java.io.FilenameFilter; public class SaveFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { if (name.startsWith("save") && name.endsWith(".xml")) { return true; } return false; } }
Java
package org.clockworkmages.games.anno1186; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.clockworkmages.games.anno1186.model.character.GameCharacter; import org.clockworkmages.games.anno1186.model.character.Skill; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.Condition; import org.clockworkmages.games.anno1186.model.effect.ConditionStatus; import org.clockworkmages.games.anno1186.model.effect.Effect; import org.clockworkmages.games.anno1186.model.effect.Perk; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.scripting.ScriptingService; public class GameCharacterService { @Injected private GameDataService gameDataService; @Injected private GameStateService gameStateService; @Injected private ScriptingService scriptingService; public void restoreAll(GameCharacter character) { double maxHp = character.getDerivates().get(StatConstants.D_MAX_HEALTH); character.getBaseStats().put(StatConstants.HEALTH, maxHp); double maxStamina = character.getDerivates().get( StatConstants.D_MAX_STAMINA); character.getBaseStats().put(StatConstants.STAMINA, maxStamina); Double maxFate = character.getEffectiveStats().get( StatConstants.MAX_FATE); // enemies do not have fate points: if (maxFate != null) { character.getBaseStats().put(StatConstants.FATE, maxFate); } character.setStatsAreStale(true); } public void refreshStats(GameCharacter character) { long gameTime = gameStateService.getGameState().getTime(); GameData gameData = gameDataService.getGameData(); // collect the effects that are set for the character, and sort out // those that are inactive (whose Conditions are not met): List<Effect> effects = new ArrayList<Effect>(); // add common effects that define how base stats (e.g. ENDURANCE) get // translated to derivates (e.g. MAX_HEALTH) effects.addAll(gameData.getBaseEffects()); // add character-specific stats: for (String perkId : character.getPerks()) { Perk perk = gameDataService.getGameData().getPerks().get(perkId); effects.addAll(perk.getEffects()); } for (Item equippedItem : character.getEquippedItems().values()) { effects.addAll(equippedItem.getEffects()); } List<EffectLevelPair> pairs = new ArrayList<EffectLevelPair>(); for (Effect effect : effects) { pairs.add(new EffectLevelPair(effect, null)); } for (Entry<String, ConditionStatus> entry : character.getConditions() .entrySet()) { String conditionId = entry.getKey(); ConditionStatus conditionStatus = entry.getValue(); long validUntil = conditionStatus.getValidUntil(); if (validUntil != -1 && validUntil < gameTime) { // condition is no longer active, remove it: character.getConditions().remove(conditionId); } else { Condition condition = gameData.getConditions().get(conditionId); int level = conditionStatus.getLevel(); // some conditions permanently affect base statistics (e.g. // increase or damage health) and can only be applied at // specified intervals. long lastExecuted = conditionStatus.getLastExecuted(); Long interval = condition.getInterval(); if (interval == null || interval < gameTime - lastExecuted) { for (Effect effect : condition.getEffects()) { pairs.add(new EffectLevelPair(effect, level)); } conditionStatus.setLastExecuted(gameTime); } } } for (Entry<String, Integer> entry : character.getSkills().entrySet()) { String skillId = entry.getKey(); int skillLevel = entry.getValue(); Skill skill = gameData.getSkills().get(skillId); for (Effect effect : skill.getEffects()) { pairs.add(new EffectLevelPair(effect, skillLevel)); } } List<EffectLevelPair> activePairs = new ArrayList<EffectLevelPair>(); for (EffectLevelPair pair : pairs) { String condition = pair.effect.getCondition(); if (condition == null || scriptingService.conditionIsMet(condition)) { activePairs.add(pair); } } Collections.sort(pairs); // clean up the old data: // we couldn't do it before checking the Effects' Conditions, in case // some conditions were based on derivates, such as // "only apply the Berzerk perk if currentHealth<50% of maxHealth". character.getEffectiveStats().clear(); character.getDerivates().clear(); for (Entry<String, Double> baseStat : character.getBaseStats() .entrySet()) { character.getEffectiveStats().put(baseStat.getKey(), baseStat.getValue()); } // execute the active Effects: for (EffectLevelPair pair : activePairs) { boolean characterIsEnemy = character.isEnemy(); Map<String, Object> model = scriptingService .getDefaultModel(characterIsEnemy); if (pair.level != null) { model.put("level", pair.level); } scriptingService.execute(pair.effect.getEffect(), model); } character.setStatsAreStale(false); } private class EffectLevelPair implements Comparable<EffectLevelPair> { public Effect effect; public Integer level; public EffectLevelPair(Effect effect, Integer level) { super(); this.effect = effect; this.level = level; } @Override public int compareTo(EffectLevelPair that) { // sort so that ffects get executd in the following order: // - increase modifiedStat by value // - increase modifiedStat by % // - increase derivate by value // - increase derivate by % int thisPrio = getPrio(this.effect.getEffect()); int thatPrio = getPrio(that.effect.getEffect()); return Integer.valueOf(thisPrio).compareTo(thatPrio); } private int getPrio(String effect) { if (effect.startsWith("modifyStatPerc")) { return 2; } if (effect.startsWith("modifyStat")) { return 1; } if (effect.startsWith("modifyDerivatePerc")) { return 4; } if (effect.startsWith("modifyDerivate")) { return 3; } return 5; } } }
Java
package org.clockworkmages.games.anno1186.text; import org.clockworkmages.games.anno1186.model.character.GenderConstants; public class TextUtil { public static String parse(String text) { TextNode textNode = new ComplexTextNode(text); String result = textNode.getParsedText(); return result; } public static String pronoun(int gender) { return capitalPronoun(gender).toLowerCase(); } public static String capitalPronoun(int gender) { if (gender == GenderConstants.MALE) { return "He"; } else if (gender == GenderConstants.FEMALE) { return "She"; } else { return "It"; } } }
Java
package org.clockworkmages.games.anno1186.text; import java.util.LinkedHashMap; import java.util.Map.Entry; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.scripting.ScriptingService; class ConditionalTextNode implements TextNode { private LinkedHashMap<String, ComplexTextNode> conditionalChildren = new LinkedHashMap<String, ComplexTextNode>(); private ComplexTextNode defaultChild; // private String ifExpression; public ConditionalTextNode(String ifExpression) { String remainingText = ifExpression; int ifCount = 0; int lengthSoFar = 0; int startOfCurrentCondition = 0; while (true) { remainingText = ifExpression.substring(lengthSoFar); int firstIfIndex = remainingText.indexOf("${if "); int firstFiIndex = remainingText.indexOf("${fi}"); int firstElseIndex = remainingText.indexOf("${else"); if (firstIfIndex > -1 && firstIfIndex < firstFiIndex && (firstIfIndex < firstElseIndex || firstElseIndex == -1)) { // "${fi}" is the first placeholder in the remaining text ifCount++; if (ifCount == 1) { startOfCurrentCondition = lengthSoFar + firstIfIndex; } // else { // ignore, it's an embedded lower-level "if" condition that will // be parsed later // } } else if (firstElseIndex > -1 && firstElseIndex < firstFiIndex && (firstElseIndex < firstIfIndex || firstIfIndex == -1)) { // "${else}" or {$elseif} is the first placeholder in the // remaining text if (ifCount == 1) { String conditionalPiece = ifExpression.substring( startOfCurrentCondition, lengthSoFar + firstElseIndex); registerConditionalChild(conditionalPiece); startOfCurrentCondition = lengthSoFar + firstElseIndex; } // else { // ignore, it's an embedded lower-level "if" condition that will // be parsed later // } } else if (firstFiIndex == -1) { throw new RuntimeException( "Conditional expression is invalid and cannot be parsed!"); } else { // "${fi}" is the first placeholder in the remaining text if (ifCount == 1) { String conditionalPiece = ifExpression .substring(startOfCurrentCondition, lengthSoFar + firstFiIndex); registerConditionalChild(conditionalPiece); break; } else { ifCount--; } } lengthSoFar += remainingText.indexOf("}") + 1; } } private void registerConditionalChild(String conditionPiece) { int beginningOfCondition = conditionPiece.indexOf(" "); int endOfCondition = conditionPiece.indexOf("}"); String text = conditionPiece.substring(endOfCondition + 1); ComplexTextNode textNode = new ComplexTextNode(text); if (beginningOfCondition == -1 || beginningOfCondition > endOfCondition) { // "${else}" condition: defaultChild = textNode; } else { // "${if ...}" or "${elseif ...}" condition: String condition = conditionPiece.substring( beginningOfCondition + 1, endOfCondition); this.conditionalChildren.put(condition, textNode); } } @Override public String getParsedText() { for (Entry<String, ComplexTextNode> entry : conditionalChildren .entrySet()) { if (GameBeansContext.getBean(ScriptingService.class) .conditionIsMet(entry.getKey())) { return entry.getValue().getParsedText(); } } if (defaultChild != null) { return defaultChild.getParsedText(); } return ""; // sb.append("[ELSE {" + defaultChild.getParsedText() + "}]"); // return sb.toString(); } }
Java
package org.clockworkmages.games.anno1186.text; interface TextNode { String getParsedText(); }
Java
package org.clockworkmages.games.anno1186.text; class PlainTextNode implements TextNode { private String plainText; public PlainTextNode(String plainText) { this.plainText = plainText; } @Override public String getParsedText() { return plainText; } }
Java
package org.clockworkmages.games.anno1186.text; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.scripting.ScriptingService; class PlaceholderTextNode implements TextNode { private String placeholder; public PlaceholderTextNode(String placeholder) { this.placeholder = placeholder; } @Override public String getParsedText() { return GameBeansContext.getBean(ScriptingService.class) .eval(placeholder).toString(); } }
Java
package org.clockworkmages.games.anno1186.text; import java.util.ArrayList; import java.util.List; class ComplexTextNode implements TextNode { private List<TextNode> children = new ArrayList<TextNode>(); public ComplexTextNode(String text) { String remainingText = text == null ? "" : text; while (remainingText.length() > 0) { int openingIndex = remainingText.indexOf("${"); int closingIndex = remainingText.indexOf("}"); if (openingIndex > closingIndex) { // TODO report error break; } if (openingIndex > -1) { if (closingIndex < openingIndex) { // TODO report error break; } children.add(new PlainTextNode(remainingText.substring(0, openingIndex))); } else { children.add(new PlainTextNode(remainingText)); break; } String expression = remainingText.substring(openingIndex + 2, closingIndex); if (expression.startsWith("if ")) { // //TODO int matchingClosingExpressionIndex = 0; String remainingText2 = remainingText.substring(openingIndex); int ifCount = 0; // counts additional "if" clauses that may be // embedded inside the main "if" condition while (true) { int firstIfIndex = remainingText2.indexOf("${if "); int firstFiIndex = remainingText2.indexOf("${fi}"); if (firstFiIndex == -1) { throw new RuntimeException( "Text contains invalid conditional expressions and cannot be parsed: " + text); } else if (firstFiIndex < firstIfIndex || firstIfIndex == -1) { if (ifCount == 1) { matchingClosingExpressionIndex += firstFiIndex; break; } else { ifCount--; } matchingClosingExpressionIndex += firstFiIndex + 2; remainingText2 = remainingText2 .substring(firstFiIndex + 2); } else { ifCount++; matchingClosingExpressionIndex += firstIfIndex + 2; remainingText2 = remainingText2 .substring(firstIfIndex + 2); } } String ifExpression = remainingText.substring(openingIndex, openingIndex + matchingClosingExpressionIndex + 5); children.add(new ConditionalTextNode(ifExpression)); remainingText = remainingText.substring(openingIndex + matchingClosingExpressionIndex + 5); } else { children.add(new PlaceholderTextNode(expression)); remainingText = remainingText.substring(closingIndex + 1); } } } @Override public String getParsedText() { StringBuffer sb = new StringBuffer(); for (TextNode textNode : children) { sb.append(textNode.getParsedText()); } return sb.toString(); } }
Java
package org.clockworkmages.games.anno1186.dao; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.clockworkmages.games.anno1186.model.Fetish; import org.clockworkmages.games.anno1186.model.character.Mutation; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.character.Skill; import org.clockworkmages.games.anno1186.model.character.Stat; import org.clockworkmages.games.anno1186.model.effect.Condition; import org.clockworkmages.games.anno1186.model.effect.Effect; import org.clockworkmages.games.anno1186.model.effect.Perk; import org.clockworkmages.games.anno1186.model.item.EquipmentSlot; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.map.tactical.GameAreaDO; import org.clockworkmages.games.anno1186.model.map.tactical.SimpleTileObject; import org.clockworkmages.games.anno1186.model.option.GenericOption; import org.clockworkmages.games.anno1186.model.situation.GenericSituation; @XmlRootElement(name = "gameObjects") @XmlAccessorType(XmlAccessType.NONE) public class GameObjectsList { private List<GenericSituation> situations = new ArrayList<GenericSituation>(); private List<GenericOption> options = new ArrayList<GenericOption>(); private List<Stat> stats = new ArrayList<Stat>(); private List<Skill> skills = new ArrayList<Skill>(); private List<Perk> perks = new ArrayList<Perk>(); private List<Effect> baseEffects = new ArrayList<Effect>(); private List<Condition> conditions = new ArrayList<Condition>(); private List<EquipmentSlot> equipmentSlots = new ArrayList<EquipmentSlot>(); private List<Item> items = new ArrayList<Item>(); private List<Mutation> mutations = new ArrayList<Mutation>(); private List<ImageIconDescriptor> icons = new ArrayList<ImageIconDescriptor>(); private String gameStartSituation; private List<NonPlayerCharacter> npcs = new ArrayList<NonPlayerCharacter>(); private List<Fetish> fetishes = new ArrayList<Fetish>(); private List<SimpleTileObject> tileObjects = new ArrayList<SimpleTileObject>(); private List<GameAreaDO> gameAreas = new ArrayList<GameAreaDO>(); @XmlElement(name = "situation") public List<GenericSituation> getSituations() { return situations; } public void setSituations(List<GenericSituation> situations) { this.situations = situations; } @XmlElement(name = "option") public List<GenericOption> getOptions() { return options; } public void setOptions(List<GenericOption> options) { this.options = options; } @XmlElement(name = "equipmentSlot") public List<EquipmentSlot> getEquipmentSlots() { return equipmentSlots; } public void setEquipmentSlots(List<EquipmentSlot> equipmentSlots) { this.equipmentSlots = equipmentSlots; } @XmlElement(name = "perk") public List<Perk> getPerks() { return perks; } public void setPerks(List<Perk> perks) { this.perks = perks; } @XmlElement(name = "gameStartSituation") public String getGameStartSituation() { return gameStartSituation; } public void setGameStartSituation(String gameStartSituation) { this.gameStartSituation = gameStartSituation; } @XmlElement(name = "stat") public List<Stat> getStats() { return stats; } public void setStats(List<Stat> stats) { this.stats = stats; } @XmlElement(name = "skill") public List<Skill> getSkills() { return skills; } public void setSkills(List<Skill> skills) { this.skills = skills; } @XmlElement(name = "mutation") public List<Mutation> getMutations() { return mutations; } public void setMutations(List<Mutation> mutations) { this.mutations = mutations; } @XmlElement(name = "imageIcon") public List<ImageIconDescriptor> getIcons() { return icons; } public void setIcons(List<ImageIconDescriptor> imageIcons) { this.icons = imageIcons; } @XmlElement(name = "condition") public List<Condition> getConditions() { return conditions; } public void setConditions(List<Condition> conditions) { this.conditions = conditions; } @XmlElement(name = "item") public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } @XmlElement(name = "baseEffect") public List<Effect> getBaseEffects() { return baseEffects; } public void setBaseEffects(List<Effect> baseEffects) { this.baseEffects = baseEffects; } @XmlElement(name = "npc") public List<NonPlayerCharacter> getNpcs() { return npcs; } public void setNpcs(List<NonPlayerCharacter> npcs) { this.npcs = npcs; } @XmlElement(name = "fetish") public List<Fetish> getFetishes() { return fetishes; } public void setFetishes(List<Fetish> fetishes) { this.fetishes = fetishes; } @XmlElement(name = "tileObject") public List<SimpleTileObject> getTileObjects() { return tileObjects; } public void setTileObjects(List<SimpleTileObject> tileObjects) { this.tileObjects = tileObjects; } @XmlElement(name = "gameArea") public List<GameAreaDO> getGameAreas() { return gameAreas; } public void setGameAreas(List<GameAreaDO> gameAreas) { this.gameAreas = gameAreas; } }
Java
package org.clockworkmages.games.anno1186.dao; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class SerializationUtil { public static String serializeGameData(GameObjectsList gameObjects, boolean prettyPrint) { String serialized = serialize(gameObjects, prettyPrint); // TODO: ugly workarounds for JAXB's marshalling of default values. // There must be some beter way to do that... String[] defaults = new String[] { " addToStack=\"false\"", // " goBack=\"false\"", // " probability=\"0\"", // " clearScreen=\"true\"", // " consumesCombatAction=\"false\"", // " textfield=\"false\"", // " or=\"false\"", // }; for (String s : defaults) { serialized = serialized.replace(s, ""); } // clean up empty lines // .replaceAll("(?m)^[ \t]*\r?\n", ""); return serialized; } public static String serialize(Object o, boolean prettyPrint) { try { StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = context.createMarshaller(); if (prettyPrint) { marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); } marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, ""); marshaller.marshal(o, writer); String serialized = writer.toString(); return serialized; } catch (Exception e) { throw new RuntimeException(e); } } public static GameObjectsList deserializeGameData(String serializedString) { // TODO: ugly workaround for JAXB's ugly marshalling // serializedString = serializedString // .replace("<option>", "<option xsi:type=\"genericOption\">") // .replace( // "<gameObjects>", // "<gameObjects xsi:schemaLocation=\"\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); Reader reader = new StringReader(serializedString); return deserializeGameData(reader); } public static GameObjectsList deserializeGameData(Reader reader) { return deserialize(reader, GameObjectsList.class); } public static <T> T deserialize(Reader reader, Class<T> clazz) { try { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); return (T) unmarshaller.unmarshal(reader); } catch (Exception e) { throw new RuntimeException(e); } } }
Java
package org.clockworkmages.games.anno1186.dao; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "gameFiles") @XmlAccessorType(XmlAccessType.NONE) public class GameFilesList { private List<String> files = new ArrayList<String>(); @XmlElement(name = "file") public List<String> getFiles() { return files; } public void setFiles(List<String> files) { this.files = files; } }
Java
package org.clockworkmages.games.anno1186.dao; import org.clockworkmages.games.anno1186.model.GameObject; public class ImageIconDescriptor extends GameObject { private String path; public ImageIconDescriptor() { } public ImageIconDescriptor(String id, String path) { super(id); this.path = path; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
Java
package org.clockworkmages.games.anno1186.dao; import java.awt.Image; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class FileUtil { public static Image getResourceAsImage(String resourcePath) { try { Image image = javax.imageio.ImageIO.read(FileUtil.class .getClassLoader().getResourceAsStream(resourcePath)); return image; } catch (IOException e) { e.printStackTrace(); return null; } } public static void write(String filePath, String content) { File file = new File(filePath); try { // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } FileOutputStream fop = new FileOutputStream(file); // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
package org.clockworkmages.games.anno1186; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.clockworkmages.games.anno1186.model.GameMode; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.map.tactical.GameArea; import org.clockworkmages.games.anno1186.model.situation.Situation; @XmlRootElement(name = "gameState") @XmlAccessorType(XmlAccessType.NONE) public class GameState { private long time; private List<Situation> situationStack = new ArrayList<Situation>(); /** * The situation that contained the Option that is currently being executed. */ private Situation previousSituation; private GameMode gameMode; private GameArea gameArea; private int localMapX; private int localMapY; private Map<String, String> plot = new HashMap<String, String>(); private Map<String, Map<String, String>> situationState = new HashMap<String, Map<String, String>>(); private PlayerCharacter character = new PlayerCharacter(); private int recentlyAdded; private Map<Integer, Map<String, Double>> situationCachedRandoms = new HashMap<Integer, Map<String, Double>>(); private Map<String, Double> dailyCachedRandoms = new HashMap<String, Double>(); private Set<String> fetishesEnabled = new HashSet<String>(); @XmlTransient public Situation getCurrentSituation() { if (this.situationStack.size() == 0) { // ok, the Situation has finished, we will now go back to the // GameMode.LOCAL_MAP return null; } else { return this.situationStack.get(this.situationStack.size() - 1); } } @XmlTransient public List<Situation> getSituationStack() { return situationStack; } @XmlElement public PlayerCharacter getCharacter() { return character; } public void setCharacter(PlayerCharacter character) { this.character = character; } /** * @return true if current Situation is the one that has been added to the * stack most recently (=if there were no other Situations that were * added and then removed from the stack since the current Situation * was added to it). */ public boolean currentSituationWasRecentlyAdded() { return recentlyAdded == situationStack.size() - 1; } @XmlElement public Map<String, String> getPlot() { return plot; } public void setPlot(Map<String, String> plot) { this.plot = plot; } @XmlTransient public Map<String, Map<String, String>> getSituationState() { return situationState; } @XmlAttribute public long getTime() { return time; } public void setTime(long time) { this.time = time; } @XmlTransient public int getRecentlyAdded() { return recentlyAdded; } // Setters, for deserialization (loading games) only public void setRecentlyAdded(int recentlyAdded) { this.recentlyAdded = recentlyAdded; } @XmlTransient public Map<Integer, Map<String, Double>> getSituationCachedRandoms() { return situationCachedRandoms; } public void setSituationRandoms( Map<Integer, Map<String, Double>> situationCachedRandoms) { this.situationCachedRandoms = situationCachedRandoms; } @XmlElement public Map<String, Double> getDailyCachedRandoms() { return dailyCachedRandoms; } public void setDailyCachedRandoms(Map<String, Double> dailyCachedValues) { this.dailyCachedRandoms = dailyCachedValues; } @XmlTransient public Situation getPreviousSituation() { return previousSituation; } public void setPreviousSituation(Situation previousSituation) { this.previousSituation = previousSituation; } @XmlElement public Set<String> getFetishesEnabled() { return fetishesEnabled; } public void setSituationStack(List<Situation> situationStack) { this.situationStack = situationStack; } public void setSituationState( Map<String, Map<String, String>> situationState) { this.situationState = situationState; } public void setSituationCachedRandoms( Map<Integer, Map<String, Double>> situationCachedRandoms) { this.situationCachedRandoms = situationCachedRandoms; } public void setFetishesEnabled(Set<String> fetishesEnabled) { this.fetishesEnabled = fetishesEnabled; } @XmlAttribute public GameMode getGameMode() { return gameMode; } public void setGameMode(GameMode gameMode) { this.gameMode = gameMode; } @XmlElement public GameArea getGameArea() { return gameArea; } public void setGameArea(GameArea currentArea) { this.gameArea = currentArea; } @XmlAttribute public int getLocalMapX() { return localMapX; } public void setLocalMapX(int localMapX) { this.localMapX = localMapX; } @XmlAttribute public int getLocalMapY() { return localMapY; } public void setLocalMapY(int localMapY) { this.localMapY = localMapY; } }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Disarm trap minigame: click on the shape that repeats most frequently in the * shown picture. I correct, all those shapes will disappear from the picture. * Repeat until all shapes disappear. Must pick all the shapes in orrect order * before the time runs out. */ public class DisarmPickMostNumerousController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Disarm trap minigame: click on the numbers that the big number shown above * can be divided by. Must succesfully divide to 1 before the time runs out. */ public class DisarmPrimeNumbersController { }
Java
package org.clockworkmages.games.anno1186.controllers; public class SituationOptionController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Pick the lock minigame: guess the correct combination with hints telling how * many of the guessed options are on correct places, and how many are on * present in the solution, but on incorrect places. * * Only has N chances to guess before the lock is jammed. */ public class LockpickMastermindController { }
Java
package org.clockworkmages.games.anno1186.controllers; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.SituationService; import org.clockworkmages.games.anno1186.gui.LocalMapPanel; import org.clockworkmages.games.anno1186.model.Direction; import org.clockworkmages.games.anno1186.model.GameMode; import org.clockworkmages.games.anno1186.model.map.tactical.Tile; import org.clockworkmages.games.anno1186.model.map.tactical.TileObject; public class LocalMapMovementController { @Injected private GameStateService gameStateService; @Injected private GameGuiService gameGuiService; @Injected private SituationService situationService; public void move(String keyPressed) { GameState gameState = gameStateService.getGameState(); boolean stateAllowsMovement = GameMode.LOCAL_MAP.equals(gameState .getGameMode()); if (stateAllowsMovement) { Direction direction; switch (keyPressed) { case "w": direction = Direction.NORTH; break; case "d": direction = Direction.EAST; break; case "s": direction = Direction.SOUTH; break; case "a": direction = Direction.WEST; break; default: // not recognized, so not moving anywhere: return; } move(direction, gameState); } } private void move(Direction direction, GameState gameState) { int currentX = gameState.getLocalMapX(); int currentY = gameState.getLocalMapY(); int targetX = currentX + direction.getX(); int targetY = currentY + direction.getY(); if (targetX < 0) { // TODO: check if the player can leave this area by going WEST. If // so, present a Situation screen asking him if he wants to continue // in that direction or return to the camp. } else if (targetY < 0) { // TODO: check if the player can leave this area by going SOUTH } Tile[][] tiles = gameState.getGameArea().getTiles(); if (targetX == tiles.length) { // TODO: check if the player can leave this area by going EAST } else if (targetY == tiles[targetX].length) { // TODO: check if the player can leave this area by going NORTH } Tile targetTile = tiles[targetX][targetY]; String situationId = null; boolean isPassable = true; for (TileObject tileObject : targetTile.getTileObjects()) { if (tileObject.getSituationId() != null) { situationId = tileObject.getSituationId(); isPassable = false; break; } else if (!tileObject.isPassable()) { isPassable = false; } } if (situationId != null) { gameStateService.addSituation(situationId, true); situationService.playCurrentSituation(); } else if (!isPassable) { // show the "The path is blocked" message. } else { gameState.setLocalMapX(targetX); gameState.setLocalMapY(targetY); // run the NPC turn, run perception tests etc. LocalMapPanel localMapPanel = gameGuiService.getLocalMapPanel(); localMapPanel.repaint(); } } }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Alchemy minigame: start by expending a phylosophical stone, then add * ingredients to produce the desired effect. The phylosophical stone sets the * three first essences of the potion to a randomized state (1,0 or -1). * * @author Tomek * */ // Initial state after expending the phylosophical stone: // // A // ------ // BC // // Recipe: // // A // AB // ------ // D // // Ingredient: // B // ABC // ------ // D public class AlchemyCardController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Pick the lock minigame: set the combination to all-white-bytes using * tetris-like byte blocks. * * The player can choose from 6 byte blocks at any given time, with new block * appearing after an old was expended. * * Only has N chances to switch before the lock is jammed. */ // E.g. // Initial state: // -##--- // Blocks that will clear that combination: // -#---- // -#-#-- // ##---- // #--#-- public class LockpickByteSwitchController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Pick the lock minigame: put the blocks in a single line. Choosing a lever * moves the block over it by 2 in chosen direction, but it also moves the * blocks adjacent to it by 1 in random direction. * * * Only has N chances to guess before the lock is jammed. */ // e.g. // // ---#- // --#-# // ##--- // // ^^^^^ // vvvvv public class LockpickBlocksController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Disarm trap minigame: select the N first numbers after the coma that are the * result of a division of large numbers ( * "What is the first place before the coma of 564 divided by 69? 8. Correct! What is the first place before the coma of 80 ((564-8*69)*10) divided by 69?" * ). Must name correct N places after the coma before the time runs out. */ public class DisarmDividingController { }
Java
package org.clockworkmages.games.anno1186.controllers; public class CombatCardController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Pick the lock minigame: find all pairs by flipping the cards. * * Only has N chances to find all pairs before the lock is jammed. */ public class LockpickMemoryController { }
Java
package org.clockworkmages.games.anno1186.controllers; /** * Disarm trap minigame: pick the image that has the same shape or color as one * of the pictures shown above.Must choose N correct imags bfore the time runs * out. */ public class DisarmSimilaritiesController { }
Java
package org.clockworkmages.games.anno1186; import java.util.List; import org.clockworkmages.games.anno1186.model.situation.ExplorableGameEvent; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.model.situation.SituationPoolForwarder; public class SituationPoolService { @Injected private GameDataService gameDataService; public Situation getRandomSituationFromPool(String situationPoolId) { List<ExplorableGameEvent> situationPool = gameDataService.getGameData() .getEventPools().get(situationPoolId); // TODO: must be enhanced using probability and conditions: int selectedIndex = (int) Math.floor(Math.random() * situationPool.size()); ExplorableGameEvent explorableEvent = situationPool.get(selectedIndex); if (explorableEvent instanceof Situation) { return (Situation) explorableEvent; } else if (explorableEvent instanceof SituationPoolForwarder) { return getRandomSituationFromPool(explorableEvent .getAreaType()); } else { // TODO exception, not supported return null; } } }
Java
package org.clockworkmages.games.anno1186; import java.util.Map.Entry; import org.clockworkmages.games.anno1186.model.character.GameCharacter; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.util.RollUtil; public class CombatUtil { private CombatUtil() { } public static void performAttack(GameGuiService gameGuiService, GameCharacter defender, GameCharacter attacker) { double attackersAccuracy = attacker.getDerivates().get( StatConstants.D_ACCURACY); double defendersEvasion = defender.getDerivates().get( StatConstants.D_EVASION); // if my accuracy equals enemy's evasion then the chance to hit is 50%: double pow = attackersAccuracy - defendersEvasion; boolean hitSuccesfull = RollUtil.rollBase50(pow); String infoText; if (hitSuccesfull) { double totalUnresistedDamage = 0;// damage as it would be if the // enemy had no resistances double totalInflictedDamage = 0; // damage that was actually // inflicted, enemy's // resistances // considered for (Entry<String, Double> entry : attacker.getDamageMinimals() .entrySet()) { String damageType = entry.getKey(); double damageMinimal = entry.getValue(); Double damageRange = attacker.getDamageRanges().get(damageType); if (damageRange == null) { damageRange = 0d; } double unresistedDamage = damageMinimal + Math.random() * damageRange; if (DamageConstants.PHYSICAL.equals(damageType)) { // physical damage additionally gets modified with attackers // strength: unresistedDamage = unresistedDamage * (100d + attacker.getEffectiveStats().get( StatConstants.STRENGTH)) / 100d; } Double enemyResistance = defender.getDamageResistances().get( damageType); if (enemyResistance == null) { enemyResistance = 0d; } double inflictedDamage; if (enemyResistance == DamageConstants.IMMUNE) { // the enemy is completely resistant to that kind of damage inflictedDamage = 0d; continue; } else { inflictedDamage = unresistedDamage * Math.pow(0.99, enemyResistance); } totalUnresistedDamage += unresistedDamage; totalInflictedDamage += inflictedDamage; } if (totalInflictedDamage != 0) { defender.increaseBaseStat(StatConstants.HEALTH, -totalInflictedDamage); defender.setStatsAreStale(true); } infoText = (attacker.isEnemy() ? attacker.getName() + " hits you" : "You hit " + defender.getName()) + " for " + (int) totalInflictedDamage + " damage!" + (totalInflictedDamage < totalUnresistedDamage ? " (" + (int) (100 * totalInflictedDamage / totalUnresistedDamage) + "% resisted)" : ""); } else { infoText = attacker.isEnemy() // ? (attacker.isAddThe() ? "The " : "") + attacker.getName() + " misses!" // : "You miss!"; } gameGuiService.getTextPane().addInfoToBuffer(infoText + "\n"); } }
Java
package org.clockworkmages.games.anno1186; import javax.swing.JList; import javax.swing.JTextField; import org.clockworkmages.games.anno1186.gui.LocalExplorationPanel; import org.clockworkmages.games.anno1186.gui.GamePanel; import org.clockworkmages.games.anno1186.gui.InfoTextPane; import org.clockworkmages.games.anno1186.gui.LocalMapPanel; import org.clockworkmages.games.anno1186.gui.MainTextPanel; import org.clockworkmages.games.anno1186.gui.OptionTextInputKeyListener; import org.clockworkmages.games.anno1186.model.option.Option; public class GameGuiService { // private AnimatedTextPane textPane; // // private InfoTextPane statsPane; // // private JList<Option> optionList; // // private JTextField optionTextInput; // // private OptionTextInputKeyListener optionTextInputKeyListener; // // private JPanel optionCardPanel; private GamePanel gamePanel; public void setGamePanel(GamePanel gamePanel) { this.gamePanel = gamePanel; } public MainTextPanel getTextPane() { return gamePanel.getExplorationPanel().getTextPane(); } public InfoTextPane getBottomLeft() { return gamePanel.getExplorationPanel().getBottomLeftPanel(); } public JList<Option> getOptionList() { return gamePanel.getExplorationPanel().getOptionList(); } public JTextField getOptionTextInput() { return gamePanel.getExplorationPanel().getOptionTextInput(); } public OptionTextInputKeyListener getOptionTextInputKeyListener() { return gamePanel.getExplorationPanel().getOptionTextInputKeyListener(); } // public JPanel getOptionCardPanel() { // return gamePanel.getOptionCardPanel(); // } public GamePanel getGamePanel() { return gamePanel; } public LocalExplorationPanel getExplorationPanel() { return gamePanel.getExplorationPanel(); } public void addInfo(String info) { this.getTextPane().addInfoToBuffer(info + "\n"); } public void addText(String text) { this.getTextPane().appendText(text); } public LocalMapPanel getLocalMapPanel() { return gamePanel.getExplorationPanel().getLocalMapPanel(); } }
Java
package org.clockworkmages.games.anno1186.situations.inventory; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.generator.sets.TechnicalSituationConstants; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.scripting.PlayerCharacterScriptingWrapper; public class InventoryItemSituation extends Situation { private Item item; public InventoryItemSituation(final Item item) { this.item = item; this.setTitle(item.getName()); this.setText(item.getDescription()); List<Option> options = getOptions(); Option option; if (item.getEquipmentSlotId() != null) { option = new Option() { @Override public void select() { PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper = GameBeansContext .getBean(PlayerCharacterScriptingWrapper.class); playerCharacterScriptingWrapper.equipItem(item.getId()); super.select(); } }; option.setLabel("Equip"); option.setGoToSituation(TechnicalSituationConstants.ST_EMPTY_RETURN); options.add(option); } options.addAll(item.getUseOptions()); option = new Option() { @Override public void select() { PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper = GameBeansContext .getBean(PlayerCharacterScriptingWrapper.class); playerCharacterScriptingWrapper.removeItem(item.getId()); super.select(); } }; option.setLabel("Discard"); option.setGoToSituation(TechnicalSituationConstants.ST_EMPTY_RETURN); options.add(option); options.add(GoBackOption.INSTANCE); } public Item getItem() { return item; } }
Java
package org.clockworkmages.games.anno1186.situations.inventory; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.inventory.options.EquippedItemOption; import org.clockworkmages.games.anno1186.situations.inventory.options.InventoryItemOption; public class InventorySituation extends Situation { public InventorySituation() { super("ST_INVENTORY"); setTitle("Inventory"); } @Override public void update() { super.update(); GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); PlayerCharacter playerCharacter = gameStateService.getGameState() .getCharacter(); List<Option> options = getOptions(); options.clear(); String text = ""; if (playerCharacter.getInventory().size() > 0) { text += "\nYou carry following items: \n"; for (Item item : playerCharacter.getInventory()) { text += " - " + item.getName() + "\n"; options.add(new InventoryItemOption(item)); } } if (playerCharacter.getEquippedItems().size() > 0) { text += "\nYou have following items equipped: \n"; for (Item equippedItem : playerCharacter.getEquippedItems() .values()) { text += " - " + equippedItem.getName() + "\n"; options.add(new EquippedItemOption(equippedItem)); } } setText(text); options.add(GoBackOption.INSTANCE); } }
Java
package org.clockworkmages.games.anno1186.situations.inventory; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.generator.sets.TechnicalSituationConstants; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.scripting.PlayerCharacterScriptingWrapper; public class EquippedItemSituation extends Situation { public EquippedItemSituation(final Item item) { this.setTitle(item.getName()); this.setText(item.getDescription()); List<Option> options = getOptions(); Option option; option = new Option() { @Override public void select() { PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper = GameBeansContext .getBean(PlayerCharacterScriptingWrapper.class); playerCharacterScriptingWrapper.unequipItem(item.getId()); super.select(); } }; option.setLabel("Unequip"); option.setGoToSituation(TechnicalSituationConstants.ST_EMPTY_RETURN); options.add(option); options.add(GoBackOption.INSTANCE); } }
Java
package org.clockworkmages.games.anno1186.situations.inventory.options; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.inventory.InventorySituation; public class InventoryOption extends Option { public static InventoryOption INSTANCE = new InventoryOption(); @Injected private GameStateService gameStateService; private InventoryOption() { super("INVENTORY"); this.setLabel("Inventory"); } @Override public void select() { InventorySituation situation = new InventorySituation(); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.inventory.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.inventory.EquippedItemSituation; public class EquippedItemOption extends Option { private Item item; public EquippedItemOption(Item item) { this.item = item; this.setLabel(item.getName() + " (equipped)"); } @Override public void select() { GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); EquippedItemSituation situation = new EquippedItemSituation(item); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.inventory.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.item.Item; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.inventory.InventoryItemSituation; public class InventoryItemOption extends Option { private Item item; public InventoryItemOption(Item item) { this.item = item; this.setLabel(item.getName()); } @Override public void select() { InventoryItemSituation situation = new InventoryItemSituation(item); GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.combat; public enum CombatStatus { STARTING, IN_PROGRESS, SURRENDERED, FLED }
Java
package org.clockworkmages.games.anno1186.situations.combat; import java.util.List; import java.util.Map; import org.clockworkmages.games.anno1186.CombatUtil; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameCharacterService; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.OptionUtil; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.model.character.IncapacitatedState; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.character.SpecialAttack; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.common.Pair; import org.clockworkmages.games.anno1186.model.effect.Condition; import org.clockworkmages.games.anno1186.model.effect.ConditionConstanst; import org.clockworkmages.games.anno1186.model.effect.ConditionStatus; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.scripting.PlayerCharacterScriptingWrapper; import org.clockworkmages.games.anno1186.scripting.ScriptingService; import org.clockworkmages.games.anno1186.situations.combat.options.AttackOption; import org.clockworkmages.games.anno1186.situations.combat.options.FleeOption; import org.clockworkmages.games.anno1186.situations.combat.options.ResistIncapacitatedStateOption; import org.clockworkmages.games.anno1186.situations.combat.options.SurrenderOption; import org.clockworkmages.games.anno1186.text.TextUtil; public class CombatSituation extends Situation { // private boolean initiated; private CombatStatus combatStatus; private boolean playerConsumedCombatAction = false; /** * IncapacitatedState's ID and the difficulty of resisting/overcoming it. */ private Pair<String, Integer> incapacitatedState = null; private NonPlayerCharacter enemy; private PlayerCharacter me; private GameCharacterService gameCharacterService; private GameStateService gameStateService; private GameDataService gameDataService; private GameGuiService gameGuiService; private ScriptingService scriptingService; private PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper; public CombatSituation(NonPlayerCharacter enemy) { gameCharacterService = GameBeansContext .getBean(GameCharacterService.class); playerCharacterScriptingWrapper = GameBeansContext .getBean(PlayerCharacterScriptingWrapper.class); gameStateService = GameBeansContext.getBean(GameStateService.class); gameDataService = GameBeansContext.getBean(GameDataService.class); gameGuiService = GameBeansContext.getBean(GameGuiService.class); scriptingService = GameBeansContext.getBean(ScriptingService.class); this.enemy = enemy; this.me = gameStateService.getGameState().getCharacter(); this.setClearScreen(true); combatStatus = CombatStatus.STARTING; this.setTitle("You are fighting " + enemy.getName()); } @Override public void update() { super.update(); if (combatStatus == CombatStatus.STARTING) { gameCharacterService.refreshStats(enemy); gameCharacterService.restoreAll(enemy); updateText(); updateOptions(); combatStatus = CombatStatus.IN_PROGRESS; } else if (playerConsumedCombatAction) { // TODO: // - evaluate player's and enemy's health if (enemy.isStatsAreStale()) { gameCharacterService.refreshStats(enemy); } if (combatStatus == CombatStatus.IN_PROGRESS) { executeEnemyTurn(); } // - execute enemy turn // - evaluate player's and enemy's health // - update enemy's stats panel // - update available options, taking the // incapacitatedStateIdAndDifficulty into account updateOptions(); updateText(); playerConsumedCombatAction = false; } checkIfTired(); double enemyHealthPerc = enemy.getBaseStats().get(StatConstants.HEALTH) / enemy.getDerivates().get(StatConstants.D_MAX_HEALTH); gameGuiService .getGamePanel() .getExplorationPanel() .getRightTotemPanel() .getTotemImage() .setTargetState(enemyHealthPerc > 0 ? enemyHealthPerc : 0, 2 * TimeConstants.SECOND); } private void checkIfTired() { boolean isTired = this.me.getStamina() < 1; boolean wasTired = false; for (String conditionId : this.me.getConditions().keySet()) { if (ConditionConstanst.TIRED.equals(conditionId)) { wasTired = true; } } if (wasTired && !isTired) { this.me.getConditions().remove(ConditionConstanst.TIRED); gameGuiService.getTextPane().addInfoToBuffer( "You no longer feel tired!"); } else if (!wasTired && isTired) { Condition condition = gameDataService.getGameData().getConditions() .get(ConditionConstanst.TIRED); ConditionStatus conditionStatus = condition.makeStatus(1, -1); this.me.getConditions().put(ConditionConstanst.TIRED, conditionStatus); gameGuiService .getTextPane() .addInfoToBuffer( "You are tired, which makes it harder for you to land succesful hits and to dodge enemy attacks!"); } } private void executeEnemyTurn() { boolean specialEffectExecuted = false; if (!enemy.getSpecialAttacks().isEmpty()) { SpecialAttack specialAttack = selectSpecialAttack(enemy .getSpecialAttacks()); if (specialAttack != null) { Map<String, Object> enemyModel = scriptingService .getDefaultModel(true); scriptingService.execute(specialAttack.getEffect(), enemyModel); gameGuiService.getTextPane().addInfoToBuffer( specialAttack.getText()); specialEffectExecuted = true; } } if (!specialEffectExecuted) { PlayerCharacter defender = gameStateService.getGameState() .getCharacter(); NonPlayerCharacter attacker = gameStateService.getEnemy(); CombatUtil.performAttack(gameGuiService, defender, attacker); } } private SpecialAttack selectSpecialAttack(List<SpecialAttack> specialAttacks) { ScriptingService scriptingService = GameBeansContext .getBean(ScriptingService.class); for (SpecialAttack specialAttack : specialAttacks) { String condition = specialAttack.getCondition(); if (condition == null || scriptingService.conditionIsMet(condition)) { return specialAttack; } } return null; } private void updateOptions() { List<Option> options = this.getOptions(); this.getOptions().clear(); if (combatStatus == CombatStatus.FLED) { options.add(GoBackOption.INSTANCE); } else if (me.getHealth() <= 0 || combatStatus == CombatStatus.SURRENDERED) { // Defeat : ( List<Option> availableSubduedOptions = OptionUtil .getAvailableOptions(enemy.getSubduedOptions()); if (availableSubduedOptions.isEmpty()) { // no Subdued options, so just present the Defeated options: gameGuiService.getTextPane().appendText("You were defeated!\n"); options.addAll(enemy.getDefeatedOptions()); } else { // there are Subdued options available, present those gameGuiService.getTextPane().appendText( TextUtil.parse(enemy.getSubduedText()) + "\n"); options.addAll(enemy.getSubduedOptions()); } removeCombatOnlyConditions(); } else if (enemy.getHealth() <= 0) { // Victory! gainExperience(); List<Option> availableSubduingOptions = OptionUtil .getAvailableOptions(enemy.getSubduingOptions()); if (availableSubduingOptions.isEmpty()) { // no Subduing options, so just present the Victorious options: gameGuiService.getTextPane() .appendText("You are victorious!\n"); options.addAll(enemy.getDefeatedOptions()); } else { // there are Subduing options available, present those gameGuiService.getTextPane().appendText( TextUtil.parse(enemy.getSubduingText()) + "\n"); options.addAll(enemy.getSubduingOptions()); } removeCombatOnlyConditions(); } else if (this.incapacitatedState != null) { IncapacitatedState incapacitatedState = IncapacitatedState .valueOf(this.incapacitatedState.getFirst()); options.add(new ResistIncapacitatedStateOption(incapacitatedState, this.incapacitatedState.getSecond(), this)); } else { AttackOption attackOption = new AttackOption(); options.add(attackOption); FleeOption fleeOption = new FleeOption(); options.add(fleeOption); List<Option> availableSubduedOptions = OptionUtil .getAvailableOptions(enemy.getSubduedOptions()); if (!availableSubduedOptions.isEmpty()) { SurrenderOption surrenderOption = new SurrenderOption(); options.add(surrenderOption); } } if (me.getHealth() < 1) { me.setHealth(1); } if (me.getStamina() < 0) { me.setStamina(0); } } private void gainExperience() { int experienceGained = (int) Math.ceil(Double.valueOf(enemy.getLevel()) / Double.valueOf(me.getLevel()) * 10); playerCharacterScriptingWrapper.gainExperience(experienceGained); } private void removeCombatOnlyConditions() { Map<String, Condition> conditions = gameDataService.getGameData() .getConditions(); for (String conditionId : me.getConditions().keySet()) { Condition condition = conditions.get(conditionId); if (condition.isCombatOnly()) { me.getConditions().remove(conditionId); } } } private void updateText() { String pronoun = TextUtil.capitalPronoun(enemy.getGender()); double dHealthStatus = enemy.getBaseStats().get(StatConstants.HEALTH) / enemy.getDerivates().get(StatConstants.D_MAX_HEALTH); String healthStatus; if (dHealthStatus > 0.99) { healthStatus = "at full health"; } else if (dHealthStatus > 0.8) { healthStatus = "lightly wounded"; } else if (dHealthStatus > 0.6) { healthStatus = "wounded"; } else if (dHealthStatus > 0.3) { healthStatus = "seriously wounded"; } else if (dHealthStatus > 0.2) { healthStatus = "very badly wounded"; } else { healthStatus = "close to dying wounded"; } this.setText(enemy.getDescription() + "\n" + pronoun + " is " + healthStatus + "."); } public boolean isPlayerConsumedCombatAction() { return playerConsumedCombatAction; } public void setPlayerConsumedCombatAction(boolean playerConsumedCombatAction) { this.playerConsumedCombatAction = playerConsumedCombatAction; } public NonPlayerCharacter getEnemy() { return enemy; } public Pair<String, Integer> getIncapacitatedState() { return incapacitatedState; } public void setIncapacitatedState(Pair<String, Integer> incapaciatedState) { this.incapacitatedState = incapaciatedState; } public void setCombatStatus(CombatStatus combatStatus) { this.combatStatus = combatStatus; } }
Java
package org.clockworkmages.games.anno1186.situations.combat.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.combat.CombatSituation; import org.clockworkmages.games.anno1186.situations.combat.CombatStatus; public class SurrenderOption extends Option { private final GameStateService gameStateService; public SurrenderOption() { this.setConsumesCombatAction(true); this.setTimePassed(TimeConstants.COMBAT_TURN); gameStateService = GameBeansContext.getBean(GameStateService.class); this.setLabel("Surrender"); this.setTooltip("Surrender and put yourself at your opponent's mercy"); this.setTextAfter("You have surrendered!"); } @Override public void select() { CombatSituation combatSituation = gameStateService .getCurrentCombatSituation(); combatSituation.setCombatStatus(CombatStatus.SURRENDERED); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.combat.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.model.character.IncapacitatedState; import org.clockworkmages.games.anno1186.model.character.Stat; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.scripting.PlayerCharacterScriptingWrapper; import org.clockworkmages.games.anno1186.situations.combat.CombatSituation; public class ResistIncapacitatedStateOption extends Option { // @Injected // private GameStateService gameStateService; // @@Injected // private PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper; // private IncapacitatedState incapacitatedState; // private int difficulty; private boolean success; private CombatSituation combatSituation; public ResistIncapacitatedStateOption( IncapacitatedState incapacitatedState, int difficulty, CombatSituation combatSituation) { // this.incapacitatedState=incapacitatedState; // GameStateService gameStateService; this.combatSituation = combatSituation; GameDataService gameDataService = GameBeansContext .getBean(GameDataService.class); PlayerCharacterScriptingWrapper playerCharacterScriptingWrapper = GameBeansContext .getBean(PlayerCharacterScriptingWrapper.class); ; int chance = playerCharacterScriptingWrapper.statChance( incapacitatedState.getResistingStatId(), difficulty); Stat stat = gameDataService.getGameData().getStats() .get(incapacitatedState.getResistingStatId()); setLabel(incapacitatedState.getResistingOptionLabel() + "(" + stat.getName() + ", " + chance + "%)"); this.success = playerCharacterScriptingWrapper.statRoll( incapacitatedState.getResistingStatId(), difficulty); setTextAfter(this.success ? incapacitatedState .getResistingSuccessText() : incapacitatedState .getResistingFailureText()); setConsumesCombatAction(true); } @Override public void select() { if (success) { combatSituation.setIncapacitatedState(null); } super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.combat.options; import org.clockworkmages.games.anno1186.CombatUtil; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.option.Option; public class AttackOption extends Option { public AttackOption() { this.setLabel("Attack"); this.setConsumesCombatAction(true); this.setTimePassed(TimeConstants.COMBAT_TURN); } /* * (non-Javadoc) * * @see org.clockworkmages.games.anno1186.model.option.Option#select() */ @Override public void select() { GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); GameState gameState = gameStateService.getGameState(); GameGuiService gameGuiService = GameBeansContext .getBean(GameGuiService.class); NonPlayerCharacter defender = gameStateService.getEnemy(); PlayerCharacter attacker = gameState.getCharacter(); CombatUtil.performAttack(gameGuiService, defender, attacker); double staminaCost = attacker .getDerivateAsInt(StatConstants.D_ATTACK_STAMINA_COST); attacker.increaseBaseStat(StatConstants.STAMINA, -1 * staminaCost); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.combat.options; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.combat.CombatSituation; import org.clockworkmages.games.anno1186.situations.combat.CombatStatus; import org.clockworkmages.games.anno1186.util.RollUtil; public class FleeOption extends Option { private final boolean success; private final GameStateService gameStateService; private final GameDataService gameDataService; public FleeOption() { this.setConsumesCombatAction(true); this.setTimePassed(TimeConstants.COMBAT_TURN); gameDataService = GameBeansContext.getBean(GameDataService.class); gameStateService = GameBeansContext.getBean(GameStateService.class); GameState gameState = gameStateService.getGameState(); NonPlayerCharacter enemy = gameStateService.getEnemy(); PlayerCharacter me = gameState.getCharacter(); int chance = RollUtil.chanceBase50(me .getBaseStatAsInt(StatConstants.AGILITY) - enemy.getBaseStatAsInt(StatConstants.AGILITY)) / 2; success = RollUtil.random(100) <= chance; this.setLabel("Flee (Agility, " + chance + "%)"); if (!success) { this.setTextAfter("You don't manage to escape your enemy."); } else { this.setTextAfter("You have fled!"); } } /* * (non-Javadoc) * * @see org.clockworkmages.games.anno1186.model.option.Option#select() */ @Override public void select() { if (success) { CombatSituation combatSituation = gameStateService .getCurrentCombatSituation(); combatSituation.setCombatStatus(CombatStatus.FLED); String fleeToSituationId = combatSituation.getEnemy().getFleeTo(); if (fleeToSituationId != null) { // replace the Situation underlying the CombatSituation with the // Situation defined as fleeTo: Situation fleeToSituation = gameDataService.getGameData() .getSituations().get(fleeToSituationId); List<Situation> situationStack = gameStateService .getGameState().getSituationStack(); situationStack.remove(situationStack.size() - 2); situationStack.add(situationStack.size() - 1, fleeToSituation); } } super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Set; import org.clockworkmages.games.anno1186.SaveFilenameFilter; import org.clockworkmages.games.anno1186.gui.GameUiUtil; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.gameoptions.options.SelectLoadSlotOption; public class LoadGameSituation extends Situation { @Override public void update() { super.update(); List<Option> options = getOptions(); options.clear(); try { File gameDataDirectory = new File("."); Set<String> existingSaveFiles = new HashSet<String>(); File[] saveFiles = gameDataDirectory .listFiles(new SaveFilenameFilter()); int index = 1; for (File saveFile : saveFiles) { options.add(new SelectLoadSlotOption(index++, saveFile .getName())); } } catch (Exception e) { GameUiUtil.logError(e); throw new RuntimeException(e); } options.add(GoBackOption.INSTANCE); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.gameoptions.options.LoadGameOption; import org.clockworkmages.games.anno1186.situations.gameoptions.options.NewGameOption; import org.clockworkmages.games.anno1186.situations.gameoptions.options.QuitGameOption; public class GameMenuSituation extends Situation { public static final String ID = "ST_GAME_MENU"; public static final GameMenuSituation INSTANCE = new GameMenuSituation(); @Injected private GameStateService gameStateService; private GameMenuSituation() { super(ID); } @Override public void update() { super.update(); getOptions().clear(); if (gameStateService.getGameState().getSituationStack().size() > 1) { getOptions().add(GoBackOption.INSTANCE); } getOptions().add(new NewGameOption()); getOptions().add(new LoadGameOption()); getOptions().add(new QuitGameOption()); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions.options; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.gameoptions.GameMenuSituation; public class GameMenuOption extends Option { public static GameMenuOption INSTANCE = new GameMenuOption(); @Injected private GameStateService gameStateService; private GameMenuOption() { super("GAME_MENU"); this.setLabel("Game Menu"); } @Override public void select() { GameMenuSituation situation = GameMenuSituation.INSTANCE; gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions.options; import java.util.Calendar; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.GameTimeService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; public class NewGameOption extends Option { private GameDataService gameDataService; private GameStateService gameStateService; private GameTimeService gameTimeService; public NewGameOption() { gameDataService = GameBeansContext.getBean(GameDataService.class); gameStateService = GameBeansContext.getBean(GameStateService.class); gameTimeService = GameBeansContext.getBean(GameTimeService.class); setLabel("New Game"); } @Override public void select() { Calendar calendar = Calendar.getInstance(); calendar.set(1492, Calendar.AUGUST, 2, 22, 16); GameState gameState = new GameState(); gameState.setTime(calendar.getTimeInMillis()); gameStateService.setGameState(gameState); gameTimeService.advanceTime(1L); String startSituationId = gameDataService.getGameData() .getGameStartSituation(); Situation startSituation = gameDataService.getGameData() .getSituations().get(startSituationId); gameStateService.addSituation(startSituation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions.options; import org.clockworkmages.games.anno1186.model.option.Option; public class QuitGameOption extends Option { public QuitGameOption() { setLabel("Quit"); } @Override public void select() { System.exit(0); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.gameoptions.LoadGameSituation; public class LoadGameOption extends Option { private GameStateService gameStateService; public LoadGameOption() { gameStateService = GameBeansContext.getBean(GameStateService.class); this.setLabel("Load game"); } @Override public void select() { LoadGameSituation situation = new LoadGameSituation(); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.gameoptions.options; import java.io.File; import java.io.FileReader; import java.io.Reader; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameCharacterService; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameState; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.dao.SerializationUtil; import org.clockworkmages.games.anno1186.gui.GameUiUtil; import org.clockworkmages.games.anno1186.model.option.Option; public class SelectLoadSlotOption extends Option { private GameStateService gameStateService; private GameGuiService gameGuiService; private GameCharacterService gameCharacterService; private GameDataService gameDataService; private String fileName; public SelectLoadSlotOption(int index, String fileName) { gameDataService = GameBeansContext.getBean(GameDataService.class); gameStateService = GameBeansContext.getBean(GameStateService.class); gameGuiService = GameBeansContext.getBean(GameGuiService.class); gameCharacterService = GameBeansContext .getBean(GameCharacterService.class); setLabel("Game slot " + index); setTextAfter("Game loaded succesfully."); this.fileName = fileName; } @Override public void select() { try { File saveFile = new File("./" + fileName); Reader reader = new FileReader(saveFile); GameState gameStateFromFile = SerializationUtil.deserialize(reader, GameState.class); gameStateFromFile.getSituationStack().clear(); gameStateService.setGameState(gameStateFromFile); gameCharacterService.refreshStats(gameStateFromFile.getCharacter()); } catch (Exception e) { GameUiUtil.logError(e); throw new RuntimeException(e); } super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.sexsettings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameData; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.Fetish; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.sexsettings.options.EnableDisableSexSettingOption; public class SexSettingsSituation extends Situation { private GameStateService gameStateService; private GameDataService gameDataService; public SexSettingsSituation() { super("ST_SEXSETTINGS"); setTitle("SexSettings!"); setClearScreen(true); gameStateService = GameBeansContext.getBean(GameStateService.class); gameDataService = GameBeansContext.getBean(GameDataService.class); } @Override public void update() { super.update(); GameData gameData = gameDataService.getGameData(); Set<String> enabledFetishes = gameStateService.getGameState() .getFetishesEnabled(); String text = " This is where you can select your sexual preferences and fetishes!\n" + " {f:b}By default, all sexual preferences are disabled{f} so as not to bombard the users with filth and perversion unless they want to be bombarded with it. " + "Nevertheless, sex is an important part of this game and activating additional preferences will unlock many additional dialogue options and random events.\n" + " Even with all sex options disabled the game is still playable and fun, but don't be surprised if you'll go visit a brothel run by mermaids, demonesses and harpies and the only dialogue option you'll get inside will be 'Uh, nice weather, isn't it?'. On the other hand, with 'Sex with women', 'Mythical creatures' and 'Submission' options enabled, things will likely get much more interesting.\n" + // "\n" + // "You currently have " + (enabledFetishes.isEmpty() ? "no fetishes enabled." : "the following fetishes enabled:\n\n"); List<String> lsEnabledFetishes = new ArrayList<String>(enabledFetishes); Collections.sort(lsEnabledFetishes); for (String fetishId : enabledFetishes) { Fetish fetish = gameData.getFetishes().get(fetishId); text += fetish.getName() + "\n"; } setText(text); List<Option> options = getOptions(); options.clear(); options.add(GoBackOption.INSTANCE); List<Fetish> fetishes = new ArrayList<Fetish>(gameData.getFetishes() .values()); Collections.sort(fetishes); for (Fetish fetish : fetishes) { boolean isEnabled = enabledFetishes.contains(fetish.getId()); options.add(new EnableDisableSexSettingOption(fetish, isEnabled)); } options.add(GoBackOption.INSTANCE); } }
Java
package org.clockworkmages.games.anno1186.situations.sexsettings.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.sexsettings.SexSettingsSituation; public class SexSettingsOption extends Option { public static SexSettingsOption INSTANCE = new SexSettingsOption(); private SexSettingsOption() { super("SEXSETTINGS"); this.setLabel("Sex settings"); } @Override public void select() { SexSettingsSituation situation = new SexSettingsSituation(); GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.sexsettings.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.Fetish; import org.clockworkmages.games.anno1186.model.option.Option; public class EnableDisableSexSettingOption extends Option { private boolean isEnabled; private GameStateService gameStateService; private Fetish fetish; public EnableDisableSexSettingOption(Fetish fetish, boolean isEnabled) { this.isEnabled = isEnabled; this.fetish = fetish; this.setLabel(fetish.getName() + " (" + (isEnabled ? "Enabled, select to disable" : "Disabled, select to enable") + ")"); this.setTooltip(fetish.getDescription()); this.setTextAfter("'" + fetish.getName() + "' " + (isEnabled ? "disabled" : "enabled")); gameStateService = GameBeansContext.getBean(GameStateService.class); } public void select() { if (isEnabled) { // disable: gameStateService.getGameState().getFetishesEnabled() .remove(fetish.getId()); } else { // enable gameStateService.getGameState().getFetishesEnabled() .add(fetish.getId()); } super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.status; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; public class CharacterStatusSituation extends Situation { public CharacterStatusSituation() { super("ST_STATUS"); setTitle("Character Status"); } @Override public void update() { super.update(); GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); PlayerCharacter playerCharacter = gameStateService.getGameState() .getCharacter(); List<Option> options = getOptions(); options.clear(); options.add(GoBackOption.INSTANCE); String text = ""; setText(text); } }
Java
package org.clockworkmages.games.anno1186.situations.status.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.inventory.InventorySituation; public class CharacterStatusOption extends Option { public static CharacterStatusOption INSTANCE = new CharacterStatusOption(); private CharacterStatusOption() { super("CHARACTER STATUS"); this.setLabel("Status"); } @Override public void select() { InventorySituation situation = new InventorySituation(); GameStateService gameStateService = GameBeansContext .getBean(GameStateService.class); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.camp; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Set; import org.clockworkmages.games.anno1186.SaveFilenameFilter; import org.clockworkmages.games.anno1186.gui.GameUiUtil; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.camp.options.SelectSaveSlotOption; public class SaveGameSituation extends Situation { @Override public void update() { super.update(); List<Option> options = getOptions(); options.clear(); try { File gameDataDirectory = new File("."); Set<String> existingSaveFiles = new HashSet<String>(); File[] saveFiles = gameDataDirectory .listFiles(new SaveFilenameFilter()); for (File saveFile : saveFiles) { existingSaveFiles.add(saveFile.getName()); } for (int i = 1; i < 7; i++) { String saveFileName = "save" + i + ".xml"; boolean overwrite = existingSaveFiles.contains(saveFileName); options.add(new SelectSaveSlotOption(i, saveFileName, overwrite)); } } catch (Exception e) { GameUiUtil.logError(e); throw new RuntimeException(e); } options.add(GoBackOption.INSTANCE); } }
Java
package org.clockworkmages.games.anno1186.situations.camp.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.camp.CampSituation; public class CampOption extends Option { private String campId; private GameStateService gameStateService; public CampOption(String campId) { gameStateService = GameBeansContext.getBean(GameStateService.class); this.campId = campId; this.setLabel("Go to your camp."); } @Override public void select() { CampSituation situation = new CampSituation(); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.camp.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.situations.camp.SaveGameSituation; public class SaveGameOption extends Option { private GameStateService gameStateService; public SaveGameOption() { gameStateService = GameBeansContext.getBean(GameStateService.class); this.setLabel("Save game"); } @Override public void select() { SaveGameSituation situation = new SaveGameSituation(); gameStateService.addSituation(situation, true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.camp.options; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameGuiService; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.dao.FileUtil; import org.clockworkmages.games.anno1186.dao.SerializationUtil; import org.clockworkmages.games.anno1186.model.option.Option; public class SelectSaveSlotOption extends Option { private GameStateService gameStateService; private GameGuiService gameGuiService; private String fileName; public SelectSaveSlotOption(int index, String fileName, boolean overwrite) { gameStateService = GameBeansContext.getBean(GameStateService.class); gameGuiService = GameBeansContext.getBean(GameGuiService.class); setLabel("Save slot " + index + " (" + (overwrite ? "overwrite" : "empty") + ""); this.fileName = fileName; } @Override public void select() { String gameStateSerialized = SerializationUtil.serialize( gameStateService.getGameState(), true); FileUtil.write("./" + this.fileName, gameStateSerialized); gameGuiService.addInfo("Games saved succesfully as '" + this.fileName + "'"); this.setGoBack(true); super.select(); } }
Java
package org.clockworkmages.games.anno1186.situations.camp; import java.util.List; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameStateService; import org.clockworkmages.games.anno1186.Injected; import org.clockworkmages.games.anno1186.model.character.PlayerCharacter; import org.clockworkmages.games.anno1186.model.option.GoBackOption; import org.clockworkmages.games.anno1186.model.option.Option; import org.clockworkmages.games.anno1186.model.situation.Situation; import org.clockworkmages.games.anno1186.situations.camp.options.SaveGameOption; import org.clockworkmages.games.anno1186.util.MathUtil; public class CampSituation extends Situation { @Injected private GameStateService gameStateService; public CampSituation() { super(); GameBeansContext.processInjectAnnotations(this); } @Override public void update() { super.update(); PlayerCharacter playerCharacter = gameStateService.getGameState() .getCharacter(); List<Option> options = getOptions(); options.clear(); int experienceNeededToLevelUp = MathUtil .experienceNeededToLevelUp(playerCharacter.getLevel()); // TODO // if (playerCharacter.getExperience() > experienceNeededToLevelUp) { // options.add(new LevelUpOption()); // } options.add(new SaveGameOption()); options.add(GoBackOption.INSTANCE); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package ch.dissem.android.drupal; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package org.xmlrpc.android; public class Tag { static final String LOG = "XMLRPC"; static final String METHOD_CALL = "methodCall"; static final String METHOD_NAME = "methodName"; static final String METHOD_RESPONSE = "methodResponse"; static final String PARAMS = "params"; static final String PARAM = "param"; static final String FAULT = "fault"; static final String FAULT_CODE = "faultCode"; static final String FAULT_STRING = "faultString"; }
Java
package org.xmlrpc.android; import android.annotation.SuppressLint; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; class XMLRPCSerializer implements IXMLRPCSerializer { @SuppressLint("SimpleDateFormat") static SimpleDateFormat dateFormat = new SimpleDateFormat(DATETIME_FORMAT); @SuppressWarnings("unchecked") public void serialize(XmlSerializer serializer, Object object) throws IOException { // check for scalar types: if (object instanceof Integer || object instanceof Short || object instanceof Byte) { serializer.startTag(null, TYPE_I4).text(object.toString()) .endTag(null, TYPE_I4); } else if (object instanceof Long) { serializer.startTag(null, TYPE_I8).text(object.toString()) .endTag(null, TYPE_I8); } else if (object instanceof Double || object instanceof Float) { serializer.startTag(null, TYPE_DOUBLE).text(object.toString()) .endTag(null, TYPE_DOUBLE); } else if (object instanceof Boolean) { Boolean bool = (Boolean) object; String boolStr = bool.booleanValue() ? "1" : "0"; serializer.startTag(null, TYPE_BOOLEAN).text(boolStr) .endTag(null, TYPE_BOOLEAN); } else if (object instanceof String) { serializer.startTag(null, TYPE_STRING).text(object.toString()) .endTag(null, TYPE_STRING); } else if (object instanceof Date || object instanceof Calendar) { String dateStr = dateFormat.format(object); serializer.startTag(null, TYPE_DATE_TIME_ISO8601).text(dateStr) .endTag(null, TYPE_DATE_TIME_ISO8601); } else if (object instanceof byte[]) { String value = new String(Base64Coder.encode((byte[]) object)); serializer.startTag(null, TYPE_BASE64).text(value) .endTag(null, TYPE_BASE64); } else if (object instanceof List) { serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA); List<Object> list = (List<Object>) object; Iterator<Object> iter = list.iterator(); while (iter.hasNext()) { Object o = iter.next(); serializer.startTag(null, TAG_VALUE); serialize(serializer, o); serializer.endTag(null, TAG_VALUE); } serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY); } else if (object instanceof Object[]) { serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA); Object[] objects = (Object[]) object; for (int i = 0; i < objects.length; i++) { Object o = objects[i]; serializer.startTag(null, TAG_VALUE); serialize(serializer, o); serializer.endTag(null, TAG_VALUE); } serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY); } else if (object instanceof Map) { serializer.startTag(null, TYPE_STRUCT); Map<String, Object> map = (Map<String, Object>) object; Iterator<Entry<String, Object>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Object> entry = iter.next(); String key = entry.getKey(); Object value = entry.getValue(); serializer.startTag(null, TAG_MEMBER); serializer.startTag(null, TAG_NAME).text(key) .endTag(null, TAG_NAME); serializer.startTag(null, TAG_VALUE); serialize(serializer, value); serializer.endTag(null, TAG_VALUE); serializer.endTag(null, TAG_MEMBER); } serializer.endTag(null, TYPE_STRUCT); } else if (object instanceof XMLRPCSerializable) { XMLRPCSerializable serializable = (XMLRPCSerializable) object; serialize(serializer, serializable.getSerializable()); } else { throw new IOException("Cannot serialize " + object); } } public Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, null, TAG_VALUE); if (parser.isEmptyElementTag()) { // degenerated <value />, return empty string return ""; } Object obj; boolean hasType = true; String typeNodeName = null; try { parser.nextTag(); typeNodeName = parser.getName(); if (typeNodeName.equals(TAG_VALUE) && parser.getEventType() == XmlPullParser.END_TAG) { // empty <value></value>, return empty string return ""; } } catch (XmlPullParserException e) { hasType = false; } if (hasType) { if (typeNodeName.equals(TYPE_INT) || typeNodeName.equals(TYPE_I4)) { String value = parser.nextText(); obj = Integer.parseInt(value); } else if (typeNodeName.equals(TYPE_I8)) { String value = parser.nextText(); obj = Long.parseLong(value); } else if (typeNodeName.equals(TYPE_DOUBLE)) { String value = parser.nextText(); obj = Double.parseDouble(value); } else if (typeNodeName.equals(TYPE_BOOLEAN)) { String value = parser.nextText(); obj = value.equals("1") ? Boolean.TRUE : Boolean.FALSE; } else if (typeNodeName.equals(TYPE_STRING)) { obj = parser.nextText(); } else if (typeNodeName.equals(TYPE_DATE_TIME_ISO8601)) { String value = parser.nextText(); try { obj = dateFormat.parseObject(value); } catch (ParseException e) { throw new IOException("Cannot deserialize dateTime " + value); } } else if (typeNodeName.equals(TYPE_BASE64)) { String value = parser.nextText(); BufferedReader reader = new BufferedReader(new StringReader( value)); String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line); } obj = Base64Coder.decode(sb.toString()); } else if (typeNodeName.equals(TYPE_ARRAY)) { parser.nextTag(); // TAG_DATA (<data>) parser.require(XmlPullParser.START_TAG, null, TAG_DATA); parser.nextTag(); List<Object> list = new ArrayList<Object>(); while (parser.getName().equals(TAG_VALUE)) { list.add(deserialize(parser)); parser.nextTag(); } parser.require(XmlPullParser.END_TAG, null, TAG_DATA); parser.nextTag(); // TAG_ARRAY (</array>) parser.require(XmlPullParser.END_TAG, null, TYPE_ARRAY); obj = list.toArray(); } else if (typeNodeName.equals(TYPE_STRUCT)) { parser.nextTag(); Map<String, Object> map = new HashMap<String, Object>(); while (parser.getName().equals(TAG_MEMBER)) { String memberName = null; Object memberValue = null; while (true) { parser.nextTag(); String name = parser.getName(); if (name.equals(TAG_NAME)) { memberName = parser.nextText(); } else if (name.equals(TAG_VALUE)) { memberValue = deserialize(parser); } else { break; } } if (memberName != null && memberValue != null) { map.put(memberName, memberValue); } parser.require(XmlPullParser.END_TAG, null, TAG_MEMBER); parser.nextTag(); } parser.require(XmlPullParser.END_TAG, null, TYPE_STRUCT); obj = map; } else { throw new IOException("Cannot deserialize " + parser.getName()); } } else { // TYPE_STRING (<string>) is not required obj = parser.getText(); } parser.nextTag(); // TAG_VALUE (</value>) parser.require(XmlPullParser.END_TAG, null, TAG_VALUE); return obj; } }
Java
package org.xmlrpc.android; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in * RFC 1521. * * <p> * This is "Open Source" software and released under the <a * href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> */ class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i = 0; for (char c = 'A'; c <= 'Z'; c++) { map1[i++] = c; } for (char c = 'a'; c <= 'z'; c++) { map1[i++] = c; } for (char c = '0'; c <= '9'; c++) { map1[i++] = c; } map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i = 0; i < map2.length; i++) { map2[i] = -1; } for (int i = 0; i < 64; i++) { map2[map1[i]] = (byte) i; } } /** * Encodes a string into Base64 format. No blanks or line breaks are * inserted. * * @param s * a String to be encoded. * @return A String with the Base64 encoded data. */ static String encodeString(String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted. * * @param in * an array containing the data bytes to be encoded. * @return A character array with the Base64 encoded data. */ static char[] encode(byte[] in) { return encode(in, in.length); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted. * * @param in * an array containing the data bytes to be encoded. * @param iLen * number of bytes to process in <code>in</code>. * @return A character array with the Base64 encoded data. */ static char[] encode(byte[] in, int iLen) { int oDataLen = (iLen * 4 + 2) / 3; // output length without padding int oLen = ((iLen + 2) / 3) * 4; // output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * * @param s * a Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException * if the input is not valid Base64 encoded data. */ static String decodeString(String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format. * * @param s * a Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException * if the input is not valid Base64 encoded data. */ static byte[] decode(String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. No blanks or line breaks are * allowed within the Base64 encoded data. * * @param in * a character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException * if the input is not valid Base64 encoded data. */ static byte[] decode(char[] in) { int iLen = in.length; if (iLen % 4 != 0) { throw new IllegalArgumentException( "Length of Base64 encoded input string is not a multiple of 4."); } while (iLen > 0 && in[iLen - 1] == '=') { iLen--; } int oLen = (iLen * 3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) { throw new IllegalArgumentException( "Illegal character in Base64 encoded data."); } int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) { throw new IllegalArgumentException( "Illegal character in Base64 encoded data."); } int o0 = (b0 << 2) | (b1 >>> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); int o2 = ((b2 & 3) << 6) | b3; out[op++] = (byte) o0; if (op < oLen) { out[op++] = (byte) o1; } if (op < oLen) { out[op++] = (byte) o2; } } return out; } // Dummy constructor. private Base64Coder() { } }
Java
package org.xmlrpc.android; public class XMLRPCFault extends XMLRPCException { /** * */ private static final long serialVersionUID = 5676562456612956519L; private String faultString; private int faultCode; public XMLRPCFault(String faultString, int faultCode) { super("XMLRPC Fault: " + faultString + " [code " + faultCode + "]"); this.faultString = faultString; this.faultCode = faultCode; } public String getFaultString() { return faultString; } public int getFaultCode() { return faultCode; } }
Java
package org.xmlrpc.android; /** * Allows to pass any XMLRPCSerializable object as input parameter. * When implementing getSerializable() you should return * one of XMLRPC primitive types (or another XMLRPCSerializable: be careful not going into * recursion by passing this object reference!) */ public interface XMLRPCSerializable { /** * Gets XMLRPC serialization object * @return object to serialize This object is most likely one of XMLRPC primitive types, * however you can return also another XMLRPCSerializable */ Object getSerializable(); }
Java
package org.xmlrpc.android; public class XMLRPCException extends Exception { /** * */ private static final long serialVersionUID = 7499675036625522379L; public XMLRPCException(Exception e) { super(e); } public XMLRPCException(String string) { super(string); } }
Java
package org.xmlrpc.android; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; public interface IXMLRPCSerializer { String TAG_NAME = "name"; String TAG_MEMBER = "member"; String TAG_VALUE = "value"; String TAG_DATA = "data"; String TYPE_INT = "int"; String TYPE_I4 = "i4"; String TYPE_I8 = "i8"; String TYPE_DOUBLE = "double"; String TYPE_BOOLEAN = "boolean"; String TYPE_STRING = "string"; String TYPE_DATE_TIME_ISO8601 = "dateTime.iso8601"; String TYPE_BASE64 = "base64"; String TYPE_ARRAY = "array"; String TYPE_STRUCT = "struct"; String DATETIME_FORMAT = "yyyyMMdd'T'HH:mm:ss"; void serialize(XmlSerializer serializer, Object object) throws IOException; Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException; }
Java
package org.xmlrpc.android; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.net.URI; import java.net.URL; import java.util.Map; import java.util.Scanner; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log; /** * XMLRPCClient allows to call remote XMLRPC method. * * <p> * The following table shows how XML-RPC types are mapped to java call * parameters/response values. * </p> * * <p> * <table border="2" align="center" cellpadding="5"> * <thead> * <tr> * <th>XML-RPC Type</th> * <th>Call Parameters</th> * <th>Call Response</th> * </tr> * </thead> * * <tbody> * <td>int, i4</td> * <td>byte<br /> * Byte<br /> * short<br /> * Short<br /> * int<br /> * Integer</td> * <td>int<br /> * Integer</td> * </tr> * <tr> * <td>i8</td> * <td>long<br /> * Long</td> * <td>long<br /> * Long</td> * </tr> * <tr> * <td>double</td> * <td>float<br /> * Float<br /> * double<br /> * Double</td> * <td>double<br /> * Double</td> * </tr> * <tr> * <td>string</td> * <td>String</td> * <td>String</td> * </tr> * <tr> * <td>boolean</td> * <td>boolean<br /> * Boolean</td> * <td>boolean<br /> * Boolean</td> * </tr> * <tr> * <td>dateTime.iso8601</td> * <td>java.util.Date<br /> * java.util.Calendar</td> * <td>java.util.Date</td> * </tr> * <tr> * <td>base64</td> * <td>byte[]</td> * <td>byte[]</td> * </tr> * <tr> * <td>array</td> * <td>java.util.List&lt;Object&gt;<br /> * Object[]</td> * <td>Object[]</td> * </tr> * <tr> * <td>struct</td> * <td>java.util.Map&lt;String, Object&gt;</td> * <td>java.util.Map&lt;String, Object&gt;</td> * </tr> * </tbody> * </table> * </p> * <p> * You can also pass as a parameter any object implementing XMLRPCSerializable * interface. In this case your object overrides getSerializable() telling how * to serialize to XMLRPC protocol * </p> */ public class XMLRPCClient extends XMLRPCCommon { private HttpClient client; private HttpPost postMethod; private HttpParams httpParams; /** * XMLRPCClient constructor. Creates new instance based on server URI * * @param XMLRPC * server URI */ public XMLRPCClient(URI uri) { postMethod = new HttpPost(uri); postMethod.addHeader("Content-Type", "text/xml"); // WARNING // I had to disable "Expect: 100-Continue" header since I had // two second delay between sending http POST request and POST body httpParams = postMethod.getParams(); HttpProtocolParams.setUseExpectContinue(httpParams, false); client = new DefaultHttpClient(); } /** * Convenience constructor. Creates new instance based on server String * address * * @param XMLRPC * server address */ public XMLRPCClient(String url) { this(URI.create(url)); } /** * Convenience XMLRPCClient constructor. Creates new instance based on * server URL * * @param XMLRPC * server URL */ public XMLRPCClient(URL url) { this(URI.create(url.toExternalForm())); } /** * Convenience constructor. Creates new instance based on server String * address * * @param XMLRPC * server address * @param HTTP * Server - Basic Authentication - Username * @param HTTP * Server - Basic Authentication - Password */ public XMLRPCClient(URI uri, String username, String password) { this(uri); ((DefaultHttpClient) client).getCredentialsProvider() .setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); } /** * Convenience constructor. Creates new instance based on server String * address * * @param XMLRPC * server address * @param HTTP * Server - Basic Authentication - Username * @param HTTP * Server - Basic Authentication - Password */ public XMLRPCClient(String url, String username, String password) { this(URI.create(url), username, password); } /** * Convenience constructor. Creates new instance based on server String * address * * @param XMLRPC * server url * @param HTTP * Server - Basic Authentication - Username * @param HTTP * Server - Basic Authentication - Password */ public XMLRPCClient(URL url, String username, String password) { this(URI.create(url.toExternalForm()), username, password); } /** * Sets basic authentication on web request using plain credentials * * @param username * The plain text username * @param password * The plain text password */ public void setBasicAuthentication(String username, String password) { ((DefaultHttpClient) client).getCredentialsProvider().setCredentials( new AuthScope(postMethod.getURI().getHost(), postMethod .getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); } /** * Call method with optional parameters. This is general method. If you want * to call your method with 0-8 parameters, you can use more convenience * call() methods * * @param method * name of method to call * @param params * parameters to pass to method (may be null if method has no * parameters) * @return deserialized method return value * @throws XMLRPCException */ @SuppressWarnings("unchecked") public Object callEx(String method, Object[] params) throws XMLRPCException { try { // prepare POST body String body = methodCall(method, params); // set POST body HttpEntity entity = new StringEntity(body); postMethod.setEntity(entity); // Log.d(Tag.LOG, "ros HTTP POST"); // execute HTTP POST request HttpResponse response = client.execute(postMethod); // Log.d(Tag.LOG, "ros HTTP POSTed"); // check status code int statusCode = response.getStatusLine().getStatusCode(); // Log.d(Tag.LOG, "ros status code:" + statusCode); if (statusCode != HttpStatus.SC_OK) { if (Log.isLoggable("xmlrpc", Log.DEBUG)) { HttpEntity he = response.getEntity(); Scanner scn = new Scanner(he.getContent()); while (scn.hasNext()) Log.d("xmlrpc", scn.nextLine()); } throw new XMLRPCException("HTTP status code: " + statusCode + ", but expected " + HttpStatus.SC_OK); } // parse response stuff // // setup pull parser XmlPullParser pullParser = XmlPullParserFactory.newInstance() .newPullParser(); entity = response.getEntity(); Reader reader = new InputStreamReader(new BufferedInputStream( entity.getContent())); // for testing purposes only // reader = new // StringReader("<?xml version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>"); pullParser.setInput(reader); // lets start pulling... pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE); pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT // (<fault>) String tag = pullParser.getName(); if (tag.equals(Tag.PARAMS)) { // normal response pullParser.nextTag(); // Tag.PARAM (<param>) pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM); pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in // XMLRPCSerializer.deserialize() below // deserialize result Object obj = iXMLRPCSerializer.deserialize(pullParser); entity.consumeContent(); return obj; } else if (tag.equals(Tag.FAULT)) { // fault response pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in // XMLRPCSerializer.deserialize() below // deserialize fault result Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer .deserialize(pullParser); String faultString = (String) map.get(Tag.FAULT_STRING); int faultCode = (Integer) map.get(Tag.FAULT_CODE); entity.consumeContent(); throw new XMLRPCFault(faultString, faultCode); } else { entity.consumeContent(); throw new XMLRPCException("Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>"); } } catch (XMLRPCException e) { // catch & propagate XMLRPCException/XMLRPCFault throw e; } catch (Exception e) { e.printStackTrace(); // wrap any other Exception(s) around XMLRPCException throw new XMLRPCException(e); } } private String methodCall(String method, Object[] params) throws IllegalArgumentException, IllegalStateException, IOException { StringWriter bodyWriter = new StringWriter(); serializer.setOutput(bodyWriter); serializer.startDocument(null, null); serializer.startTag(null, Tag.METHOD_CALL); // set method name serializer.startTag(null, Tag.METHOD_NAME).text(method) .endTag(null, Tag.METHOD_NAME); serializeParams(params); serializer.endTag(null, Tag.METHOD_CALL); serializer.endDocument(); return bodyWriter.toString(); } /** * Convenience method call with no parameters * * @param method * name of method to call * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method) throws XMLRPCException { return callEx(method, null); } /** * Convenience method call with one parameter * * @param method * name of method to call * @param p0 * method's parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0) throws XMLRPCException { Object[] params = { p0, }; return callEx(method, params); } /** * Convenience method call with two parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1) throws XMLRPCException { Object[] params = { p0, p1, }; return callEx(method, params); } /** * Convenience method call with three parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2) throws XMLRPCException { Object[] params = { p0, p1, p2, }; return callEx(method, params); } /** * Convenience method call with four parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @param p3 * method's 4th parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2, Object p3) throws XMLRPCException { Object[] params = { p0, p1, p2, p3, }; return callEx(method, params); } /** * Convenience method call with five parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @param p3 * method's 4th parameter * @param p4 * method's 5th parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4) throws XMLRPCException { Object[] params = { p0, p1, p2, p3, p4, }; return callEx(method, params); } /** * Convenience method call with six parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @param p3 * method's 4th parameter * @param p4 * method's 5th parameter * @param p5 * method's 6th parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) throws XMLRPCException { Object[] params = { p0, p1, p2, p3, p4, p5, }; return callEx(method, params); } /** * Convenience method call with seven parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @param p3 * method's 4th parameter * @param p4 * method's 5th parameter * @param p5 * method's 6th parameter * @param p6 * method's 7th parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) throws XMLRPCException { Object[] params = { p0, p1, p2, p3, p4, p5, p6, }; return callEx(method, params); } /** * Convenience method call with eight parameters * * @param method * name of method to call * @param p0 * method's 1st parameter * @param p1 * method's 2nd parameter * @param p2 * method's 3rd parameter * @param p3 * method's 4th parameter * @param p4 * method's 5th parameter * @param p5 * method's 6th parameter * @param p6 * method's 7th parameter * @param p7 * method's 8th parameter * @return deserialized method return value * @throws XMLRPCException */ public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) throws XMLRPCException { Object[] params = { p0, p1, p2, p3, p4, p5, p6, p7, }; return callEx(method, params); } }
Java
package org.xmlrpc.android; import java.io.IOException; import org.xmlpull.v1.XmlSerializer; import android.util.Xml; class XMLRPCCommon { protected XmlSerializer serializer; protected IXMLRPCSerializer iXMLRPCSerializer; XMLRPCCommon() { serializer = Xml.newSerializer(); iXMLRPCSerializer = new XMLRPCSerializer(); } /** * Sets custom IXMLRPCSerializer serializer (in case when server doesn't support * standard XMLRPC protocol) * * @param serializer custom serializer */ public void setSerializer(IXMLRPCSerializer serializer) { iXMLRPCSerializer = serializer; } protected void serializeParams(Object[] params) throws IllegalArgumentException, IllegalStateException, IOException { if (params != null && params.length != 0) { // set method params serializer.startTag(null, Tag.PARAMS); for (int i=0; i<params.length; i++) { serializer.startTag(null, Tag.PARAM).startTag(null, IXMLRPCSerializer.TAG_VALUE); iXMLRPCSerializer.serialize(serializer, params[i]); serializer.endTag(null, IXMLRPCSerializer.TAG_VALUE).endTag(null, Tag.PARAM); } serializer.endTag(null, Tag.PARAMS); } } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import android.os.Parcel; import android.os.Parcelable; public class Tag implements Parcelable { private Integer id; private String startTag; private String defaultText; private String endTag; public Tag() { // Default constructor } public Tag(String startTag, String defaultText, String endTag) { this.startTag = startTag; this.defaultText = defaultText; this.endTag = endTag; } public String getStartTag() { return startTag; } public void setStartTag(String startTag) { this.startTag = startTag; } public String getDefaultText() { return defaultText; } public void setDefaultText(String defaultText) { this.defaultText = defaultText; } public String getEndTag() { return endTag; } public void setEndTag(String endTag) { this.endTag = endTag; } Integer getId() { return id; } void setId(int id) { this.id = id; } @Override public String toString() { return startTag; } // Parcelable implementation private Tag(Parcel in) { if (in.readByte() == 1) id = in.readInt(); startTag = in.readString(); if (in.readByte() == 1) defaultText = in.readString(); endTag = in.readString(); } public static final Parcelable.Creator<Tag> CREATOR = new Parcelable.Creator<Tag>() { public Tag createFromParcel(Parcel in) { return new Tag(in); } public Tag[] newArray(int size) { return new Tag[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { if (id != null) { out.writeByte((byte) 1); out.writeInt(id); } else { out.writeByte((byte) 0); } out.writeString(startTag); if (id != null) { out.writeByte((byte) 1); out.writeString(defaultText); } else { out.writeByte((byte) 0); } out.writeString(endTag); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + startTag.hashCode(); result = prime * result + defaultText.hashCode(); result = prime * result + endTag.hashCode(); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof Tag)) return false; Tag other = (Tag) obj; if (!stringEqual(startTag, other.startTag)) return false; if (!stringEqual(defaultText, other.defaultText)) return false; if (!stringEqual(endTag, other.endTag)) return false; return true; } private static boolean stringEqual(String a, String b) { if (a == null) return b == null; return a.equals(b); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import static android.provider.BaseColumns._ID; import java.util.ArrayList; import java.util.List; import ch.dissem.android.drupal.model.Site.SignaturePosition; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DAO extends SQLiteOpenHelper { public static String DATABASE_NAME = "drupaleditor.db"; public static int DATABASE_VERSION = 2; // Sites table public static String SITES_TABLE_NAME = "sites"; public static final String NAME = "name"; public static final String URL = "url"; public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String SIGNATURE = "signature"; public static final String SIGNATURE_ENABLED = "signature_on"; public static final String SIGNATURE_POSITION = "signature_position"; // Tags table public static String TAGS_TABLE_NAME = "tags"; public static final String START_TAG = "startTag"; public static final String DEFAULT_TEXT = "defaultText"; public static final String END_TAG = "endTag"; public DAO(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // create sites table db.execSQL("CREATE TABLE " + SITES_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " TEXT, " + URL + " TEXT, " + USERNAME + " TEXT, " + PASSWORD + " TEXT, " + SIGNATURE + " TEXT, " + SIGNATURE_ENABLED + " TEXT, " + SIGNATURE_POSITION + " TEXT);"); // create tags table db.execSQL("CREATE TABLE " + TAGS_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + START_TAG + " TEXT, " + DEFAULT_TEXT + " TEXT, " + END_TAG + " TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 2) { db.execSQL("CREATE TABLE " + TAGS_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + START_TAG + " TEXT, " + DEFAULT_TEXT + " TEXT, " + END_TAG + " TEXT);"); } // FIXME: Remember to change that if DB changes! // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); } public void save(Site site) { SQLiteDatabase db = getWritableDatabase(); try { ContentValues values = new ContentValues(); values.put(NAME, site.getName()); values.put(URL, site.getUrl()); values.put(USERNAME, site.getUsername()); values.put(PASSWORD, site.getPassword()); values.put(SIGNATURE, site.getSignature()); values.put(SIGNATURE_ENABLED, String.valueOf(site .isSignatureEnabled())); Site.SignaturePosition pos = site.getSignaturePosition(); values.put(SIGNATURE_POSITION, pos == null ? null : pos.toString()); if (site.getId() != null) { // update db.update(SITES_TABLE_NAME, values, _ID + "=" + site.getId(), null); } else { // save db.insertOrThrow(SITES_TABLE_NAME, null, values); } } finally { db.close(); } } public void save(Tag tag) { SQLiteDatabase db = getWritableDatabase(); try { ContentValues values = new ContentValues(); values.put(START_TAG, tag.getStartTag()); values.put(DEFAULT_TEXT, tag.getDefaultText()); values.put(END_TAG, tag.getEndTag()); if (tag.getId() != null) { // update db.update(TAGS_TABLE_NAME, values, _ID + "=" + tag.getId(), null); } else { // save db.insertOrThrow(TAGS_TABLE_NAME, null, values); } } finally { db.close(); } } public void delete(Site site) { SQLiteDatabase db = getWritableDatabase(); try { db.delete(SITES_TABLE_NAME, _ID + "=" + site.getId(), null); } finally { db.close(); } } public void delete(Tag tag) { SQLiteDatabase db = getWritableDatabase(); try { db.delete(TAGS_TABLE_NAME, _ID + "=" + tag.getId(), null); } finally { db.close(); } } public List<Site> getSites() { SQLiteDatabase db = getReadableDatabase(); try { Cursor c = db.query(SITES_TABLE_NAME, null, null, null, null, null, null); List<Site> list = new ArrayList<Site>(c.getColumnCount()); while (c.moveToNext()) { Site s = new Site(); s.setId(c.getInt(0)); s.setName(c.getString(1)); s.setUrl(c.getString(2)); s.setUsername(c.getString(3)); s.setPassword(c.getString(4)); s.setSignature(c.getString(5)); s.setSignatureEnabled(Boolean.parseBoolean(c.getString(6))); s.setSignaturePosition(SignaturePosition.parse(c.getString(7))); list.add(s); } c.close(); return list; } finally { db.close(); } } public List<Tag> getTags() { SQLiteDatabase db = getReadableDatabase(); try { Cursor c = db.query(TAGS_TABLE_NAME, null, null, null, null, null, START_TAG); List<Tag> list = new ArrayList<Tag>(c.getColumnCount()); while (c.moveToNext()) { Tag t = new Tag(); t.setId(c.getInt(0)); t.setStartTag(c.getString(1)); t.setDefaultText(c.getString(2)); t.setEndTag(c.getString(3)); list.add(t); } c.close(); return list; } finally { db.close(); } } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.xmlrpc.android.XMLRPCClient; import org.xmlrpc.android.XMLRPCException; import org.xmlrpc.android.XMLRPCFault; import android.app.AlertDialog.Builder; import android.content.Context; import android.os.Handler; import android.util.Log; import android.widget.Toast; import ch.dissem.android.drupal.R; import ch.dissem.android.drupal.Settings; import ch.dissem.android.utils.ThreadingUtils; public class WDAO { public static final String BLOGGER_API_KEY = "0123456789ABCDEF"; private Map<String, List<CategoryInfo>> categoryInfo; private Map<String, Lock> categoryInfoPreloadLocks = new HashMap<String, Lock>(); private Context ctx; private Handler handler; public WDAO(Context context) { ctx = context; handler = new Handler(); categoryInfo = new HashMap<String, List<CategoryInfo>>(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public Post[] getPosts(String blogid) { try { XMLRPCClient client = new XMLRPCClient(Settings.getURI()); Object[] results = (Object[]) client.call( "metaWeblog.getRecentPosts", blogid, // Settings.getUserName(), // Settings.getPassword(), // Settings.getHistorySize(ctx)); final Post[] posts = new Post[results.length]; for (int i = 0; i < results.length; i++) { posts[i] = new Post((Map) results[i]); } return posts; } catch (XMLRPCException e) { handleException(e, "Could not get post categories"); } return new Post[0]; } public void updateContent(Post post) { try { XMLRPCClient client = new XMLRPCClient(Settings.getURI()); @SuppressWarnings("unchecked") Map<String, Object> results = (Map<String, Object>) client.call( "metaWeblog.getPost", post.getPostid(), // Settings.getUserName(), // Settings.getPassword()); post.setDescription(String.valueOf(results.get("description"))); } catch (XMLRPCException e) { handleException(e, "Could not get post categories"); } } public void setCategories(Post post) { Log.d(getClass().getSimpleName(), "setCategories started"); if (post == null || post.getPostid() == null) return; XMLRPCClient client = new XMLRPCClient(Settings.getURI()); Object[] categories; try { categories = (Object[]) client.call("mt.getPostCategories", post.getPostid(), Settings.getUserName(), Settings.getPassword()); } catch (XMLRPCException e) { handleException(e, "Could not load categories for post " + post.getPostid()); categories = null; } post.setCategories(categories); Log.d(getClass().getSimpleName(), "setCategories finished"); } public boolean save(Post post, String blogid, boolean publish) { try { XMLRPCClient client = new XMLRPCClient(Settings.getURI()); Object postid = post.getPostid(); if (postid == null) { postid = client.call("metaWeblog.newPost", blogid, Settings.getUserName(), Settings.getPassword(), post.getMap(), publish); } else { client.call("metaWeblog.editPost", post.getPostid(), // Settings.getUserName(), Settings.getPassword(), // post.getMap(), publish); } if (post.isCategoriesSet()) { try { client.call("mt.setPostCategories", postid, // Settings.getUserName(), Settings.getPassword(), // post.getCategoriesAsMap()); } catch (XMLRPCException e) { ThreadingUtils.showToast(handler, ctx, R.string.taxonomy_save_error, Toast.LENGTH_LONG); } } return true; } catch (XMLRPCException e) { handleException(e, "Could not send post"); return false; } } public void initCategories(String... blogids) { for (final String blogid : blogids) new Thread() { public void run() { loadCategory(blogid); }; }.start(); } public List<CategoryInfo> getCategories(String blogid) { Lock lock = getLock(blogid); lock.lock(); try { List<CategoryInfo> availableCategories = categoryInfo.get(blogid); if (availableCategories == null) return loadCategory(blogid); return availableCategories; } finally { lock.unlock(); } } @SuppressWarnings("unchecked") protected ArrayList<CategoryInfo> loadCategory(String blogid) { Lock lock = getLock(blogid); lock.lock(); ArrayList<CategoryInfo> availableCategories; try { XMLRPCClient client = new XMLRPCClient(Settings.getURI()); Object[] res = (Object[]) client.call("mt.getCategoryList", blogid, // Settings.getUserName(), Settings.getPassword()); Arrays.sort(res, new Comparator<Object>() { @Override public int compare(Object object1, Object object2) { return object1.toString().compareTo(object2.toString()); } }); availableCategories = new ArrayList<CategoryInfo>(res.length); for (Object c : res) availableCategories.add(new CategoryInfo( (Map<String, Object>) c)); categoryInfo.put(blogid, availableCategories); } catch (XMLRPCException e) { handleException(e, "Could not get category list"); availableCategories = new ArrayList<CategoryInfo>(); } lock.unlock(); return availableCategories; } @SuppressWarnings({ "unchecked", "rawtypes" }) public ArrayList<UsersBlog> getUsersBlogs() { try { ArrayList<UsersBlog> usersBlogs; XMLRPCClient client = new XMLRPCClient(Settings.getURI()); Object[] result = (Object[]) client.call("blogger.getUsersBlogs", BLOGGER_API_KEY, Settings.getUserName(), Settings.getPassword()); usersBlogs = new ArrayList<UsersBlog>(result.length); for (Object map : result) { usersBlogs.add(new UsersBlog((Map) map)); } return usersBlogs; } catch (XMLRPCException e) { handleException(e, "Could not get users blogs"); return new ArrayList<UsersBlog>(); } } public boolean delete(Post post) { XMLRPCClient client = new XMLRPCClient(Settings.getURI()); try { client.call("blogger.deletePost", BLOGGER_API_KEY, // post.getPostid(), // Settings.getUserName(), // Settings.getPassword(), false); return true; } catch (XMLRPCException e) { handleException(e, "Could not delete post " + post.getPostid()); return false; } } protected void handleException(final Throwable e, String msg) { Log.e("WDAO", msg, e); handler.post(new Runnable() { @Override public void run() { Builder alertBuilder = new Builder(ctx); if (e instanceof XMLRPCFault && ((XMLRPCFault) e).getFaultCode() == 1) { String xmlrpcFault = ctx.getResources().getString( R.string.xmlrpc_fault_1); alertBuilder.setMessage(xmlrpcFault + "\n" + e.getMessage()); } else { String wdaoFault = ctx.getResources().getString( R.string.wdao_fault); alertBuilder.setMessage(wdaoFault + "\n" + e.getMessage()); } alertBuilder.create().show(); } }); } private synchronized Lock getLock(String blogid) { Lock lock = categoryInfoPreloadLocks.get(blogid); if (lock == null) { lock = new ReentrantLock(); categoryInfoPreloadLocks.put(blogid, lock); } return lock; } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import java.util.Map; import android.os.Parcel; import android.os.Parcelable; public class UsersBlog implements Parcelable { private String blogName; private String blogid; private String url; public UsersBlog(Map<String, Object> map) { blogName = String.valueOf(map.get("blogName")); blogid = String.valueOf(map.get("blogid")); url = String.valueOf(map.get("url")); } public String getBlogName() { return blogName; } public String getBlogid() { return blogid; } public String getUrl() { return url; } @Override public String toString() { return blogName; } // Parcelable implementation private UsersBlog(Parcel in) { blogName = in.readString(); blogid = in.readString(); url = in.readString(); } public static final Parcelable.Creator<UsersBlog> CREATOR = new Parcelable.Creator<UsersBlog>() { public UsersBlog createFromParcel(Parcel in) { return new UsersBlog(in); } public UsersBlog[] newArray(int size) { return new UsersBlog[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(blogName); out.writeString(blogid); out.writeString(url); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import java.util.HashMap; import java.util.Map; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; public class CategoryInfo implements Parcelable { private static boolean intId = false; private String categoryName; private String categoryId; public CategoryInfo(Map<String, Object> struct) { Log.d("CategoryInfo", struct.toString()); categoryName = String.valueOf(struct.get("categoryName")); Object id = struct.get("categoryId"); intId = id instanceof Integer; categoryId = String.valueOf(id); } public String getCategoryName() { return categoryName; } public String getCategoryId() { return categoryId; } public Map<String, Object> getMap() { Map<String, Object> result = new HashMap<String, Object>(); if (intId) result.put("categoryId", Integer.parseInt(categoryId)); else result.put("categoryId", categoryId); result.put("categoryName", categoryName); return result; } @Override public String toString() { return categoryName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((categoryId == null) ? 0 : categoryId.hashCode()); result = prime * result + ((categoryName == null) ? 0 : categoryName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CategoryInfo other = (CategoryInfo) obj; if (categoryId == null) { if (other.categoryId != null) return false; } else if (!categoryId.equals(other.categoryId)) return false; if (categoryName == null) { if (other.categoryName != null) return false; } else if (!categoryName.equals(other.categoryName)) return false; return true; } // Parcelable public CategoryInfo(Parcel in) { categoryId = in.readString(); categoryName = in.readString(); } public static final Parcelable.Creator<CategoryInfo> CREATOR = new Parcelable.Creator<CategoryInfo>() { public CategoryInfo createFromParcel(Parcel in) { return new CategoryInfo(in); } public CategoryInfo[] newArray(int size) { return new CategoryInfo[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(categoryId); dest.writeString(categoryName); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; public class NamedObject<T> { private String name; private T value; public NamedObject(String name, T value) { this.name = name; this.value = value; } public T getValue() { return value; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (o instanceof NamedObject<?>) { NamedObject<?> no = (NamedObject<?>) o; return name.equals(no.name) && value.equals(no.value); } if (value == null) return o == null; return value.equals(o); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import android.os.Parcel; import android.os.Parcelable; public class Post implements Parcelable { private String title; private String link; private Date dateCreated; private String permaLink; private String postid; private String description; private Set<CategoryInfo> categories = new HashSet<CategoryInfo>(); private boolean categoriesSet; public Post() { // empty constructor } public Post(Map<String, Object> struct) { title = (String) struct.get("title"); link = (String) struct.get("link"); dateCreated = (Date) struct.get("dateCreated"); permaLink = (String) struct.get("permaLink"); postid = String.valueOf(struct.get("postid")); description = (String) struct.get("description"); } /** * mt_allow_comments=1, userid=christian, mt_convert_breaks=0, * content=<title>Erster Blogeintrag</title>Dies ist nicht nur mein erster * Blogeintrag, es ist auch der erste welcher mit dem Drupal Editor erstellt * wurde. Ob es wohl funktioniert?, description=Dies ist nicht nur mein * erster Blogeintrag, es ist auch der erste welcher mit dem Drupal Editor * erstellt wurde. Ob es wohl funktioniert? */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Date getDateCreated() { return dateCreated; } public String getPermaLink() { return permaLink; } public String getPostid() { return postid; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Set<CategoryInfo> getCategories() { return categories; } public void addCategory(CategoryInfo category) { categories.add(category); categoriesSet = true; } @SuppressWarnings("unchecked") public void setCategories(Object[] categories) { if (categories == null) return; this.categories = new HashSet<CategoryInfo>(); for (Object c : categories) this.categories.add(new CategoryInfo((Map<String, Object>) c)); categoriesSet = true; } public Map<String, Object> getMap() { Map<String, Object> struct = new HashMap<String, Object>(); struct.put("title", title); struct.put("link", link == null ? "" : link); struct.put("description", description); return struct; } @SuppressWarnings("unchecked") public Map<String, Object>[] getCategoriesAsMap() { Set<CategoryInfo> categories = getCategories(); Map<String, Object>[] result = new Map[categories.size()]; int i = 0; for (CategoryInfo c : categories) result[i++] = c.getMap(); return result; } // Parcelable implementation private Post(Parcel in) { title = in.readString(); link = in.readString(); long d = in.readLong(); dateCreated = (d == 0L ? null : new Date(d)); permaLink = in.readString(); postid = in.readString(); description = in.readString(); categoriesSet = in.readByte() == 1; Object[] cats = in.readParcelableArray(CategoryInfo.class .getClassLoader()); if (cats != null) for (Object o : cats) categories.add((CategoryInfo) o); } public static final Parcelable.Creator<Post> CREATOR = new Parcelable.Creator<Post>() { public Post createFromParcel(Parcel in) { return new Post(in); } public Post[] newArray(int size) { return new Post[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(title); out.writeString(link); out.writeLong(dateCreated == null ? 0L : dateCreated.getTime()); out.writeString(permaLink); out.writeString(postid); out.writeString(description); out.writeByte(categoriesSet ? (byte) 1 : (byte) 0); out.writeParcelableArray(categories.toArray(new CategoryInfo[categories .size()]), 0); } public void setCategoriesSet(boolean categoriesSet) { this.categoriesSet = categoriesSet; } public boolean isCategoriesSet() { return categoriesSet; } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal.model; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import ch.dissem.android.drupal.R; public class Site implements Parcelable { private Integer id; private String name; private String url; private String username; private String password; private String signature; private boolean signatureEnabled = false; private SignaturePosition signaturePosition; public Site() { } public Site(Context ctx) { signature = ctx.getString(R.string.default_signature); signaturePosition = SignaturePosition.END; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public boolean isSignatureEnabled() { return signatureEnabled; } public void setSignatureEnabled(boolean signatureEnabled) { this.signatureEnabled = signatureEnabled; } public SignaturePosition getSignaturePosition() { return signaturePosition; } public void setSignaturePosition(SignaturePosition signaturePosition) { this.signaturePosition = signaturePosition; } public static enum SignaturePosition { START(R.string.start), END(R.string.end); int resId; private SignaturePosition(int resId) { this.resId = resId; } public String toString(Context ctx) { return ctx.getString(resId); } public static SignaturePosition parse(String s) { for (SignaturePosition v : values()) { if (v.toString().equals(s)) return v; } return null; } } Integer getId() { return id; } void setId(int id) { this.id = id; } @Override public String toString() { return name; } // Parcelable implementation private Site(Parcel in) { if (in.readByte() == 1) id = in.readInt(); name = in.readString(); url = in.readString(); username = in.readString(); password = in.readString(); signature = in.readString(); signatureEnabled = (in.readByte() == 1); signaturePosition = SignaturePosition.parse(in.readString()); } public static final Parcelable.Creator<Site> CREATOR = new Parcelable.Creator<Site>() { public Site createFromParcel(Parcel in) { return new Site(in); } public Site[] newArray(int size) { return new Site[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { if (id != null) { out.writeByte((byte) 1); out.writeInt(id); } else { out.writeByte((byte) 0); } out.writeString(name); out.writeString(url); out.writeString(username); out.writeString(password); out.writeString(signature); out.writeByte(signatureEnabled ? (byte) 1 : (byte) 0); out.writeString(signaturePosition == null ? null : signaturePosition .toString()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((signature == null) ? 0 : signature.hashCode()); result = prime * result + (signatureEnabled ? 1231 : 1237); result = prime * result + ((signaturePosition == null) ? 0 : signaturePosition .hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Site other = (Site) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (signature == null) { if (other.signature != null) return false; } else if (!signature.equals(other.signature)) return false; if (signatureEnabled != other.signatureEnabled) return false; if (signaturePosition == null) { if (other.signaturePosition != null) return false; } else if (!signaturePosition.equals(other.signaturePosition)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } public boolean isSame(Site other) { if (id != null) return id.equals(other.id); return false; } }
Java
/** * Copyright (C) 2010 christian * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Spinner; import ch.dissem.android.drupal.model.Post; import ch.dissem.android.drupal.model.UsersBlog; /** * Activity to handle "shared" texts. * * @author christian */ public class ShareReceiver extends SiteSelector implements OnClickListener { private Button btnNew; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.share_receiver); super.onCreate(savedInstanceState); btnNew = (Button) findViewById(R.id.new_button); btnNew.setOnClickListener(this); } @Override protected Button[] getButtons() { return new Button[] { btnNew }; } @Override public void onClick(View v) { Intent intentEdit = new Intent(this, EditPost.class); String title = getIntent().getStringExtra(Intent.EXTRA_TITLE); String text = getIntent().getStringExtra(Intent.EXTRA_TEXT); Post post = new Post(); post.setTitle(title); post.setDescription(text); intentEdit.putExtra(EditPost.KEY_BLOG_ID, ((UsersBlog) ((Spinner) findViewById(R.id.sites)) .getSelectedItem()).getBlogid()); intentEdit.putExtra(EditPost.KEY_POST, post); startActivity(intentEdit); finish(); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import ch.dissem.android.drupal.model.Post; public class PostAdapter extends BaseAdapter { private Post[] posts; private Context ctx; private DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); public PostAdapter(Context ctx, Post[] posts) { this.ctx = ctx; this.posts = posts; } public int getCount() { return posts.length; } public Object getItem(int position) { return posts[position]; } public long getItemId(int position) { return position; } public View getView(int position, View v, ViewGroup parent) { if (v == null) { v = View.inflate(ctx, R.layout.recent_list_item, null); } Date date = posts[position].getDateCreated(); String title = posts[position].getTitle(); ((TextView) v.findViewById(R.id.date)).setText(df.format(date)); ((TextView) v.findViewById(R.id.title)).setText(title); return v; } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.net.URI; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ListView; import ch.dissem.android.drupal.model.DAO; import ch.dissem.android.drupal.model.Site; import ch.dissem.android.drupal.model.Site.SignaturePosition; public class Settings extends Activity implements OnClickListener { private static final String HISTORY_SIZE = "history_size"; private static final String SHOW_ADS = "show_ads"; private static Site selected; private static Editor settingsEditor; private ListView list; private DAO dao; /** * @param selected * @return <code>true</code> if settings actually changed */ public static boolean setSite(Site selected) { try { return selected == null ? Settings.selected != null : !selected .equals(Settings.selected); } finally { Settings.selected = selected; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_sites); dao = new DAO(this); List<Site> drupals = dao.getSites(); if (drupals.isEmpty()) { editSite(new Site(this)); return; } settingsEditor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); final EditText hsize = (EditText) findViewById(R.id.history_size); hsize.setText(String.valueOf(getHistorySize(this))); hsize.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { settingsEditor.putString(HISTORY_SIZE, hsize.getText() .toString()); return false; } }); final CheckBox ads = (CheckBox) findViewById(R.id.show_ads); ads.setChecked(isShowAds(this)); ads.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { settingsEditor.putBoolean(SHOW_ADS, isChecked); } }); list = (ListView) findViewById(R.id.site_list); Button btn = (Button) findViewById(R.id.add_site); btn.setOnClickListener(this); registerForContextMenu(list); } protected void editSite(Site drupal) { Intent intentEdit = new Intent(this, EditSite.class); intentEdit.putExtra(EditSite.KEY_SITE, drupal); startActivity(intentEdit); } @Override protected void onResume() { super.onResume(); if (settingsEditor == null) settingsEditor = PreferenceManager .getDefaultSharedPreferences(this).edit(); if (list == null) list = (ListView) findViewById(R.id.site_list); list.setAdapter(new ArrayAdapter<Site>(this, android.R.layout.simple_list_item_1, dao.getSites())); } @Override protected void onPause() { super.onPause(); settingsEditor.commit(); } public static URI getURI() { try { if (selected == null) return null; String result = selected.getUrl(); if (result == null) return null; if (!result.contains("://")) result = "http://" + result; if (!result.matches(".*[a-zA-Z0-9]/[a-zA-Z0-9].*\\.[a-zA-Z]+$")) { if (result.endsWith("/")) return URI.create(result + "xmlrpc.php"); else return URI.create(result + "/xmlrpc.php"); } return URI.create(result); } catch (IllegalArgumentException e) { return null; } } public static String getUserName() { if (selected == null) return null; return selected.getUsername(); } public static String getPassword() { if (selected == null) return null; return selected.getPassword(); } public static int getHistorySize(Context context) { try { return Integer.valueOf(PreferenceManager .getDefaultSharedPreferences(context).getString( HISTORY_SIZE, "10")); } catch (NumberFormatException e) { return 10; } } public static boolean isShowAds(Context context) { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(SHOW_ADS, true); } public static boolean isSignatureEnabled() { if (selected == null) return false; return selected.isSignatureEnabled(); } public static SignaturePosition getSignaturePosition() { if (selected == null) return null; return selected.getSignaturePosition(); } public static String getSignature() { if (selected == null) return null; return selected.getSignature(); } @Override public void onClick(View v) { editSite(new Site(this)); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, R.string.edit, 0, R.string.edit); menu.add(Menu.NONE, R.string.delete, 1, R.string.delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info; try { info = (AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e("ctxMenu", "bad menuInfo", e); return false; } final Site site = (Site) list.getAdapter().getItem(info.position); switch (item.getItemId()) { case R.string.edit: Intent intentEdit = new Intent(this, EditSite.class); intentEdit.putExtra(EditSite.KEY_SITE, site); startActivity(intentEdit); return true; case R.string.delete: dao.delete(site); if (site.isSame(selected)) selected = null; list.setAdapter(new ArrayAdapter<Site>(this, android.R.layout.simple_list_item_1, dao.getSites())); return true; default: return false; } } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import ch.dissem.android.drupal.model.DAO; import ch.dissem.android.drupal.model.NamedObject; import ch.dissem.android.drupal.model.Site; import ch.dissem.android.drupal.model.Site.SignaturePosition; public class EditSite extends Activity { public static final String KEY_SITE = "drupalsite"; public static final String KEY_URI_ERROR = "uriError"; private Site drupal; private EditText name; private EditText url; private EditText username; private EditText password; private EditText signature; private CheckBox useSignature; private Spinner signaturePos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_site); drupal = getIntent().getParcelableExtra(KEY_SITE); name = (EditText) findViewById(R.id.site_name); name.setText(drupal.getName()); url = (EditText) findViewById(R.id.site_url); url.setText(drupal.getUrl()); if (getIntent().getBooleanExtra(KEY_URI_ERROR, false)) { url.requestFocus(); url.selectAll(); } username = (EditText) findViewById(R.id.username); username.setText(drupal.getUsername()); password = (EditText) findViewById(R.id.password); password.setText(drupal.getPassword()); signature = (EditText) findViewById(R.id.signature); signature.setText(drupal.getSignature()); useSignature = (CheckBox) findViewById(R.id.show_signature); useSignature.setChecked(drupal.isSignatureEnabled()); signaturePos = (Spinner) findViewById(R.id.signature_position); ArrayList<NamedObject<SignaturePosition>> data = new ArrayList<NamedObject<SignaturePosition>>( 2); for (SignaturePosition sp : SignaturePosition.values()) { data.add(new NamedObject<SignaturePosition>(sp.toString(this), sp)); } ArrayAdapter<NamedObject<SignaturePosition>> adapter = new ArrayAdapter<NamedObject<SignaturePosition>>( this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(// android.R.layout.simple_spinner_dropdown_item); signaturePos.setAdapter(adapter); SignaturePosition sp = drupal.getSignaturePosition(); for (int i = 0; i < data.size(); i++) if (data.get(i).equals(sp)) signaturePos.setSelection(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.edit_site, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.site_save: save(); finish(); return true; case R.id.site_cancel: finish(); return true; default: return false; } } @SuppressWarnings("unchecked") private void save() { drupal.setName(name.getText().toString()); drupal.setUrl(url.getText().toString()); drupal.setUsername(username.getText().toString()); drupal.setPassword(password.getText().toString()); drupal.setSignature(signature.getText().toString()); drupal.setSignatureEnabled(useSignature.isChecked()); drupal.setSignaturePosition(// ((NamedObject<SignaturePosition>) signaturePos.getSelectedItem()) .getValue()); new DAO(this).save(drupal); } /* * (non-Javadoc) * * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent) */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { finish(); return true; } return super.onKeyDown(keyCode, event); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import ch.dissem.android.drupal.model.CategoryInfo; import ch.dissem.android.drupal.model.Post; import ch.dissem.android.drupal.model.Tag; import ch.dissem.android.drupal.model.WDAO; import ch.dissem.android.utils.MultiChoice; import ch.dissem.android.utils.ThreadingUtils; public class EditPost extends Activity implements OnClickListener { private boolean showTagWarning = true; public static final String KEY_BLOG_ID = "blogid"; public static final String KEY_POST = "post"; private String blogid; private Post post; private EditText content; private WDAO wdao; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { handler = new Handler(); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.edit_post); View saveButton = findViewById(R.id.save_post); saveButton.setOnClickListener(this); wdao = new WDAO(this); post = getIntent().getParcelableExtra(KEY_POST); blogid = getIntent().getStringExtra(KEY_BLOG_ID); content = (EditText) findViewById(R.id.Text); if (post != null) { EditText title = (EditText) findViewById(R.id.Title); title.setText(post.getTitle()); String description = post.getDescription(); if (description != null && description.length() > 0) { setText(description); } else { setProgressBarIndeterminateVisibility(true); new Thread() { public void run() { wdao.updateContent(post); handler.post(new Runnable() { @Override public void run() { if (content.getText().length() == 0) setText(post.getDescription()); EditPost.this .setProgressBarIndeterminateVisibility(false); } }); }; }.start(); } if (!post.isCategoriesSet()) { new Thread() { public void run() { wdao.setCategories(post); }; }.start(); } } else post = new Post(); } private void setText(String description) { String text = removeSignature(description); text = replaceLinks(text); content.setText(text); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.edit_post, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.insert_location: startActivityForResult(new Intent(this, LocationDialog.class), LocationDialog.REQUEST_CODE); return true; case R.id.taxonomy: if (post.getPostid() != null && !post.isCategoriesSet()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(android.R.string.dialog_alert_title); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(R.string.taxonomy_warning); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showTaxonomyDialog(); } }); builder.setCancelable(true); Dialog warning = builder.create(); warning.show(); } else { showTaxonomyDialog(); } return true; case R.id.tag_em: insertTag("<em>", null, "</em>"); return true; case R.id.tag_strong: insertTag("<strong>", null, "</strong>"); return true; case R.id.tag_menu: startActivityForResult(new Intent(this, TagList.class), TagList.REQUEST_CODE); return true; default: return false; } } private void showTaxonomyDialog() { EditPost.this.setProgressBarIndeterminate(true); final Handler handler = new Handler(); new Thread() { @Override public void run() { final List<CategoryInfo> categories = wdao .getCategories(blogid); handler.post(new Runnable() { @Override public void run() { MultiChoice<CategoryInfo> dlg = new MultiChoice<CategoryInfo>( EditPost.this, categories, post.getCategories()); dlg.setTitle(R.string.taxonomy); post.setCategoriesSet(true); dlg.show(); EditPost.this.setProgressBarIndeterminate(false); } }); } }.start(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CANCELED) return; if (requestCode == LocationDialog.REQUEST_CODE) { double lat = data.getDoubleExtra(LocationDialog.LATITUDE, 0); double lng = data.getDoubleExtra(LocationDialog.LONGITUDE, 0); insertTag(new StringBuilder("[").append(lat).append(",") .append(lng).append("|"), // getResources().getString(R.string.location_link_text), "]"); } else if (requestCode == TagList.REQUEST_CODE) { Tag tag = data.getParcelableExtra(TagList.TAG); insertTag(tag.getStartTag(), tag.getDefaultText(), tag.getEndTag()); } } public void onClick(View v) { final String title = String.valueOf(// ((TextView) findViewById(R.id.Title)).getText()); final ProgressDialog progress = ProgressDialog.show(EditPost.this, EditPost.this.getString(R.string.saving_post), title, false); new Thread() { @Override public void run() { if (post == null) post = new Post(); post.setTitle(title); String text = String.valueOf(// ((TextView) findViewById(R.id.Text)).getText()); post.setDescription(addSignature(replaceShorts(text))); if (wdao.save(post, blogid, ((CheckBox) findViewById(R.id.publish)).isChecked())) { ThreadingUtils.showToast(handler, EditPost.this, R.string.post_saved, Toast.LENGTH_LONG); finish(); } progress.dismiss(); } }.start(); } /** * Replace links with shortcuts in text * * @param text * @return */ public String replaceLinks(String text) { StringBuilder result = new StringBuilder(text); String link = getResources().getText(R.string.location_link).toString(); Pattern p = Pattern.compile("(<a href=\"" + link.replace("\\", "\\\\").replace(".", "\\.") .replace("?", "\\?").replace("+", "\\+") .replace("-", "\\-").replace("&", "\\&") .replace("%s", "\\d*\\.?\\d*") + "\">.*?</a>)"); Matcher m = p.matcher(text); while (m.find()) { result.replace(m.start(), m.end(), getShorts(m.group())); } return result.toString(); } /** * @param link * @return shortcut string for link */ private String getShorts(String link) { String[] p = getLinkPattern(); link = link.replace(p[0], "["); link = link.replace(p[1], ","); link = link.replace(p[2], "|"); link = link.replace(p[3], "]"); return link; } /** * Replace shortcuts with real links * * @param text * @return */ public String replaceShorts(String text) { StringBuilder result = new StringBuilder(text); Pattern p = Pattern.compile("(\\[\\d*\\.?\\d*,\\d*\\.?\\d*\\|.*?\\])"); Matcher m = p.matcher(text); while (m.find()) { result.replace(m.start(), m.end(), getLink(m.group())); } return result.toString(); } private String getLink(String shortLink) { String[] p = getLinkPattern(); shortLink = shortLink.replace("[", p[0]); shortLink = shortLink.replace(",", p[1]); shortLink = shortLink.replace("|", p[2]); shortLink = shortLink.replace("]", p[3]); return shortLink; } private String[] linkPattern = null; private String[] getLinkPattern() { if (linkPattern == null) { String linkString = "<a href=\"" + getResources().getText(R.string.location_link) + "\">%s</a>"; int i0 = 0; int i1 = linkString.indexOf("%s", 0); linkPattern = new String[4]; for (int c = 0; c < 3; c++) { linkPattern[c] = linkString.substring(i0, i1); i0 = i1 + 2; i1 = c < 2 ? linkString.indexOf("%s", i0) : linkString.length(); } linkPattern[3] = linkString.substring(i0, i1); } return linkPattern; } /** * Remove signature to save space on screen. * * @param text * @return */ private String removeSignature(String text) { if (Settings.isSignatureEnabled()) { String signature = Settings.getSignature(); switch (Settings.getSignaturePosition()) { case START: if (text.startsWith(signature)) { text = text.substring(signature.length()); } return text; case END: if (text.endsWith(signature)) { text = text .substring(0, text.length() - signature.length()); } return text; } } return text; } /** * Add the signature * * @param text * @return */ private String addSignature(String text) { if (Settings.isSignatureEnabled()) { String signature = Settings.getSignature(); switch (Settings.getSignaturePosition()) { case START: return signature + text; case END: return text + signature; } } return text; } private void insertTag(CharSequence startTag, CharSequence text, CharSequence endTag) { int endTagPos = content.getSelectionEnd(); int startTagPos = content.getSelectionStart(); int selectionLength = endTagPos - startTagPos; content.getText().insert(endTagPos, endTag); if (endTagPos == startTagPos && text != null) content.getText().insert(startTagPos, text); content.getText().insert(startTagPos, startTag); int dq = getDoubleQuote(startTag); if (dq > 0) content.setSelection(startTagPos + dq); else { startTagPos = content.getSelectionStart(); content.setSelection(startTagPos, startTagPos + selectionLength); } if (showTagWarning && startTag.length() > 0 && startTag.charAt(0) == '<') { Toast toast = Toast.makeText(this, R.string.tag_warning, Toast.LENGTH_LONG); toast.show(); showTagWarning = false; } } /** * @param tag * @return the first position in a "", or -1 if there is no occurrence */ private int getDoubleQuote(CharSequence tag) { for (int i = 0; i < tag.length() - 1; i++) { if (tag.charAt(i) == '"' && tag.charAt(i + 1) == '"') return i + 1; } return -1; } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.List; import android.app.Dialog; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.AdapterView.AdapterContextMenuInfo; import ch.dissem.android.drupal.model.DAO; import ch.dissem.android.drupal.model.Tag; public class TagList extends ListActivity implements OnClickListener { public static final int REQUEST_CODE = 0x10CA711; public static final String TAG = "tag"; private List<Tag> tagList; private DAO dao; private EditText startTag; private EditText defaultText; private EditText endTag; private ListView list; private Dialog editTagDialog; private Tag editTag; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tag_list); dao = new DAO(this); list = getListView(); initList(); registerForContextMenu(getListView()); findViewById(R.id.add_tag).setOnClickListener(this); } private void initList() { tagList = dao.getTags(); list.setAdapter(new ArrayAdapter<Tag>(this, android.R.layout.simple_list_item_1, tagList .toArray(new Tag[tagList.size()]))); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.add_tag: editTag = new Tag(); openDialog(); break; case R.id.save_tag: if (startTag.getText().length() > 0) { editTag.setStartTag(startTag.getText().toString()); editTag.setDefaultText(defaultText.getText().toString()); editTag.setEndTag(endTag.getText().toString()); dao.save(editTag); editTag = new Tag(); startTag.setText(""); endTag.setText(""); getDialog().hide(); initList(); } break; } } private void openDialog() { Dialog dlg = getDialog(); startTag.setText(editTag.getStartTag()); defaultText.setText(editTag.getDefaultText()); endTag.setText(editTag.getEndTag()); dlg.show(); } private Dialog getDialog() { if (editTagDialog == null) { editTagDialog = new Dialog(this); editTagDialog.setContentView(R.layout.edit_tag); editTagDialog.setTitle(R.string.edit_tag); startTag = (EditText) editTagDialog.findViewById(R.id.start_tag); defaultText = (EditText) editTagDialog .findViewById(R.id.default_text); endTag = (EditText) editTagDialog.findViewById(R.id.end_tag); editTagDialog.findViewById(R.id.save_tag).setOnClickListener(this); } return editTagDialog; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Tag tag = (Tag) getListView().getItemAtPosition(position); Intent intent = getIntent(); intent.putExtra(TAG, tag); setResult(RESULT_OK, intent); finish(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, R.string.edit, 0, R.string.edit); menu.add(Menu.NONE, R.string.delete, 1, R.string.delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info; try { info = (AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e("ctxMenu", "bad menuInfo", e); return false; } final Tag tag = (Tag) getListView().getItemAtPosition(info.position); switch (item.getItemId()) { case R.string.edit: editTag = tag; openDialog(); break; case R.string.delete: dao.delete(tag); initList(); break; default: return false; } return true; } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class About extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); // Set up click listeners View cancelButton = findViewById(R.id.about_close); cancelButton.setOnClickListener(this); } public void onClick(View v) { finish(); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import com.google.ads.AdRequest; import com.google.ads.AdSize; import com.google.ads.AdView; import android.content.Intent; import android.content.res.TypedArray; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Spinner; import ch.dissem.android.drupal.model.UsersBlog; public class Main extends SiteSelector implements OnClickListener { private AdView adView; private Button btnNew; private Button btnRecent; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.main); super.onCreate(savedInstanceState); btnNew = (Button) findViewById(R.id.new_button); btnNew.setOnClickListener(this); btnRecent = (Button) findViewById(R.id.recent_button); btnRecent.setOnClickListener(this); if (Settings.isShowAds(this)) setUpAds(); } public void onClick(View v) { switch (v.getId()) { case R.id.new_button: Intent intentEdit = new Intent(this, EditPost.class); intentEdit.putExtra(EditPost.KEY_BLOG_ID, ((UsersBlog) ((Spinner) findViewById(R.id.sites)) .getSelectedItem()).getBlogid()); startActivity(intentEdit); break; case R.id.recent_button: Intent intentRecent = new Intent(this, RecentEntries.class); intentRecent.putExtra(EditPost.KEY_BLOG_ID, ((UsersBlog) contentTypes.getSelectedItem()).getBlogid()); intentRecent.putExtra(KEY_CONTENT_TYPE_LIST, contentTypeList); startActivity(intentRecent); break; } } @Override protected Button[] getButtons() { return new Button[] { btnNew, btnRecent }; } private void setUpAds() { try { adView = new AdView(this, AdSize.SMART_BANNER, getString(R.string.admob)); AdRequest adRequest = new AdRequest(); adRequest.addTestDevice(AdRequest.TEST_EMULATOR); // Emulator adRequest.addTestDevice("D8DAABC966F7DF36A94AF57F1F809AE7"); // Transformer adRequest.addTestDevice("82CC01D4D1D7EFD209DB33A58DD10EF1"); // GalaxyNexus adRequest.addTestDevice("5827EEF4F3AEF72339B86D1A2A3193AC"); // Note 10.1 adView.loadAd(adRequest); LinearLayout main = (LinearLayout) findViewById(R.id.ad_space); main.addView(adView); } catch (Exception e) { // Ignore all exceptions, just don't display any ads... Log.d("ads", e.getMessage()); } } }
Java
/** * Copyright (C) 2010 christian * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; import ch.dissem.android.drupal.model.DAO; import ch.dissem.android.drupal.model.Site; import ch.dissem.android.drupal.model.UsersBlog; import ch.dissem.android.drupal.model.WDAO; /** * @author christian */ public abstract class SiteSelector extends Activity implements OnItemSelectedListener { public static final String KEY_CONTENT_TYPE_LIST = "contentTypeList"; protected ArrayList<UsersBlog> contentTypeList; private List<Site> drupalSiteList; private Spinner drupalSites; protected Spinner contentTypes; private ProgressBar progressBar; private int selectedSite; private int selectedType; private DAO dao; private WDAO wdao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); wdao = new WDAO(this); drupalSites = (Spinner) findViewById(R.id.drupals); dao = new DAO(this); contentTypes = (Spinner) findViewById(R.id.sites); contentTypes.setEnabled(false); progressBar = (ProgressBar) findViewById(R.id.sites_loader_progress); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelableArrayList(KEY_CONTENT_TYPE_LIST, contentTypeList); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); contentTypeList = savedInstanceState .getParcelableArrayList(KEY_CONTENT_TYPE_LIST); drupalSiteList = new DAO(this).getSites(); if (contentTypeList == null || contentTypeList.isEmpty()) { fillSiteSpinner(); } else { for (Button btn : getButtons()) btn.setEnabled(true); } } @Override protected void onPause() { super.onPause(); Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putInt("selectedSite", drupalSites.getSelectedItemPosition()); editor.putInt("selectedType", contentTypes.getSelectedItemPosition()); editor.commit(); } @Override protected void onResume() { super.onResume(); SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); selectedSite = preferences.getInt("selectedSite", 0); selectedType = preferences.getInt("selectedType", 0); fillDrupalsSpinner(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(this, Settings.class)); return true; case R.id.reload_sites: contentTypeList = null; fillSiteSpinner(); return true; case R.id.about: startActivity(new Intent(this, About.class)); return true; default: return false; } } protected void fillDrupalsSpinner() { drupalSiteList = dao.getSites(); SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); if (drupalSiteList.isEmpty()) { String url = preferences.getString("url", null); if (url != null) { Site imported = new Site(this); imported.setName("Default"); imported.setUrl(url); imported.setUsername(preferences.getString(DAO.USERNAME, null)); imported.setPassword(preferences.getString(DAO.PASSWORD, null)); dao.save(imported); drupalSiteList.add(imported); } else { startActivity(new Intent(this, Settings.class)); return; } } ArrayAdapter<Site> adapter = new ArrayAdapter<Site>(this, android.R.layout.simple_spinner_item, dao.getSites()); adapter.setDropDownViewResource(// android.R.layout.simple_spinner_dropdown_item); drupalSites.setAdapter(adapter); if (selectedSite >= 0 && selectedSite < drupalSites.getCount()) drupalSites.setSelection(selectedSite); drupalSites.setClickable(true); drupalSites.setOnItemSelectedListener(this); } @Override public void onItemSelected(AdapterView<?> av, View view, int position, long arg3) { if (position != selectedSite) { selectedSite = position; selectedType = 0; } if (Settings.setSite((Site) av.getSelectedItem()) || contentTypeList == null) { contentTypeList = null; fillSiteSpinner(); } else { if (!contentTypeList.isEmpty()) { updateContentTypeSpinner(); } else { contentTypes.setClickable(false); contentTypes.setEnabled(false); } } } protected void fillSiteSpinner() { contentTypes.setEnabled(false); for (Button btn : getButtons()) btn.setEnabled(false); progressBar.setVisibility(View.VISIBLE); final Handler handler = new Handler(); new Thread() { public void run() { if (contentTypeList == null) { if (Settings.getURI() == null) { if (drupalSites.getAdapter().isEmpty()) startActivity(new Intent(SiteSelector.this, Settings.class)); else { Intent intentEdit = new Intent(SiteSelector.this, EditSite.class); intentEdit.putExtra(EditSite.KEY_SITE, (Site) drupalSites.getSelectedItem()); intentEdit.putExtra(EditSite.KEY_URI_ERROR, true); startActivity(intentEdit); } return; } contentTypeList = wdao.getUsersBlogs(); for (UsersBlog blog : contentTypeList) wdao.initCategories(blog.getBlogid()); } if (!contentTypeList.isEmpty()) handler.post(new Runnable() { public void run() { updateContentTypeSpinner(); for (Button btn : getButtons()) btn.setEnabled(true); progressBar.setVisibility(View.INVISIBLE); } }); else handler.post(new Runnable() { public void run() { progressBar.setVisibility(View.INVISIBLE); } }); } }.start(); } private void updateContentTypeSpinner() { try { ArrayAdapter<UsersBlog> adapter = new ArrayAdapter<UsersBlog>( SiteSelector.this, android.R.layout.simple_spinner_item, contentTypeList); adapter.setDropDownViewResource(// android.R.layout.simple_spinner_dropdown_item); contentTypes.setAdapter(adapter); if (selectedType >= 0 && selectedType < contentTypes.getCount()) contentTypes.setSelection(selectedType); contentTypes.setClickable(true); contentTypes.setEnabled(true); } catch (NullPointerException ignore) { // If the user selects another site while loading, there can be a // NPE - just ignore it. } } /** * Buttons that ought to stay inactive until the sites are loaded. * * @return */ protected abstract Button[] getButtons(); @Override public void onNothingSelected(AdapterView<?> arg0) { // Nothing to do, I presume } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.Date; import android.app.Activity; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class LocationDialog extends Activity implements LocationListener, OnClickListener { public static final String LONGITUDE = "long"; public static final String LATITUDE = "lat"; public static final int REQUEST_CODE = 0x10CA710; private LocationManager mgr; private String best; private Criteria criteria; private TextView info; private Location lastLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location_dialog); setTitle(R.string.location_dialog_title); mgr = (LocationManager) getSystemService(LOCATION_SERVICE); criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); best = mgr.getBestProvider(criteria, true); Log.d("location", best); Location location = mgr.getLastKnownLocation(best); Log.d("location", String.valueOf(location)); info = (TextView) findViewById(R.id.location_dialog_info); setInfo(location); Button btn = (Button) findViewById(R.id.location_insert); btn.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); mgr.requestLocationUpdates(best, 2000, 0, this); } @Override protected void onPause() { super.onPause(); mgr.removeUpdates(this); } protected void setInfo(Location location) { String time; String accuracy; if (location == null) { time = getResources().getString(R.string.unknown); accuracy = getResources().getString(R.string.unknown); } else { time = new Date(location.getTime()).toLocaleString(); float acc = location.getAccuracy(); accuracy = Math.round(acc) + getResources().getString(R.string.accuracy_unit); } info.setText(getResources().getString(R.string.location_dialog_info, accuracy, time)); lastLocation = location; } public void onLocationChanged(Location location) { setInfo(location); } public void onProviderDisabled(String provider) { best = mgr.getBestProvider(criteria, true); } public void onProviderEnabled(String provider) { best = mgr.getBestProvider(criteria, true); } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } public void onClick(View v) { if (lastLocation == null) { setResult(RESULT_CANCELED); } else { Intent intent = getIntent(); intent.putExtra(LATITUDE, lastLocation.getLatitude()); intent.putExtra(LONGITUDE, lastLocation.getLongitude()); setResult(RESULT_OK, intent); } finish(); } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor 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. * * Drupal Editor 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 Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.drupal; import java.util.ArrayList; import android.app.ListActivity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import ch.dissem.android.drupal.model.Post; import ch.dissem.android.drupal.model.UsersBlog; import ch.dissem.android.drupal.model.WDAO; public class RecentEntries extends ListActivity implements OnItemClickListener { private String blogid; private ArrayList<UsersBlog> contentTypeList; private WDAO wdao; private int selectedType; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.recent_entries); contentTypeList = getIntent().getParcelableArrayListExtra( SiteSelector.KEY_CONTENT_TYPE_LIST); registerForContextMenu(getListView()); blogid = getIntent().getStringExtra(EditPost.KEY_BLOG_ID); wdao = new WDAO(this); fillSiteSpinner(); getListView().setOnItemClickListener(this); } @Override protected void onPause() { super.onPause(); Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putInt("selectedType", // ((Spinner) findViewById(R.id.sites)).getSelectedItemPosition()); editor.commit(); } @Override protected void onResume() { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); selectedType = preferences.getInt("selectedType", 0); loadRecentEntries(); super.onResume(); } private void loadRecentEntries() { final Handler handler = new Handler(); setProgressBarIndeterminateVisibility(true); new Thread() { public void run() { final Post[] posts = wdao.getPosts(blogid); handler.post(new Runnable() { public void run() { ListView list = getListView(); list.setAdapter(new PostAdapter(RecentEntries.this, posts)); RecentEntries.this .setProgressBarIndeterminateVisibility(false); } }); } }.start(); } protected void fillSiteSpinner() { final Handler handler = new Handler(); new Thread() { public void run() { handler.post(new Runnable() { public void run() { Spinner blogs = (Spinner) findViewById(R.id.sites); ArrayAdapter<UsersBlog> adapter = new ArrayAdapter<UsersBlog>( RecentEntries.this, android.R.layout.simple_spinner_item, contentTypeList); adapter.setDropDownViewResource(// android.R.layout.simple_spinner_dropdown_item); blogs.setAdapter(adapter); blogs.setClickable(true); blogs.setSelection(selectedType); blogs.setOnItemSelectedListener(new SiteSelectedListener()); } }); } }.start(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, R.string.edit, 0, R.string.edit); menu.add(Menu.NONE, R.string.delete, 1, R.string.delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info; try { info = (AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e("ctxMenu", "bad menuInfo", e); return false; } final Post post = (Post) getListView().getAdapter().getItem( info.position); switch (item.getItemId()) { case R.string.edit: editPost(post); break; case R.string.delete: deletePost(post); break; default: return false; } return true; } protected void editPost(Post post) { Intent intentEdit = new Intent(this, EditPost.class); intentEdit.putExtra(EditPost.KEY_POST, post); intentEdit.putExtra(EditPost.KEY_BLOG_ID, blogid); startActivity(intentEdit); } protected void deletePost(final Post post) { final Handler handler = new Handler(); setProgressBarIndeterminateVisibility(true); new Thread() { public void run() { final boolean deleted = wdao.delete(post); handler.post(new Runnable() { public void run() { if (deleted) loadRecentEntries(); else RecentEntries.this .setProgressBarIndeterminateVisibility(false); } }); } }.start(); } protected class SiteSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { UsersBlog site = (UsersBlog) parent.getSelectedItem(); blogid = site.getBlogid(); loadRecentEntries(); } public void onNothingSelected(AdapterView<?> parent) { } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long arg3) { Post post = (Post) getListView().getItemAtPosition(pos); editPost(post); } }
Java