Extend optional MySQL implementation, part 3. See #312 and #1707

This commit is contained in:
PikaMug 2021-07-09 19:48:00 -04:00
parent fe4deed7af
commit ab6dee05d2
17 changed files with 2116 additions and 2123 deletions

View File

@ -12,20 +12,19 @@
package me.blackvein.quests;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.events.quester.QuesterPostUpdateObjectiveEvent;
import me.blackvein.quests.events.quester.QuesterPreUpdateObjectiveEvent;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.events.quester.QuesterPostUpdateObjectiveEvent;
import me.blackvein.quests.events.quester.QuesterPreUpdateObjectiveEvent;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
public abstract class CustomObjective implements Listener {
@ -121,7 +120,7 @@ public abstract class CustomObjective implements Listener {
/**
* Set whether to let user set required amount for objective
*
* @param showCount
* @param showCount Whether or not to show the count
*/
public void setShowCount(final boolean showCount) {
this.showCount = showCount;
@ -150,7 +149,7 @@ public abstract class CustomObjective implements Listener {
}
}
}
if (m != null && !m.isEmpty()) {
if (!m.isEmpty()) {
return m;
}
}
@ -161,32 +160,19 @@ public abstract class CustomObjective implements Listener {
public void incrementObjective(final Player player, final CustomObjective obj, final int count, final Quest quest) {
final Quester quester = plugin.getQuester(player.getUniqueId());
if (quester != null) {
// Check if the player has Quest with objective
boolean hasQuest = false;
for (final CustomObjective co : quester.getCurrentStage(quest).customObjectives) {
if (co.getName().equals(obj.getName())) {
hasQuest = true;
break;
}
}
if (hasQuest && quester.hasCustomObjective(quest, obj.getName())) {
if (quester.getQuestData(quest).customObjectiveCounts.containsKey(obj.getName())) {
final int old = quester.getQuestData(quest).customObjectiveCounts.get(obj.getName());
plugin.getQuester(player.getUniqueId()).getQuestData(quest).customObjectiveCounts
.put(obj.getName(), old + count);
} else {
plugin.getQuester(player.getUniqueId()).getQuestData(quest).customObjectiveCounts
.put(obj.getName(), count);
}
if (quester.hasCustomObjective(quest, obj.getName())) {
int index = -1;
for (int i = 0; i < quester.getCurrentStage(quest).customObjectives.size(); i++) {
if (quester.getCurrentStage(quest).customObjectives.get(i).getName().equals(obj.getName())) {
index = i;
for (CustomObjective co : quester.getCurrentStage(quest).customObjectives) {
index++;
if (co.getName().equals(this.getName())) {
final int old = quester.getQuestData(quest).customObjectiveCounts.get(index);
plugin.getQuester(player.getUniqueId()).getQuestData(quest).customObjectiveCounts
.set(index, old + count);
break;
}
}
if (index > -1) {
final int progress = quester.getQuestData(quest).customObjectiveCounts.get(obj.getName());
final int progress = quester.getQuestData(quest).customObjectiveCounts.get(index);
final int goal = quester.getCurrentStage(quest).customObjectiveCounts.get(index);
final ObjectiveType type = ObjectiveType.CUSTOM;
@ -199,9 +185,10 @@ public abstract class CustomObjective implements Listener {
new ItemStack(Material.AIR, goal)), null, null, null, null, null, null, obj);
// Multiplayer
int finalIndex = index;
quester.dispatchMultiplayerObjectives(quest, quester.getCurrentStage(quest), (final Quester q) -> {
q.getQuestData(quest).customObjectiveCounts.put(obj.getName(),
quester.getQuestData(quest).customObjectiveCounts.get(obj.getName()));
final int old = q.getQuestData(quest).customObjectiveCounts.get(finalIndex);
q.getQuestData(quest).customObjectiveCounts.set(finalIndex, old + count);
q.finishObjective(quest, new Objective(type, new ItemStack(Material.AIR, 1),
new ItemStack(Material.AIR, goal)), null, null, null, null, null, null, obj);
return null;

View File

@ -362,7 +362,7 @@ public class Quest implements Comparable<Quest> {
final Location source = quester.getPlayer().getLocation();
Location nearest = null;
double old_distance = 30000000;
final EntityType et = stage.mobsToTame.keySet().iterator().next();
final EntityType et = stage.mobsToTame.getFirst();
if (source.getWorld() == null) {
return;
}
@ -383,7 +383,7 @@ public class Quest implements Comparable<Quest> {
final Location source = quester.getPlayer().getLocation();
Location nearest = null;
double old_distance = 30000000;
final DyeColor dc = stage.sheepToShear.keySet().iterator().next();
final DyeColor dc = stage.sheepToShear.getFirst();
if (source.getWorld() == null) {
return;
}
@ -452,7 +452,7 @@ public class Quest implements Comparable<Quest> {
if (quester.questPoints < reqs.getQuestPoints()) {
return false;
}
if (quester.completedQuests.containsAll(reqs.getNeededQuests()) == false) {
if (!quester.completedQuests.containsAll(reqs.getNeededQuests())) {
return false;
}
for (final Quest q : reqs.getBlockQuests()) {
@ -468,14 +468,13 @@ public class Quest implements Comparable<Quest> {
}
}
if (reqs.getHeroesPrimaryClass() != null) {
if (plugin.getDependencies()
.testPrimaryHeroesClass(reqs.getHeroesPrimaryClass(), player.getUniqueId()) == false) {
if (!plugin.getDependencies().testPrimaryHeroesClass(reqs.getHeroesPrimaryClass(), player.getUniqueId())) {
return false;
}
}
if (reqs.getHeroesSecondaryClass() != null) {
if (plugin.getDependencies()
.testSecondaryHeroesClass(reqs.getHeroesSecondaryClass(), player.getUniqueId()) == false) {
if (!plugin.getDependencies().testSecondaryHeroesClass(reqs.getHeroesSecondaryClass(),
player.getUniqueId())) {
return false;
}
}
@ -491,7 +490,7 @@ public class Quest implements Comparable<Quest> {
}
}
for (final String s : reqs.getPermissions()) {
if (p.hasPermission(s) == false) {
if (!p.hasPermission(s)) {
return false;
}
}
@ -504,7 +503,7 @@ public class Quest implements Comparable<Quest> {
}
}
if (found != null) {
if (found.testRequirement(p, reqs.getCustomRequirements().get(s)) == false) {
if (!found.testRequirement(p, reqs.getCustomRequirements().get(s))) {
return false;
}
} else {
@ -706,7 +705,7 @@ public class Quest implements Comparable<Quest> {
depends.getVaultEconomy().depositPlayer(player, lb.getMoney());
}
}
if (lb.getItemList().isEmpty() == false) {
if (!lb.getItemList().isEmpty()) {
phatLootItems.addAll(lb.getItemList());
if (player.isOnline()) {
for (final ItemStack is : lb.getItemList()) {
@ -721,12 +720,12 @@ public class Quest implements Comparable<Quest> {
}
}
}
if (lb.getCommandList().isEmpty() == false && player.isOnline()) {
if (!lb.getCommandList().isEmpty() && player.isOnline()) {
for (final CommandLoot cl : lb.getCommandList()) {
cl.execute((Player)player);
}
}
if (lb.getMessageList().isEmpty() == false) {
if (!lb.getMessageList().isEmpty()) {
phatLootMessages.addAll(lb.getMessageList());
}
if (plugin.getSettings().getConsoleLogging() > 2) {
@ -749,7 +748,7 @@ public class Quest implements Comparable<Quest> {
}
issuedReward = true;
}
if (rews.getCustomRewards().isEmpty() == false) {
if (!rews.getCustomRewards().isEmpty()) {
issuedReward = true;
if (plugin.getSettings().getConsoleLogging() > 2) {
for (final String s : rews.getCustomRewards().keySet()) {
@ -897,10 +896,10 @@ public class Quest implements Comparable<Quest> {
quester.sendMessage("- " + ChatColor.DARK_GREEN + tot + ChatColor.DARK_PURPLE + " "
+ Lang.get(p, "experience"));
}
if (rews.getCommands().isEmpty() == false) {
if (!rews.getCommands().isEmpty()) {
int index = 0;
for (final String s : rews.getCommands()) {
if (rews.getCommandsOverrideDisplay().isEmpty() == false
if (!rews.getCommandsOverrideDisplay().isEmpty()
&& rews.getCommandsOverrideDisplay().size() > index) {
if (!rews.getCommandsOverrideDisplay().get(index).trim().equals("")) {
quester.sendMessage("- " + ChatColor.DARK_GREEN
@ -912,7 +911,7 @@ public class Quest implements Comparable<Quest> {
index++;
}
}
if (rews.getPermissions().isEmpty() == false) {
if (!rews.getPermissions().isEmpty()) {
int index = 0;
for (final String s : rews.getPermissions()) {
if (rews.getPermissionWorlds() != null && rews.getPermissionWorlds().size() > index) {
@ -925,14 +924,14 @@ public class Quest implements Comparable<Quest> {
index++;
}
}
if (rews.getMcmmoSkills().isEmpty() == false) {
if (!rews.getMcmmoSkills().isEmpty()) {
for (final String s : rews.getMcmmoSkills()) {
quester.sendMessage("- " + ChatColor.DARK_GREEN
+ rews.getMcmmoAmounts().get(rews.getMcmmoSkills().indexOf(s)) + " "
+ ChatColor.DARK_PURPLE + s + " " + Lang.get(p, "experience"));
}
}
if (rews.getHeroesClasses().isEmpty() == false) {
if (!rews.getHeroesClasses().isEmpty()) {
for (final String s : rews.getHeroesClasses()) {
quester.sendMessage("- " + ChatColor.AQUA
+ rews.getHeroesAmounts().get(rews.getHeroesClasses().indexOf(s)) + " " + ChatColor.BLUE
@ -943,7 +942,7 @@ public class Quest implements Comparable<Quest> {
p.sendMessage("- " + ChatColor.DARK_GREEN + rews.getPartiesExperience() + ChatColor.DARK_PURPLE
+ " " + Lang.get(p, "partiesExperience"));
}
if (phatLootMessages.isEmpty() == false) {
if (!phatLootMessages.isEmpty()) {
for (final String s : phatLootMessages) {
quester.sendMessage("- " + s);
}
@ -979,7 +978,9 @@ public class Quest implements Comparable<Quest> {
}
quester.saveData();
if (player.isOnline()) {
player.getPlayer().updateInventory();
if (player.getPlayer() != null) {
player.getPlayer().updateInventory();
}
}
quester.updateJournal();
quester.findCompassTarget();
@ -1043,7 +1044,7 @@ public class Quest implements Comparable<Quest> {
/**
* Checks if quester is in WorldGuard region start
*
* @deprecated Use {@link #isInRegion(Quester)}
* @deprecated Use {@link #isInRegionStart(Quester)}
* @param quester The quester to check
* @return true if quester is in region
*/
@ -1085,10 +1086,7 @@ public class Quest implements Comparable<Quest> {
if (regionStart == null) {
return false;
}
if (plugin.getDependencies().getWorldGuardApi()
.getApplicableRegionsIDs(player.getWorld(), player.getLocation()).contains(regionStart)) {
return true;
}
return false;
return plugin.getDependencies().getWorldGuardApi()
.getApplicableRegionsIDs(player.getWorld(), player.getLocation()).contains(regionStart);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,18 +12,14 @@
package me.blackvein.quests;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import me.blackvein.quests.convo.quests.main.QuestMainPrompt;
import me.blackvein.quests.convo.quests.menu.QuestMenuPrompt;
import me.blackvein.quests.convo.quests.stages.StageMenuPrompt;
import me.blackvein.quests.interfaces.ReloadCallback;
import me.blackvein.quests.util.CK;
import me.blackvein.quests.util.ConfigUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Location;
@ -42,14 +38,17 @@ import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import me.blackvein.quests.convo.quests.main.QuestMainPrompt;
import me.blackvein.quests.convo.quests.menu.QuestMenuPrompt;
import me.blackvein.quests.convo.quests.stages.StageMenuPrompt;
import me.blackvein.quests.interfaces.ReloadCallback;
import me.blackvein.quests.util.CK;
import me.blackvein.quests.util.ConfigUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
public class QuestFactory implements ConversationAbandonedListener {
@ -180,23 +179,23 @@ public class QuestFactory implements ConversationAbandonedListener {
if (reqs.getQuestPoints() != 0) {
context.setSessionData(CK.REQ_QUEST_POINTS, reqs.getQuestPoints());
}
if (reqs.getItems().isEmpty() == false) {
if (!reqs.getItems().isEmpty()) {
context.setSessionData(CK.REQ_ITEMS, reqs.getItems());
context.setSessionData(CK.REQ_ITEMS_REMOVE, reqs.getRemoveItems());
}
if (reqs.getNeededQuests().isEmpty() == false) {
if (!reqs.getNeededQuests().isEmpty()) {
final List<String> names = reqs.getNeededQuests().stream().map(Quest::getName).collect(Collectors.toList());
context.setSessionData(CK.REQ_QUEST, names);
}
if (reqs.getBlockQuests().isEmpty() == false) {
if (!reqs.getBlockQuests().isEmpty()) {
final List<String> names = reqs.getBlockQuests().stream().map(Quest::getName).collect(Collectors.toList());
context.setSessionData(CK.REQ_QUEST_BLOCK, names);
}
if (reqs.getMcmmoSkills().isEmpty() == false) {
if (!reqs.getMcmmoSkills().isEmpty()) {
context.setSessionData(CK.REQ_MCMMO_SKILLS, reqs.getMcmmoAmounts());
context.setSessionData(CK.REQ_MCMMO_SKILL_AMOUNTS, reqs.getMcmmoAmounts());
}
if (reqs.getPermissions().isEmpty() == false) {
if (!reqs.getPermissions().isEmpty()) {
context.setSessionData(CK.REQ_PERMISSION, reqs.getPermissions());
}
if (reqs.getHeroesPrimaryClass() != null) {
@ -205,7 +204,7 @@ public class QuestFactory implements ConversationAbandonedListener {
if (reqs.getHeroesSecondaryClass() != null) {
context.setSessionData(CK.REQ_HEROES_SECONDARY_CLASS, reqs.getHeroesSecondaryClass());
}
if (reqs.getCustomRequirements().isEmpty() == false) {
if (!reqs.getCustomRequirements().isEmpty()) {
final LinkedList<String> list = new LinkedList<String>();
final LinkedList<Map<String, Object>> datamapList = new LinkedList<Map<String, Object>>();
for (final Entry<String, Map<String, Object>> entry : reqs.getCustomRequirements().entrySet()) {
@ -215,7 +214,7 @@ public class QuestFactory implements ConversationAbandonedListener {
context.setSessionData(CK.REQ_CUSTOM, list);
context.setSessionData(CK.REQ_CUSTOM_DATA, datamapList);
}
if (reqs.getDetailsOverride().isEmpty() == false) {
if (!reqs.getDetailsOverride().isEmpty()) {
context.setSessionData(CK.REQ_FAIL_MESSAGE, reqs.getDetailsOverride());
}
final Rewards rews = q.getRewards();
@ -228,40 +227,40 @@ public class QuestFactory implements ConversationAbandonedListener {
if (rews.getExp() != 0) {
context.setSessionData(CK.REW_EXP, rews.getExp());
}
if (rews.getItems().isEmpty() == false) {
if (!rews.getItems().isEmpty()) {
context.setSessionData(CK.REW_ITEMS, rews.getItems());
}
if (rews.getCommands().isEmpty() == false) {
if (!rews.getCommands().isEmpty()) {
context.setSessionData(CK.REW_COMMAND, rews.getCommands());
}
if (rews.getCommandsOverrideDisplay().isEmpty() == false) {
if (!rews.getCommandsOverrideDisplay().isEmpty()) {
context.setSessionData(CK.REW_COMMAND_OVERRIDE_DISPLAY, rews.getCommandsOverrideDisplay());
}
if (rews.getPermissions().isEmpty() == false) {
if (!rews.getPermissions().isEmpty()) {
context.setSessionData(CK.REW_PERMISSION, rews.getPermissions());
}
if (rews.getPermissions().isEmpty() == false) {
if (!rews.getPermissions().isEmpty()) {
context.setSessionData(CK.REW_PERMISSION_WORLDS, rews.getPermissionWorlds());
}
if (rews.getMcmmoSkills().isEmpty() == false) {
if (!rews.getMcmmoSkills().isEmpty()) {
context.setSessionData(CK.REW_MCMMO_SKILLS, rews.getMcmmoSkills());
context.setSessionData(CK.REW_MCMMO_AMOUNTS, rews.getMcmmoAmounts());
}
if (rews.getHeroesClasses().isEmpty() == false) {
if (!rews.getHeroesClasses().isEmpty()) {
context.setSessionData(CK.REW_HEROES_CLASSES, rews.getHeroesClasses());
context.setSessionData(CK.REW_HEROES_AMOUNTS, rews.getHeroesAmounts());
}
if (rews.getPartiesExperience() != 0) {
context.setSessionData(CK.REW_PARTIES_EXPERIENCE, rews.getPartiesExperience());
}
if (rews.getPhatLoots().isEmpty() == false) {
if (!rews.getPhatLoots().isEmpty()) {
context.setSessionData(CK.REW_PHAT_LOOTS, rews.getPhatLoots());
}
if (rews.getCustomRewards().isEmpty() == false) {
if (!rews.getCustomRewards().isEmpty()) {
context.setSessionData(CK.REW_CUSTOM, new LinkedList<String>(rews.getCustomRewards().keySet()));
context.setSessionData(CK.REW_CUSTOM_DATA, new LinkedList<Object>(rews.getCustomRewards().values()));
}
if (rews.getDetailsOverride().isEmpty() == false) {
if (!rews.getDetailsOverride().isEmpty()) {
context.setSessionData(CK.REW_DETAILS_OVERRIDE, rews.getDetailsOverride());
}
final Planner pln = q.getPlanner();
@ -360,38 +359,23 @@ public class QuestFactory implements ConversationAbandonedListener {
context.setSessionData(pref + CK.S_CUT_DURABILITY, durab);
}
if (!stage.getItemsToCraft().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
for (final ItemStack is : stage.getItemsToCraft()) {
items.add(is);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToCraft());
context.setSessionData(pref + CK.S_CRAFT_ITEMS, items);
}
if (!stage.getItemsToSmelt().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
for (final ItemStack is : stage.getItemsToSmelt()) {
items.add(is);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToSmelt());
context.setSessionData(pref + CK.S_SMELT_ITEMS, items);
}
if (!stage.getItemsToEnchant().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
for (final ItemStack is : stage.getItemsToEnchant()) {
items.add(is);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToEnchant());
context.setSessionData(pref + CK.S_ENCHANT_ITEMS, items);
}
if (!stage.getItemsToBrew().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
for (final ItemStack is : stage.getItemsToBrew()) {
items.add(is);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToBrew());
context.setSessionData(pref + CK.S_BREW_ITEMS, items);
}
if (!stage.getItemsToConsume().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
for (final ItemStack is : stage.getItemsToConsume()) {
items.add(is);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToConsume());
context.setSessionData(pref + CK.S_CONSUME_ITEMS, items);
}
if (stage.getCowsToMilk() != null) {
@ -404,30 +388,18 @@ public class QuestFactory implements ConversationAbandonedListener {
context.setSessionData(pref + CK.S_PLAYER_KILL, stage.getPlayersToKill());
}
if (!stage.getItemsToDeliver().isEmpty()) {
final LinkedList<ItemStack> items = new LinkedList<ItemStack>();
final LinkedList<Integer> npcs = new LinkedList<Integer>();
for (final ItemStack is : stage.getItemsToDeliver()) {
items.add(is);
}
for (final Integer n : stage.getItemDeliveryTargets()) {
npcs.add(n);
}
final LinkedList<ItemStack> items = new LinkedList<ItemStack>(stage.getItemsToDeliver());
final LinkedList<Integer> npcs = new LinkedList<Integer>(stage.getItemDeliveryTargets());
context.setSessionData(pref + CK.S_DELIVERY_ITEMS, items);
context.setSessionData(pref + CK.S_DELIVERY_NPCS, npcs);
context.setSessionData(pref + CK.S_DELIVERY_MESSAGES, stage.getDeliverMessages());
}
if (!stage.getCitizensToInteract().isEmpty()) {
final LinkedList<Integer> npcs = new LinkedList<Integer>();
for (final Integer n : stage.getCitizensToInteract()) {
npcs.add(n);
}
final LinkedList<Integer> npcs = new LinkedList<Integer>(stage.getCitizensToInteract());
context.setSessionData(pref + CK.S_NPCS_TO_TALK_TO, npcs);
}
if (!stage.getCitizensToKill().isEmpty()) {
final LinkedList<Integer> npcs = new LinkedList<Integer>();
for (final Integer n : stage.getCitizensToKill()) {
npcs.add(n);
}
final LinkedList<Integer> npcs = new LinkedList<Integer>(stage.getCitizensToKill());
context.setSessionData(pref + CK.S_NPCS_TO_KILL, npcs);
context.setSessionData(pref + CK.S_NPCS_TO_KILL_AMOUNTS, stage.getCitizenNumToKill());
}
@ -459,23 +431,22 @@ public class QuestFactory implements ConversationAbandonedListener {
}
if (!stage.getMobsToTame().isEmpty()) {
final LinkedList<String> mobs = new LinkedList<String>();
final LinkedList<Integer> amnts = new LinkedList<Integer>();
for (final Entry<EntityType, Integer> e : stage.getMobsToTame().entrySet()) {
mobs.add(MiscUtil.getPrettyMobName(e.getKey()));
amnts.add(e.getValue());
for (final EntityType e : stage.getMobsToTame()) {
mobs.add(MiscUtil.getPrettyMobName(e));
}
final LinkedList<Integer> amts = new LinkedList<Integer>(stage.getMobNumToTame());
context.setSessionData(pref + CK.S_TAME_TYPES, mobs);
context.setSessionData(pref + CK.S_TAME_AMOUNTS, amnts);
context.setSessionData(pref + CK.S_TAME_AMOUNTS, amts);
}
if (!stage.getSheepToShear().isEmpty()) {
final LinkedList<String> colors = new LinkedList<String>();
final LinkedList<Integer> amnts = new LinkedList<Integer>();
for (final Entry<DyeColor, Integer> e : stage.getSheepToShear().entrySet()) {
colors.add(MiscUtil.getPrettyDyeColorName(e.getKey()));
amnts.add(e.getValue());
for (final DyeColor d : stage.getSheepToShear()) {
colors.add(MiscUtil.getPrettyDyeColorName(d));
}
final LinkedList<Integer> amts = new LinkedList<Integer>(stage.sheepNumToShear);
context.setSessionData(pref + CK.S_SHEAR_COLORS, colors);
context.setSessionData(pref + CK.S_SHEAR_AMOUNTS, amnts);
context.setSessionData(pref + CK.S_SHEAR_AMOUNTS, amts);
}
if (!stage.getPasswordDisplays().isEmpty()) {
context.setSessionData(pref + CK.S_PASSWORD_DISPLAYS, stage.getPasswordDisplays());
@ -484,12 +455,12 @@ public class QuestFactory implements ConversationAbandonedListener {
if (!stage.getCustomObjectives().isEmpty()) {
final LinkedList<String> list = new LinkedList<String>();
final LinkedList<Integer> countList = new LinkedList<Integer>();
final LinkedList<Entry<String, Object>> datamapList = new LinkedList<Entry<String, Object>>();
for (int i = 0; i < stage.getCustomObjectives().size(); i++) {
list.add(stage.getCustomObjectives().get(i).getName());
countList.add(stage.getCustomObjectiveCounts().get(i));
}
datamapList.addAll(stage.getCustomObjectiveData());
final LinkedList<Entry<String, Object>> datamapList
= new LinkedList<Entry<String, Object>>(stage.getCustomObjectiveData());
context.setSessionData(pref + CK.S_CUSTOM_OBJECTIVES, list);
context.setSessionData(pref + CK.S_CUSTOM_OBJECTIVES_COUNT, countList);
context.setSessionData(pref + CK.S_CUSTOM_OBJECTIVES_DATA, datamapList);
@ -781,23 +752,8 @@ public class QuestFactory implements ConversationAbandonedListener {
? (LinkedList<Integer>) context.getSessionData(pref + CK.S_SHEAR_AMOUNTS) : null);
stage.set("password-displays", context.getSessionData(pref + CK.S_PASSWORD_DISPLAYS) != null
? (LinkedList<String>) context.getSessionData(pref + CK.S_PASSWORD_DISPLAYS) : null);
final LinkedList<LinkedList<String>> passPhrases
= (LinkedList<LinkedList<String>>) context.getSessionData(pref + CK.S_PASSWORD_PHRASES);
if (context.getSessionData(pref + CK.S_PASSWORD_PHRASES) != null) {
final LinkedList<String> toPut = new LinkedList<String>();
for (final LinkedList<String> list : passPhrases) {
String combine = "";
for (final String s : list) {
if (list.getLast().equals(s) == false) {
combine += s + "|";
} else {
combine += s;
}
}
toPut.add(combine);
}
stage.set("password-phrases", toPut);
}
stage.set("password-phrases", context.getSessionData(pref + CK.S_PASSWORD_PHRASES) != null
? (LinkedList<String>) context.getSessionData(pref + CK.S_PASSWORD_PHRASES) : null);
final LinkedList<String> customObjs = (LinkedList<String>) context.getSessionData(pref + CK.S_CUSTOM_OBJECTIVES);
final LinkedList<Integer> customObjCounts
= (LinkedList<Integer>) context.getSessionData(pref + CK.S_CUSTOM_OBJECTIVES_COUNT);
@ -849,21 +805,20 @@ public class QuestFactory implements ConversationAbandonedListener {
stage.set("condition", context.getSessionData(pref + CK.S_CONDITION) != null
? context.getSessionData(pref + CK.S_CONDITION) : null);
final Long delay = (Long) context.getSessionData(pref + CK.S_DELAY);
if (context.getSessionData(pref + CK.S_DELAY) != null) {
if (delay != null) {
stage.set("delay", delay.intValue() / 1000);
}
final String delayMessage = (String) context.getSessionData(pref + CK.S_DELAY_MESSAGE);
if (context.getSessionData(pref + CK.S_DELAY_MESSAGE) != null) {
stage.set("delay-message", delayMessage == null ? delayMessage : delayMessage.replace("\\n", "\n"));
if (delayMessage != null) {
stage.set("delay-message", delayMessage.replace("\\n", "\n"));
}
final String startMessage = (String) context.getSessionData(pref + CK.S_START_MESSAGE);
if (context.getSessionData(pref + CK.S_START_MESSAGE) != null) {
stage.set("start-message", startMessage == null ? startMessage : startMessage.replace("\\n", "\n"));
if (startMessage != null) {
stage.set("start-message", startMessage.replace("\\n", "\n"));
}
final String completeMessage = (String) context.getSessionData(pref + CK.S_COMPLETE_MESSAGE);
if (context.getSessionData(pref + CK.S_COMPLETE_MESSAGE) != null) {
stage.set("complete-message", completeMessage == null ? completeMessage
: completeMessage.replace("\\n", "\n"));
if (completeMessage != null) {
stage.set("complete-message", completeMessage.replace("\\n", "\n"));
}
stage.set("objective-override", context.getSessionData(pref + CK.S_OVERRIDE_DISPLAY) != null
? context.getSessionData(pref + CK.S_OVERRIDE_DISPLAY) : null);
@ -927,9 +882,9 @@ public class QuestFactory implements ConversationAbandonedListener {
pln.set("end", context.getSessionData(CK.PLN_END_DATE) != null
? (String) context.getSessionData(CK.PLN_END_DATE) : null);
pln.set("repeat", context.getSessionData(CK.PLN_REPEAT_CYCLE) != null
? ((Long) context.getSessionData(CK.PLN_REPEAT_CYCLE) / 1000) : null);
? ((Long) context.getSessionData(CK.PLN_REPEAT_CYCLE) / 1000L) : null);
pln.set("cooldown", context.getSessionData(CK.PLN_COOLDOWN) != null
? ((Long) context.getSessionData(CK.PLN_COOLDOWN) / 1000) : null);
? ((Long) context.getSessionData(CK.PLN_COOLDOWN) / 1000L) : null);
pln.set("override", context.getSessionData(CK.PLN_OVERRIDE) != null
? (Boolean) context.getSessionData(CK.PLN_OVERRIDE) : null);
if (pln.getKeys(false).isEmpty()) {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,21 +12,19 @@
package me.blackvein.quests;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import me.blackvein.quests.actions.Action;
import me.blackvein.quests.conditions.Condition;
import me.blackvein.quests.enums.ObjectiveType;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import me.blackvein.quests.actions.Action;
import me.blackvein.quests.conditions.Condition;
import me.blackvein.quests.enums.ObjectiveType;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
public class Stage {
@ -35,9 +33,6 @@ public class Stage {
protected LinkedList<ItemStack> blocksToPlace = new LinkedList<ItemStack>();
protected LinkedList<ItemStack> blocksToUse = new LinkedList<ItemStack>();
protected LinkedList<ItemStack> blocksToCut = new LinkedList<ItemStack>();
protected Integer cowsToMilk;
protected Integer fishToCatch;
protected Integer playersToKill;
protected LinkedList<ItemStack> itemsToCraft = new LinkedList<ItemStack>();
protected LinkedList<ItemStack> itemsToSmelt = new LinkedList<ItemStack>();
protected LinkedList<ItemStack> itemsToEnchant = new LinkedList<ItemStack>();
@ -111,14 +106,19 @@ public class Stage {
protected LinkedList<Location> locationsToKillWithin = new LinkedList<Location>();
protected LinkedList<Integer> radiiToKillWithin = new LinkedList<Integer>();
protected LinkedList<String> killNames = new LinkedList<String>();
protected LinkedList<EntityType> mobsToTame = new LinkedList<EntityType>();
protected LinkedList<Integer> mobNumToTame = new LinkedList<Integer>();
protected Integer fishToCatch;
protected Integer cowsToMilk;
protected LinkedList<DyeColor> sheepToShear = new LinkedList<DyeColor>();
protected LinkedList<Integer> sheepNumToShear = new LinkedList<Integer>();
protected Integer playersToKill;
protected LinkedList<Location> locationsToReach = new LinkedList<Location>();
protected LinkedList<Integer> radiiToReachWithin = new LinkedList<Integer>();
protected LinkedList<World> worldsToReachWithin = new LinkedList<World>();
protected LinkedList<String> locationNames = new LinkedList<String>();
protected Map<EntityType, Integer> mobsToTame = new EnumMap<EntityType, Integer>(EntityType.class);
protected Map<DyeColor, Integer> sheepToShear = new EnumMap<DyeColor, Integer>(DyeColor.class);
protected LinkedList<String> passwordDisplays = new LinkedList<String>();
protected LinkedList<LinkedList<String>> passwordPhrases = new LinkedList<LinkedList<String>>();
protected LinkedList<String> passwordPhrases = new LinkedList<String>();
protected String script;
protected Action startAction = null;
protected Action finishAction = null;
@ -178,30 +178,6 @@ public class Stage {
this.blocksToCut = blocksToCut;
}
public Integer getCowsToMilk() {
return cowsToMilk;
}
public void setCowsToMilk(final Integer cowsToMilk) {
this.cowsToMilk = cowsToMilk;
}
public Integer getFishToCatch() {
return fishToCatch;
}
public void setFishToCatch(final Integer fishToCatch) {
this.fishToCatch = fishToCatch;
}
public Integer getPlayersToKill() {
return playersToKill;
}
public void setPlayersToKill(final Integer playersToKill) {
this.playersToKill = playersToKill;
}
public LinkedList<ItemStack> getItemsToCraft() {
return itemsToCraft;
}
@ -362,22 +338,62 @@ public class Stage {
this.locationNames = locationNames;
}
public Map<EntityType, Integer> getMobsToTame() {
public LinkedList<EntityType> getMobsToTame() {
return mobsToTame;
}
public void setMobsToTame(final Map<EntityType, Integer> mobsToTame) {
public void setMobsToTame(final LinkedList<EntityType> mobsToTame) {
this.mobsToTame = mobsToTame;
}
public Map<DyeColor, Integer> getSheepToShear() {
public LinkedList<Integer> getMobNumToTame() {
return mobNumToTame;
}
public void setMobNumToTame(final LinkedList<Integer> mobNumToTame) {
this.mobNumToTame = mobNumToTame;
}
public Integer getFishToCatch() {
return fishToCatch;
}
public void setFishToCatch(final Integer fishToCatch) {
this.fishToCatch = fishToCatch;
}
public Integer getCowsToMilk() {
return cowsToMilk;
}
public void setCowsToMilk(final Integer cowsToMilk) {
this.cowsToMilk = cowsToMilk;
}
public Integer getPlayersToKill() {
return playersToKill;
}
public void setPlayersToKill(final Integer playersToKill) {
this.playersToKill = playersToKill;
}
public LinkedList<DyeColor> getSheepToShear() {
return sheepToShear;
}
public void setSheepToShear(final Map<DyeColor, Integer> sheepToShear) {
public void setSheepToShear(final LinkedList<DyeColor> sheepToShear) {
this.sheepToShear = sheepToShear;
}
public LinkedList<Integer> getSheepNumToShear() {
return sheepNumToShear;
}
public void setSheepNumToShear(final LinkedList<Integer> sheepNumToShear) {
this.sheepNumToShear = sheepNumToShear;
}
public LinkedList<String> getPasswordDisplays() {
return passwordDisplays;
}
@ -386,11 +402,11 @@ public class Stage {
this.passwordDisplays = passwordDisplays;
}
public LinkedList<LinkedList<String>> getPasswordPhrases() {
public LinkedList<String> getPasswordPhrases() {
return passwordPhrases;
}
public void setPasswordPhrases(final LinkedList<LinkedList<String>> passwordPhrases) {
public void setPasswordPhrases(final LinkedList<String> passwordPhrases) {
this.passwordPhrases = passwordPhrases;
}
@ -530,27 +546,27 @@ public class Stage {
* @return true if stage contains an objective
*/
public boolean hasObjective() {
if (blocksToBreak.isEmpty() == false) { return true; }
if (blocksToDamage.isEmpty() == false) { return true; }
if (blocksToPlace.isEmpty() == false) { return true; }
if (blocksToUse.isEmpty() == false) { return true; }
if (blocksToCut.isEmpty() == false) { return true; }
if (!blocksToBreak.isEmpty()) { return true; }
if (!blocksToDamage.isEmpty()) { return true; }
if (!blocksToPlace.isEmpty()) { return true; }
if (!blocksToUse.isEmpty()) { return true; }
if (!blocksToCut.isEmpty()) { return true; }
if (cowsToMilk != null) { return true; }
if (fishToCatch != null) { return true; }
if (playersToKill != null) { return true; }
if (itemsToCraft.isEmpty() == false) { return true; }
if (itemsToSmelt.isEmpty() == false) { return true; }
if (itemsToEnchant.isEmpty() == false) { return true; }
if (itemsToBrew.isEmpty() == false) { return true; }
if (itemsToConsume.isEmpty() == false) { return true; }
if (itemsToDeliver.isEmpty() == false) { return true; }
if (citizensToInteract.isEmpty() == false) { return true; }
if (citizensToKill.isEmpty() == false) { return true; }
if (locationsToReach.isEmpty() == false) { return true; }
if (mobsToTame.isEmpty() == false) { return true; }
if (sheepToShear.isEmpty() == false) { return true; }
if (passwordDisplays.isEmpty() == false) { return true; }
if (customObjectives.isEmpty() == false) { return true; }
if (!itemsToCraft.isEmpty()) { return true; }
if (!itemsToSmelt.isEmpty()) { return true; }
if (!itemsToEnchant.isEmpty()) { return true; }
if (!itemsToBrew.isEmpty()) { return true; }
if (!itemsToConsume.isEmpty()) { return true; }
if (!itemsToDeliver.isEmpty()) { return true; }
if (!citizensToInteract.isEmpty()) { return true; }
if (!citizensToKill.isEmpty()) { return true; }
if (!locationsToReach.isEmpty()) { return true; }
if (!mobsToTame.isEmpty()) { return true; }
if (!sheepToShear.isEmpty()) { return true; }
if (!passwordDisplays.isEmpty()) { return true; }
if (!customObjectives.isEmpty()) { return true; }
return false;
}

View File

@ -12,22 +12,6 @@
package me.blackvein.quests.convo.quests.stages;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.StringPrompt;
import org.bukkit.entity.Player;
import me.blackvein.quests.CustomObjective;
import me.blackvein.quests.Quests;
import me.blackvein.quests.actions.Action;
@ -45,6 +29,21 @@ import me.blackvein.quests.util.CK;
import me.blackvein.quests.util.ConfigUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.StringPrompt;
import org.bukkit.entity.Player;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
public class StageMainPrompt extends QuestsEditorNumericPrompt {
private final Quests plugin;
@ -307,16 +306,13 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
return ChatColor.GRAY + "(" + Lang.get("noneSet") + ")";
} else {
String text = "\n";
final LinkedList<LinkedList<String>> passPhrases
= (LinkedList<LinkedList<String>>) context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES);
final LinkedList<String> passPhrases
= (LinkedList<String>) context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES);
final LinkedList<String> passDisplays
= (LinkedList<String>) context.getSessionData(stagePrefix + CK.S_PASSWORD_DISPLAYS);
for (int i = 0; i < passPhrases.size(); i++) {
for (int i = 0; i < passDisplays.size(); i++) {
text += ChatColor.AQUA + " - \"" + passDisplays.get(i) + "\"\n";
final LinkedList<String> phrases = passPhrases.get(i);
for (final String phrase : phrases) {
text += ChatColor.DARK_AQUA + " - " + phrase + "\n";
}
text += ChatColor.DARK_AQUA + " - " + passPhrases.get(i) + "\n";
}
return text;
}
@ -992,7 +988,7 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
return ChatColor.GRAY + " (" + Lang.get("noneSet") + ")";
} else {
String text = "\n";
for (final String display : (List<String>) context.getSessionData(stagePrefix
for (final String display : (List<String>) context.getSessionData(stagePrefix
+ CK.S_PASSWORD_DISPLAYS)) {
text += ChatColor.GRAY + " - " + ChatColor.AQUA + display + "\n";
}
@ -1003,16 +999,9 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
return ChatColor.GRAY + " (" + Lang.get("noneSet") + ")";
} else {
String text = "\n";
for (final LinkedList<String> phraseList : (LinkedList<LinkedList<String>>) context
.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES)) {
text += ChatColor.GRAY + " - ";
for (final String s : phraseList) {
if (phraseList.getLast().equals(s) == false) {
text += ChatColor.DARK_AQUA + s + ChatColor.GRAY + "|";
} else {
text += ChatColor.DARK_AQUA + s + "\n";
}
}
for (final String phrase : (List<String>) context.getSessionData(stagePrefix
+ CK.S_PASSWORD_PHRASES)) {
text += ChatColor.GRAY + " - " + ChatColor.DARK_AQUA + phrase + "\n";
}
return text;
}
@ -1065,8 +1054,7 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
one = 0;
}
if (context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES) != null) {
two = ((LinkedList<LinkedList<String>>) context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES))
.size();
two = ((List<String>) context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES)).size();
} else {
two = 0;
}
@ -1109,11 +1097,10 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
@Override
public Prompt acceptInput(final ConversationContext context, final String input) {
if (input.equalsIgnoreCase(Lang.get("cmdCancel")) == false) {
if (!input.equalsIgnoreCase(Lang.get("cmdCancel"))) {
if (context.getSessionData(stagePrefix + CK.S_PASSWORD_DISPLAYS) != null) {
@SuppressWarnings("unchecked")
final
List<String> displays = (List<String>) context.getSessionData(stagePrefix
final List<String> displays = (List<String>) context.getSessionData(stagePrefix
+ CK.S_PASSWORD_DISPLAYS);
displays.add(input);
context.setSessionData(stagePrefix + CK.S_PASSWORD_DISPLAYS, displays);
@ -1155,22 +1142,16 @@ public class StageMainPrompt extends QuestsEditorNumericPrompt {
@Override
public Prompt acceptInput(final ConversationContext context, final String input) {
if (input.equalsIgnoreCase(Lang.get("cmdCancel")) == false) {
if (!input.equalsIgnoreCase(Lang.get("cmdCancel"))) {
if (context.getSessionData(stagePrefix + CK.S_PASSWORD_PHRASES) != null) {
@SuppressWarnings("unchecked")
final
LinkedList<LinkedList<String>> phrases
= (LinkedList<LinkedList<String>>) context.getSessionData(stagePrefix
final List<String> phrases = (List<String>) context.getSessionData(stagePrefix
+ CK.S_PASSWORD_PHRASES);
final LinkedList<String> newPhrases = new LinkedList<String>();
newPhrases.addAll(Arrays.asList(input.split(Lang.get("charSemi"))));
phrases.add(newPhrases);
phrases.add(input);
context.setSessionData(stagePrefix + CK.S_PASSWORD_PHRASES, phrases);
} else {
final LinkedList<LinkedList<String>> phrases = new LinkedList<LinkedList<String>>();
final LinkedList<String> newPhrases = new LinkedList<String>();
newPhrases.addAll(Arrays.asList(input.split(Lang.get("charSemi"))));
phrases.add(newPhrases);
final List<String> phrases = new LinkedList<String>();
phrases.add(input);
context.setSessionData(stagePrefix + CK.S_PASSWORD_PHRASES, phrases);
}
}

View File

@ -198,7 +198,7 @@ public class CmdExecutor implements CommandExecutor {
if (args.length == 0) {
final Player player = (Player) cs;
final Quester quester = plugin.getQuester(player.getUniqueId());
if (quester.getCurrentQuests().isEmpty() == false) {
if (!quester.getCurrentQuests().isEmpty()) {
for (final Quest q : quester.getCurrentQuests().keySet()) {
final Stage stage = quester.getCurrentStage(q);
q.updateCompass(quester, stage);
@ -1381,7 +1381,7 @@ public class CmdExecutor implements CommandExecutor {
quester.saveData();
quester.updateJournal();
final Storage storage = plugin.getStorage();
storage.deleteQuesterData(id);
storage.deleteQuester(id);
String msg = Lang.get("questReset");
if (target.getName() != null) {
msg = msg.replace("<player>", ChatColor.GREEN + target.getName() + ChatColor.GOLD);

View File

@ -12,13 +12,16 @@
package me.blackvein.quests.listeners;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.util.ItemUtil;
import me.blackvein.quests.util.Lang;
import net.citizensnpcs.api.event.NPCDeathEvent;
import net.citizensnpcs.api.event.NPCLeftClickEvent;
import net.citizensnpcs.api.event.NPCRightClickEvent;
import net.citizensnpcs.api.npc.NPC;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.conversations.Conversation;
@ -33,16 +36,12 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.util.ItemUtil;
import me.blackvein.quests.util.Lang;
import net.citizensnpcs.api.event.NPCDeathEvent;
import net.citizensnpcs.api.event.NPCLeftClickEvent;
import net.citizensnpcs.api.event.NPCRightClickEvent;
import net.citizensnpcs.api.npc.NPC;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
public class NpcListener implements Listener {
@ -186,13 +185,13 @@ public class NpcListener implements Listener {
}
}
}
if (plugin.getQuestNpcs().contains(evt.getNPC()) && delivery == false) {
if (plugin.getQuestNpcs().contains(evt.getNPC())) {
boolean hasObjective = false;
for (final Quest quest : quester.getCurrentQuests().keySet()) {
if (quester.getCurrentStage(quest).containsObjective(ObjectiveType.TALK_TO_NPC)) {
if (quester.getQuestData(quest) != null
&& quester.getQuestData(quest).citizensInteracted.containsKey(evt.getNPC().getId())
&& quester.getQuestData(quest).citizensInteracted.get(evt.getNPC().getId()) == false) {
&& quester.getCurrentStage(quest).getCitizensToInteract().contains(evt.getNPC().getId())
&& !quester.getQuestData(quest).citizensInteracted.get(evt.getNPC().getId())) {
hasObjective = true;
}
quester.interactWithNPC(quest, evt.getNPC());
@ -205,8 +204,8 @@ public class NpcListener implements Listener {
if (quester.getCurrentQuests().containsKey(q))
continue;
if (q.getNpcStart() != null && q.getNpcStart().getId() == evt.getNPC().getId()) {
if (plugin.getSettings().canIgnoreLockedQuests()
&& (quester.getCompletedQuests().contains(q) == false
if (plugin.getSettings().canIgnoreLockedQuests()
&& (!quester.getCompletedQuests().contains(q)
|| q.getPlanner().getCooldown() > -1)) {
if (q.testRequirements(quester)) {
npcQuests.add(q);
@ -214,8 +213,7 @@ public class NpcListener implements Listener {
hasAtLeastOneGUI = true;
}
}
} else if (quester.getCompletedQuests().contains(q) == false
|| q.getPlanner().getCooldown() > -1) {
} else if (!quester.getCompletedQuests().contains(q) || q.getPlanner().getCooldown() > -1) {
npcQuests.add(q);
if (q.getGUIDisplay() != null) {
hasAtLeastOneGUI = true;
@ -223,7 +221,7 @@ public class NpcListener implements Listener {
}
}
}
if (npcQuests.isEmpty() == false && npcQuests.size() == 1) {
if (npcQuests.size() == 1) {
final Quest q = npcQuests.get(0);
if (quester.canAcceptOffer(q, true)) {
quester.setQuestIdToTake(q.getId());
@ -240,17 +238,16 @@ public class NpcListener implements Listener {
}
}
}
} else if (npcQuests.isEmpty() == false && npcQuests.size() > 1) {
if (hasAtLeastOneGUI) {
quester.showGUIDisplay(evt.getNPC(), npcQuests);
} else {
final Conversation c = plugin.getNpcConversationFactory().buildConversation(player);
c.getContext().setSessionData("npcQuests", npcQuests);
c.getContext().setSessionData("npc", evt.getNPC().getName());
c.begin();
}
return;
} else if (npcQuests.isEmpty()) {
} else if (npcQuests.size() > 1) {
if (hasAtLeastOneGUI) {
quester.showGUIDisplay(evt.getNPC(), npcQuests);
} else {
final Conversation c = plugin.getNpcConversationFactory().buildConversation(player);
c.getContext().setSessionData("npcQuests", npcQuests);
c.getContext().setSessionData("npc", evt.getNPC().getName());
c.begin();
}
} else {
evt.getClicker().sendMessage(ChatColor.YELLOW + Lang.get(player, "noMoreQuest"));
}
}
@ -282,39 +279,37 @@ public class NpcListener implements Listener {
final EntityDamageByEntityEvent damageEvent
= (EntityDamageByEntityEvent) evt.getNPC().getEntity().getLastDamageCause();
final Entity damager = damageEvent.getDamager();
if (damager != null) {
if (plugin.getDependencies().getCitizens().getNPCRegistry().isNPC(damager)) {
return;
}
final ObjectiveType type = ObjectiveType.KILL_NPC;
final Set<String> dispatchedQuestIDs = new HashSet<String>();
Player player = null;
if (damager instanceof Projectile
&& evt.getNPC().getEntity().getLastDamageCause().getEntity() instanceof Player) {
player = (Player) evt.getNPC().getEntity().getLastDamageCause().getEntity();
} else if (damager instanceof Player) {
player = (Player) damager;
}
if (player != null) {
final Quester quester = plugin.getQuester(player.getUniqueId());
for (final Quest quest : quester.getCurrentQuests().keySet()) {
if (!quester.meetsCondition(quest, true)) {
continue;
}
if (quester.getCurrentQuests().containsKey(quest)
&& quester.getCurrentStage(quest).containsObjective(type)) {
quester.killNPC(quest, evt.getNPC());
}
dispatchedQuestIDs.addAll(quester.dispatchMultiplayerEverything(quest, type,
(final Quester q, final Quest cq) -> {
if (!dispatchedQuestIDs.contains(cq.getId())) {
q.killNPC(cq, evt.getNPC());
}
return null;
}));
if (plugin.getDependencies().getCitizens().getNPCRegistry().isNPC(damager)) {
return;
}
final ObjectiveType type = ObjectiveType.KILL_NPC;
final Set<String> dispatchedQuestIDs = new HashSet<String>();
Player player = null;
if (damager instanceof Projectile
&& evt.getNPC().getEntity().getLastDamageCause().getEntity() instanceof Player) {
player = (Player) evt.getNPC().getEntity().getLastDamageCause().getEntity();
} else if (damager instanceof Player) {
player = (Player) damager;
}
if (player != null) {
final Quester quester = plugin.getQuester(player.getUniqueId());
for (final Quest quest : quester.getCurrentQuests().keySet()) {
if (!quester.meetsCondition(quest, true)) {
continue;
}
if (quester.getCurrentQuests().containsKey(quest)
&& quester.getCurrentStage(quest).containsObjective(type)) {
quester.killNPC(quest, evt.getNPC());
}
dispatchedQuestIDs.addAll(quester.dispatchMultiplayerEverything(quest, type,
(final Quester q, final Quest cq) -> {
if (!dispatchedQuestIDs.contains(cq.getId())) {
q.killNPC(cq, evt.getNPC());
}
return null;
}));
}
}
}

View File

@ -12,15 +12,15 @@
package me.blackvein.quests.listeners;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListSet;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.Stage;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.util.ItemUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -63,15 +63,12 @@ import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.Stage;
import me.blackvein.quests.enums.ObjectiveType;
import me.blackvein.quests.util.ItemUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import net.citizensnpcs.api.CitizensAPI;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListSet;
public class PlayerListener implements Listener {
@ -215,7 +212,7 @@ public class PlayerListener implements Listener {
final Player player = evt.getPlayer();
if (evt.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
boolean hasObjective = false;
if (evt.isCancelled() == false) {
if (!evt.isCancelled()) {
for (final Quest quest : plugin.getLoadedQuests()) {
if (quester.getCurrentQuests().containsKey(quest)
&& quester.getCurrentStage(quest).containsObjective("useBlock")) {
@ -320,7 +317,7 @@ public class PlayerListener implements Listener {
+ loc.getZ() + ChatColor.GOLD + " (" + ChatColor.GREEN
+ ItemUtil.getName(new ItemStack(block.getType())) + ChatColor.GOLD + ")");
evt.setCancelled(true);
} else if (player.isConversing() == false) {
} else if (!player.isConversing()) {
for (final Quest q : plugin.getLoadedQuests()) {
if (q.getBlockStart() != null) {
if (q.getBlockStart().equals(evt.getClickedBlock().getLocation())) {
@ -445,33 +442,27 @@ public class PlayerListener implements Listener {
if (currentStage == null) {
continue;
}
if (currentStage.getChatActions().isEmpty() == false) {
if (!currentStage.getChatActions().isEmpty()) {
final String chat = evt.getMessage();
for (final String s : currentStage.getChatActions().keySet()) {
if (s.equalsIgnoreCase(chat)) {
if (quester.getQuestData(quest).actionFired.get(s) == null
|| quester.getQuestData(quest).actionFired.get(s) == false) {
new BukkitRunnable() {
@Override
public void run() {
currentStage.getChatActions().get(s).fire(quester, quest);
}
}.runTask(this.plugin);
quester.getQuestData(quest).actionFired.put(s, true);
}
new BukkitRunnable() {
@Override
public void run() {
currentStage.getChatActions().get(s).fire(quester, quest);
}
}.runTask(this.plugin);
}
}
}
final ObjectiveType type = ObjectiveType.PASSWORD;
final Set<String> dispatchedQuestIDs = new HashSet<String>();
if (quester.getCurrentStage(quest).containsObjective(type)) {
for (final LinkedList<String> passes : quester.getCurrentStage(quest).getPasswordPhrases()) {
for (final String pass : passes) {
if (pass.equalsIgnoreCase(evt.getMessage())) {
evt.setCancelled(true);
break;
}
for (final String pass : quester.getCurrentStage(quest).getPasswordPhrases()) {
if (pass.equalsIgnoreCase(evt.getMessage())) {
evt.setCancelled(true);
break;
}
}
quester.sayPassword(quest, evt);
@ -493,7 +484,7 @@ public class PlayerListener implements Listener {
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent evt) {
if (plugin.canUseQuests(evt.getPlayer().getUniqueId())) {
final Quester quester = plugin.getQuester(evt.getPlayer().getUniqueId());
if (quester.getCurrentQuests().isEmpty() == false) {
if (!quester.getCurrentQuests().isEmpty()) {
for (final Quest quest : quester.getCurrentQuests().keySet()) {
if (!quest.getOptions().canAllowCommands()) {
if (!evt.getMessage().startsWith("/quest")) {
@ -512,15 +503,11 @@ public class PlayerListener implements Listener {
+ " on command for quest " + quest.getName());
continue;
}
if (currentStage.getCommandActions().isEmpty() == false) {
if (!currentStage.getCommandActions().isEmpty()) {
final String command = evt.getMessage();
for (final String s : currentStage.getCommandActions().keySet()) {
if (command.equalsIgnoreCase("/" + s)) {
if (quester.getQuestData(quest).actionFired.get(s) == null
|| quester.getQuestData(quest).actionFired.get(s) == false) {
currentStage.getCommandActions().get(s).fire(quester, quest);
quester.getQuestData(quest).actionFired.put(s, true);
}
currentStage.getCommandActions().get(s).fire(quester, quest);
}
}
}
@ -837,7 +824,7 @@ public class PlayerListener implements Listener {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
final CompletableFuture<Quester> cf = plugin.getStorage().loadQuesterData(evt.getPlayer().getUniqueId());
final CompletableFuture<Quester> cf = plugin.getStorage().loadQuester(evt.getPlayer().getUniqueId());
try {
final Quester quester = cf.get();
if (quester == null) {
@ -917,19 +904,14 @@ public class PlayerListener implements Listener {
plugin.getQuestFactory().setSelectingNpcs(temp);
}
final ConcurrentSkipListSet<Quester> temp = (ConcurrentSkipListSet<Quester>) plugin.getOfflineQuesters();
for (final Iterator<Quester> iterator = temp.iterator(); iterator.hasNext();) {
final Quester q = iterator.next();
if (q.getUUID().equals(quester.getUUID())) {
iterator.remove();
}
}
temp.removeIf(q -> q.getUUID().equals(quester.getUUID()));
plugin.setOfflineQuesters(temp);
}
}
@EventHandler
public void onPlayerMove(final PlayerMoveEvent evt) {
if (evt.getPlayer() == null || evt.getTo() == null) {
if (evt.getTo() == null) {
return;
}
if (evt.getFrom().getBlock().equals(evt.getTo().getBlock())) {

View File

@ -12,6 +12,10 @@
package me.blackvein.quests.storage;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.storage.implementation.StorageImplementation;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
@ -19,10 +23,6 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.storage.implementation.StorageImplementation;
public class Storage {
private final Quests plugin;
private final StorageImplementation implementation;
@ -88,27 +88,26 @@ public class Storage {
}
}
public CompletableFuture<Quester> loadQuesterData(final UUID uniqueId) {
public CompletableFuture<Quester> loadQuester(final UUID uniqueId) {
return makeFuture(() -> {
final Quester quester = implementation.loadQuesterData(uniqueId);
return quester;
return implementation.loadQuester(uniqueId);
});
}
public CompletableFuture<Void> saveQuesterData(final Quester quester) {
public CompletableFuture<Void> saveQuester(final Quester quester) {
return makeFuture(() -> {
try {
implementation.saveQuesterData(quester);
implementation.saveQuester(quester);
} catch (final Exception e) {
e.printStackTrace();
}
});
}
public CompletableFuture<Void> deleteQuesterData(final UUID uniqueId) {
public CompletableFuture<Void> deleteQuester(final UUID uniqueId) {
return makeFuture(() -> {
try {
implementation.deleteQuesterData(uniqueId);
implementation.deleteQuester(uniqueId);
} catch (final Exception e) {
e.printStackTrace();
}

View File

@ -12,12 +12,12 @@
package me.blackvein.quests.storage.implementation;
import java.util.Collection;
import java.util.UUID;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import java.util.Collection;
import java.util.UUID;
public interface StorageImplementation {
Quests getPlugin();
@ -27,11 +27,11 @@ public interface StorageImplementation {
void close();
Quester loadQuesterData(UUID uniqueId) throws Exception;
Quester loadQuester(UUID uniqueId) throws Exception;
void saveQuesterData(Quester quester) throws Exception;
void saveQuester(Quester quester) throws Exception;
void deleteQuesterData(UUID uniqueId) throws Exception;
void deleteQuester(UUID uniqueId) throws Exception;
String getQuesterLastKnownName(UUID uniqueId) throws Exception;

View File

@ -12,6 +12,20 @@
package me.blackvein.quests.storage.implementation.file;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.Stage;
import me.blackvein.quests.storage.implementation.StorageImplementation;
import me.blackvein.quests.util.MiscUtil;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
@ -22,24 +36,6 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import me.blackvein.quests.Quest;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.Stage;
import me.blackvein.quests.storage.implementation.StorageImplementation;
import me.blackvein.quests.util.ConfigUtil;
import me.blackvein.quests.util.MiscUtil;
public class SeparatedYamlStorage implements StorageImplementation {
private final Quests plugin;
private final String directoryPath;
@ -72,7 +68,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
@SuppressWarnings("deprecation")
@Override
public Quester loadQuesterData(final UUID uniqueId) throws Exception {
public Quester loadQuester(final UUID uniqueId) throws Exception {
final FileConfiguration data = new YamlConfiguration();
Quester quester = plugin.getQuester(uniqueId);
if (quester != null) {
@ -144,7 +140,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
}
}
quester.setCompletedQuests(completedQuests);
if (data.isString("currentQuests") == false) {
if (!data.isString("currentQuests")) {
final List<String> questIds = data.getStringList("currentQuests");
final List<Integer> questStages = data.getIntegerList("currentStages");
final int maxSize = Math.min(questIds.size(), questStages.size());
@ -166,7 +162,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ConfigurationSection questSec = dataSec.getConfigurationSection(key);
final Quest quest = plugin.getQuestById(key) != null ? plugin.getQuestById(key) : plugin.getQuest(key);
Stage stage;
if (quest == null || quester.getCurrentQuests().containsKey(quest) == false) {
if (quest == null || !quester.getCurrentQuests().containsKey(quest)) {
continue;
}
stage = quester.getCurrentStage(quest);
@ -180,97 +176,67 @@ public class SeparatedYamlStorage implements StorageImplementation {
if (questSec == null) {
continue;
}
if (questSec.contains("blocks-broken-names")) {
final List<String> names = questSec.getStringList("blocks-broken-names");
final List<Integer> amounts = questSec.getIntegerList("blocks-broken-amounts");
final List<Short> durability = questSec.getShortList("blocks-broken-durability");
if (questSec.contains("blocks-broken-amounts")) {
final List<Integer> brokenAmounts = questSec.getIntegerList("blocks-broken-amounts");
int index = 0;
for (final String s : names) {
ItemStack is;
try {
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), durability.get(index));
} catch (final IndexOutOfBoundsException e) {
// Legacy
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), (short) 0);
}
if (quester.getQuestData(quest).blocksBroken.size() > 0) {
quester.getQuestData(quest).blocksBroken.set(index, is);
for (final int amt : brokenAmounts) {
final ItemStack is = quester.getCurrentStage(quest).getBlocksToBreak().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).getBlocksBroken().size() > 0) {
quester.getQuestData(quest).blocksBroken.set(index, temp);
}
index++;
}
}
if (questSec.contains("blocks-damaged-names")) {
final List<String> names = questSec.getStringList("blocks-damaged-names");
final List<Integer> amounts = questSec.getIntegerList("blocks-damaged-amounts");
final List<Short> durability = questSec.getShortList("blocks-damaged-durability");
if (questSec.contains("blocks-damaged-amounts")) {
final List<Integer> damagedAmounts = questSec.getIntegerList("blocks-damaged-amounts");
int index = 0;
for (final String s : names) {
ItemStack is;
try {
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), durability.get(index));
} catch (final IndexOutOfBoundsException e) {
// Legacy
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), (short) 0);
}
if (quester.getQuestData(quest).blocksDamaged.size() > 0) {
quester.getQuestData(quest).blocksDamaged.set(index, is);
for (final int amt : damagedAmounts) {
final ItemStack is = quester.getCurrentStage(quest).getBlocksToDamage().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).getBlocksDamaged().size() > 0) {
quester.getQuestData(quest).blocksDamaged.set(index, temp);
}
index++;
}
}
if (questSec.contains("blocks-placed-names")) {
final List<String> names = questSec.getStringList("blocks-placed-names");
final List<Integer> amounts = questSec.getIntegerList("blocks-placed-amounts");
final List<Short> durability = questSec.getShortList("blocks-placed-durability");
if (questSec.contains("blocks-placed-amounts")) {
final List<Integer> placedAmounts = questSec.getIntegerList("blocks-placed-amounts");
int index = 0;
for (final String s : names) {
ItemStack is;
try {
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), durability.get(index));
} catch (final IndexOutOfBoundsException e) {
// Legacy
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), (short) 0);
}
if (quester.getQuestData(quest).blocksPlaced.size() > 0) {
quester.getQuestData(quest).blocksPlaced.set(index, is);
for (final int amt : placedAmounts) {
final ItemStack is = quester.getCurrentStage(quest).getBlocksToPlace().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).getBlocksPlaced().size() > 0) {
quester.getQuestData(quest).blocksPlaced.set(index, temp);
}
index++;
}
}
if (questSec.contains("blocks-used-names")) {
final List<String> names = questSec.getStringList("blocks-used-names");
final List<Integer> amounts = questSec.getIntegerList("blocks-used-amounts");
final List<Short> durability = questSec.getShortList("blocks-used-durability");
if (questSec.contains("blocks-used-amounts")) {
final List<Integer> usedAmounts = questSec.getIntegerList("blocks-used-amounts");
int index = 0;
for (final String s : names) {
ItemStack is;
try {
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), durability.get(index));
} catch (final IndexOutOfBoundsException e) {
// Legacy
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), (short) 0);
}
if (quester.getQuestData(quest).blocksUsed.size() > 0) {
quester.getQuestData(quest).blocksUsed.set(index, is);
for (final int amt : usedAmounts) {
final ItemStack is = quester.getCurrentStage(quest).getBlocksToUse().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).getBlocksUsed().size() > 0) {
quester.getQuestData(quest).blocksUsed.set(index, temp);
}
index++;
}
}
if (questSec.contains("blocks-cut-names")) {
final List<String> names = questSec.getStringList("blocks-cut-names");
final List<Integer> amounts = questSec.getIntegerList("blocks-cut-amounts");
final List<Short> durability = questSec.getShortList("blocks-cut-durability");
if (questSec.contains("blocks-cut-amounts")) {
final List<Integer> cutAmounts = questSec.getIntegerList("blocks-cut-amounts");
int index = 0;
for (final String s : names) {
ItemStack is;
try {
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), durability.get(index));
} catch (final IndexOutOfBoundsException e) {
// Legacy
is = new ItemStack(Material.matchMaterial(s), amounts.get(index), (short) 0);
}
if (quester.getQuestData(quest).blocksCut.size() > 0) {
quester.getQuestData(quest).blocksCut.set(index, is);
for (final int amt : cutAmounts) {
final ItemStack is = quester.getCurrentStage(quest).getBlocksToCut().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).getBlocksCut().size() > 0) {
quester.getQuestData(quest).blocksCut.set(index, temp);
}
index++;
}
@ -282,7 +248,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack is = quester.getCurrentStage(quest).getItemsToCraft().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).itemsCrafted.size() > 0) {
if (quester.getQuestData(quest).getItemsCrafted().size() > 0) {
quester.getQuestData(quest).itemsCrafted.set(index, temp);
}
index++;
@ -295,7 +261,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack is = quester.getCurrentStage(quest).getItemsToSmelt().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).itemsSmelted.size() > 0) {
if (quester.getQuestData(quest).getItemsSmelted().size() > 0) {
quester.getQuestData(quest).itemsSmelted.set(index, temp);
}
index++;
@ -308,7 +274,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack is = quester.getCurrentStage(quest).getItemsToEnchant().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).itemsEnchanted.size() > 0) {
if (quester.getQuestData(quest).getItemsEnchanted().size() > 0) {
quester.getQuestData(quest).itemsEnchanted.set(index, temp);
}
index++;
@ -321,7 +287,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack is = quester.getCurrentStage(quest).getItemsToBrew().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).itemsBrewed.size() > 0) {
if (quester.getQuestData(quest).getItemsBrewed().size() > 0) {
quester.getQuestData(quest).itemsBrewed.set(index, temp);
}
index++;
@ -334,7 +300,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack is = quester.getCurrentStage(quest).getItemsToConsume().get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
if (quester.getQuestData(quest).itemsConsumed.size() > 0) {
if (quester.getQuestData(quest).getItemsConsumed().size() > 0) {
quester.getQuestData(quest).itemsConsumed.set(index, temp);
}
index++;
@ -349,27 +315,24 @@ public class SeparatedYamlStorage implements StorageImplementation {
final ItemStack temp = new ItemStack(is.getType(), amt, is.getDurability());
temp.addUnsafeEnchantments(is.getEnchantments());
temp.setItemMeta(is.getItemMeta());
if (quester.getQuestData(quest).itemsDelivered.size() > 0) {
if (quester.getQuestData(quest).getItemsDelivered().size() > 0) {
quester.getQuestData(quest).itemsDelivered.set(index, temp);
}
index++;
}
}
if (questSec.contains("citizen-ids-to-talk-to")) {
final List<Integer> ids = questSec.getIntegerList("citizen-ids-to-talk-to");
final List<Boolean> has = questSec.getBooleanList("has-talked-to");
for (final int i : ids) {
quester.getQuestData(quest).citizensInteracted.put(i, has.get(ids.indexOf(i)));
}
if (questSec.contains("has-talked-to")) {
final List<Boolean> talkAmount = questSec.getBooleanList("has-talked-to");
quester.getQuestData(quest).setCitizensInteracted(new LinkedList<Boolean>(talkAmount));
}
if (questSec.contains("citizen-ids-killed")) {
final List<Integer> ids = questSec.getIntegerList("citizen-ids-killed");
final List<Integer> num = questSec.getIntegerList("citizen-amounts-killed");
quester.getQuestData(quest).citizensKilled.clear();
quester.getQuestData(quest).citizenNumKilled.clear();
quester.getQuestData(quest).citizensIdsKilled.clear();
quester.getQuestData(quest).citizensNumKilled.clear();
for (final int i : ids) {
quester.getQuestData(quest).citizensKilled.add(i);
quester.getQuestData(quest).citizenNumKilled.add(num.get(ids.indexOf(i)));
quester.getQuestData(quest).citizensIdsKilled.add(i);
quester.getQuestData(quest).citizensNumKilled.add(num.get(ids.indexOf(i)));
}
}
if (questSec.contains("cows-milked")) {
@ -389,114 +352,44 @@ public class SeparatedYamlStorage implements StorageImplementation {
if (mob != null) {
mobs.add(mob);
}
quester.getQuestData(quest).mobsKilled.clear();
quester.getQuestData(quest).mobTypesKilled.clear();
quester.getQuestData(quest).mobNumKilled.clear();
for (final EntityType e : mobs) {
quester.getQuestData(quest).mobsKilled.add(e);
quester.getQuestData(quest).mobTypesKilled.add(e);
quester.getQuestData(quest).mobNumKilled.add(amounts.get(mobs.indexOf(e)));
}
if (questSec.contains("mob-kill-locations")) {
final LinkedList<Location> locations = new LinkedList<Location>();
final List<Integer> radii = questSec.getIntegerList("mob-kill-location-radii");
for (final String loc : questSec.getStringList("mob-kill-locations")) {
if (ConfigUtil.getLocation(loc) != null) {
locations.add(ConfigUtil.getLocation(loc));
}
}
quester.getQuestData(quest).locationsToKillWithin = locations;
quester.getQuestData(quest).radiiToKillWithin.clear();
for (final int i : radii) {
quester.getQuestData(quest).radiiToKillWithin.add(i);
}
}
}
}
if (questSec.contains("locations-to-reach")) {
final LinkedList<Location> locations = new LinkedList<Location>();
final List<Boolean> has = questSec.getBooleanList("has-reached-location");
while (has.size() < locations.size()) {
// TODO - Find proper cause of Github issues #646 and #825
plugin.getLogger().info("Added missing has-reached-location data for Quester " + uniqueId);
has.add(false);
}
final List<Integer> radii = questSec.getIntegerList("radii-to-reach-within");
for (final String loc : questSec.getStringList("locations-to-reach")) {
if (ConfigUtil.getLocation(loc) != null) {
locations.add(ConfigUtil.getLocation(loc));
}
}
quester.getQuestData(quest).locationsReached = locations;
quester.getQuestData(quest).hasReached.clear();
quester.getQuestData(quest).radiiToReachWithin.clear();
for (final boolean b : has) {
quester.getQuestData(quest).hasReached.add(b);
}
for (final int i : radii) {
quester.getQuestData(quest).radiiToReachWithin.add(i);
}
final List<Boolean> hasReached = questSec.getBooleanList("has-reached-location");
quester.getQuestData(quest).setLocationsReached(new LinkedList<Boolean>(hasReached));
}
if (questSec.contains("mobs-to-tame")) {
final List<String> mobs = questSec.getStringList("mobs-to-tame");
final List<Integer> amounts = questSec.getIntegerList("mob-tame-amounts");
for (final String mob : mobs) {
quester.getQuestData(quest).mobsTamed.put(EntityType.valueOf(mob.toUpperCase()), amounts
.get(mobs.indexOf(mob)));
}
if (questSec.contains("mob-tame-amounts")) {
final List<Integer> tameAmounts = questSec.getIntegerList("mob-tame-amounts");
quester.getQuestData(quest).setMobsTamed(new LinkedList<Integer>(tameAmounts));
}
if (questSec.contains("sheep-to-shear")) {
final List<String> colors = questSec.getStringList("sheep-to-shear");
final List<Integer> amounts = questSec.getIntegerList("sheep-sheared");
for (final String color : colors) {
quester.getQuestData(quest).sheepSheared.put(MiscUtil.getProperDyeColor(color), amounts.get(colors
.indexOf(color)));
}
if (questSec.contains("sheep-sheared")) {
final List<Integer> sheepAmounts = questSec.getIntegerList("sheep-sheared");
quester.getQuestData(quest).setSheepSheared(new LinkedList<Integer>(sheepAmounts));
}
if (questSec.contains("passwords")) {
final List<String> passwords = questSec.getStringList("passwords");
final List<Boolean> said = questSec.getBooleanList("passwords-said");
for (int i = 0; i < passwords.size(); i++) {
quester.getQuestData(quest).passwordsSaid.put(passwords.get(i), said.get(i));
}
if (questSec.contains("passwords-said")) {
final List<Boolean> passAmounts = questSec.getBooleanList("passwords-said");
quester.getQuestData(quest).setPasswordsSaid(new LinkedList<Boolean>(passAmounts));
}
if (questSec.contains("custom-objectives")) {
final List<String> customObj = questSec.getStringList("custom-objectives");
final List<Integer> customObjCount = questSec.getIntegerList("custom-objective-counts");
for (int i = 0; i < customObj.size(); i++) {
quester.getQuestData(quest).customObjectiveCounts.put(customObj.get(i), customObjCount.get(i));
}
quester.getQuestData(quest).setCustomObjectiveCounts(new LinkedList<Integer>(customObjCount));
}
if (questSec.contains("stage-delay")) {
quester.getQuestData(quest).setDelayTimeLeft(questSec.getLong("stage-delay"));
}
if (quester.getCurrentStage(quest).getChatActions().isEmpty() == false) {
for (final String chatTrig : quester.getCurrentStage(quest).getChatActions().keySet()) {
quester.getQuestData(quest).actionFired.put(chatTrig, false);
}
}
if (questSec.contains("chat-triggers")) {
final List<String> chatTriggers = questSec.getStringList("chat-triggers");
for (final String s : chatTriggers) {
quester.getQuestData(quest).actionFired.put(s, true);
}
}
if (quester.getCurrentStage(quest).getCommandActions().isEmpty() == false) {
for (final String commandTrig : quester.getCurrentStage(quest).getCommandActions().keySet()) {
quester.getQuestData(quest).actionFired.put(commandTrig, false);
}
}
if (questSec.contains("command-triggers")) {
final List<String> commandTriggers = questSec.getStringList("command-triggers");
for (final String s : commandTriggers) {
quester.getQuestData(quest).actionFired.put(s, true);
}
}
}
}
return quester;
}
@Override
public void saveQuesterData(final Quester quester) throws Exception {
public void saveQuester(final Quester quester) throws Exception {
final FileConfiguration data = quester.getBaseData();
try {
data.save(new File(directoryPath + File.separator + quester.getUUID() + ".yml"));
@ -506,7 +399,7 @@ public class SeparatedYamlStorage implements StorageImplementation {
}
@Override
public void deleteQuesterData(final UUID uniqueId) throws Exception {
public void deleteQuester(final UUID uniqueId) throws Exception {
final File f = new File(directoryPath + File.separator + uniqueId + ".yml");
f.delete();
}
@ -535,19 +428,20 @@ public class SeparatedYamlStorage implements StorageImplementation {
return name.endsWith(".yml");
}
});
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
final String name = listOfFiles[i].getName().substring(0, listOfFiles[i].getName().lastIndexOf("."));
if (listOfFiles == null) {
return ids;
}
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
final String name = listOfFile.getName().substring(0, listOfFile.getName().lastIndexOf("."));
UUID id = null;
try {
id = UUID.fromString(name);
} catch (final IllegalArgumentException e) {
continue;
}
if (id != null) {
ids.add(id);
}
ids.add(id);
}
}
return ids;

View File

@ -13,10 +13,12 @@
package me.blackvein.quests.storage.implementation.sql;
import me.blackvein.quests.Quest;
import me.blackvein.quests.QuestData;
import me.blackvein.quests.Quester;
import me.blackvein.quests.Quests;
import me.blackvein.quests.storage.implementation.StorageImplementation;
import me.blackvein.quests.storage.implementation.sql.connection.ConnectionFactory;
import org.bukkit.inventory.ItemStack;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -24,6 +26,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
@ -59,6 +62,43 @@ public class SqlStorage implements StorageImplementation {
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE uuid=uuid, questid=questid, lasttime=VALUES(lasttime), amount=VALUES(amount)";
private static final String PLAYER_REDOABLE_QUESTS_DELETE = "DELETE FROM '{prefix}player_redoablequests' WHERE uuid=?";
private static final String PLAYER_QUEST_DATA_SELECT_BY_UUID = "SELECT * FROM '{prefix}player_questdata' WHERE uuid=?";
private static final String PLAYER_QUEST_DATA_DELETE_FOR_UUID_AND_QUEST = "DELETE FROM '{prefix}player_questdata' WHERE uuid=? AND quest_id=?";
private static final String PLAYER_QUEST_DATA_INSERT = "INSERT INTO '{prefix}player_questdata'"
+ " (uuid, quest_id, blocks_broken, blocks_damaged, blocks_placed, blocks_used, blocks_cut,"
+ " items_crafted, items_smelted, items_enchanted, items_brewed, items_consumed,"
+ " items_delivered, npcs_interacted, npcs_killed,"
+ " mobs_killed, mobs_tamed, fish_caught, cows_milked, sheep_sheared,"
+ " players_killed, locations_reached, passwords_said, custom_counts,"
+ " delay_start_time, delay_time_left)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
+ " ON DUPLICATE KEY UPDATE uuid=uuid, quest_id=quest_id,"
+ " blocks_broken=VALUES(blocks_broken),"
+ " blocks_damaged=VALUES(blocks_damaged),"
+ " blocks_placed=VALUES(blocks_placed),"
+ " blocks_used=VALUES(blocks_used),"
+ " blocks_cut=VALUES(blocks_cut),"
+ " items_crafted=VALUES(items_crafted),"
+ " items_smelted=VALUES(items_smelted),"
+ " items_enchanted=VALUES(items_enchanted),"
+ " items_brewed=VALUES(items_brewed),"
+ " items_consumed=VALUES(items_consumed),"
+ " items_delivered=VALUES(items_delivered),"
+ " npcs_interacted=VALUES(npcs_interacted),"
+ " npcs_killed=VALUES(npcs_killed),"
+ " mobs_killed=VALUES(mobs_killed),"
+ " mobs_tamed=VALUES(mobs_tamed),"
+ " fish_caught=VALUES(fish_caught),"
+ " cows_milked=VALUES(cows_milked),"
+ " sheep_sheared=VALUES(sheep_sheared),"
+ " players_killed=VALUES(players_killed),"
+ " locations_reached=VALUES(locations_reached),"
+ " passwords_said=VALUES(passwords_said),"
+ " custom_counts=VALUES(custom_counts),"
+ " delay_start_time=VALUES(delay_start_time),"
+ " delay_time_left=VALUES(delay_time_left)";
private static final String PLAYER_QUEST_DATA_DELETE = "DELETE FROM '{prefix}player_questdata' WHERE uuid=?";
private final Quests plugin;
private final ConnectionFactory connectionFactory;
private final Function<String, String> statementProcessor;
@ -92,7 +132,7 @@ public class SqlStorage implements StorageImplementation {
connectionFactory.init(plugin);
try (Connection c = connectionFactory.getConnection()) {
final String[] queries = new String[4];
final String[] queries = new String[5];
queries[0] = "CREATE TABLE IF NOT EXISTS `" + statementProcessor.apply("{prefix}players")
+ "` (`uuid` VARCHAR(36) NOT NULL, "
+ "`lastknownname` VARCHAR(16) NOT NULL, "
@ -123,6 +163,37 @@ public class SqlStorage implements StorageImplementation {
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY (`uuid`, `questid`)"
+ ") DEFAULT CHARSET = utf8mb4";
queries[4] = "CREATE TABLE IF NOT EXISTS `" + statementProcessor.apply("{prefix}player_questdata")
+ "` (id INT AUTO_INCREMENT NOT NULL,"
+ "`uuid` VARCHAR(36) NOT NULL, "
+ "`quest_id` VARCHAR(100) NOT NULL,"
+ "`blocks_broken` VARCHAR(100) NULL,"
+ "`blocks_damaged` VARCHAR(100) NULL,"
+ "`blocks_placed` VARCHAR(100) NULL,"
+ "`blocks_used` VARCHAR(100) NULL,"
+ "`blocks_cut` VARCHAR(100) NULL,"
+ "`items_crafted` VARCHAR(100) NULL,"
+ "`items_smelted` VARCHAR(100) NULL,"
+ "`items_enchanted` VARCHAR(100) NULL,"
+ "`items_brewed` VARCHAR(100) NULL,"
+ "`items_consumed` VARCHAR(100) NULL,"
+ "`items_delivered` VARCHAR(100) NULL,"
+ "`npcs_interacted` VARCHAR(100) NULL,"
+ "`npcs_killed` VARCHAR(100) NULL,"
+ "`mobs_killed` INT NULL,"
+ "`mobs_tamed` INT NULL,"
+ "`fish_caught` INT NULL,"
+ "`cows_milked` INT NULL,"
+ "`sheep_sheared` INT NULL,"
+ "`players_killed` INT NULL,"
+ "`locations_reached` VARCHAR(100) NULL,"
+ "`passwords_said` VARCHAR(100) NULL,"
+ "`custom_counts` INT NULL,"
+ "`delay_start_time` BIGINT NULL,"
+ "`delay_time_left` BIGINT NULL,"
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY (`uuid`, `quest_id`)"
+ ") DEFAULT CHARSET = utf8mb4";
try (Statement s = c.createStatement()) {
for (final String query : queries) {
try {
@ -150,7 +221,7 @@ public class SqlStorage implements StorageImplementation {
}
@Override
public Quester loadQuesterData(final UUID uniqueId) throws Exception {
public Quester loadQuester(final UUID uniqueId) throws Exception {
final Quester quester = plugin.getQuester(uniqueId);
if (quester == null) {
return null;
@ -170,13 +241,14 @@ public class SqlStorage implements StorageImplementation {
quester.setCompletedQuests(getQuesterCompletedQuests(uniqueId));
quester.setCompletedTimes(getQuesterCompletedTimes(uniqueId));
quester.setAmountsCompleted(getQuesterAmountsCompleted(uniqueId));
quester.setQuestData(getQuesterQuestData(uniqueId));
}
}
return quester;
}
@Override
public void saveQuesterData(final Quester quester) throws Exception {
public void saveQuester(final Quester quester) throws Exception {
final UUID uniqueId = quester.getUUID();
final String lastKnownName = quester.getLastKnownName();
final String oldLastKnownName = getQuesterLastKnownName(uniqueId);
@ -189,6 +261,9 @@ public class SqlStorage implements StorageImplementation {
final Set<String> redoableQuests = quester.getCompletedTimes().keySet().stream().map(Quest::getId).collect(Collectors.toSet());
final Set<String> oldRedoableQuests = getQuesterCompletedTimes(uniqueId).keySet().stream().map(Quest::getId).collect(Collectors.toSet());
oldRedoableQuests.removeAll(redoableQuests);
final Set<String> questData = quester.getQuestData().keySet().stream().map(Quest::getId).collect(Collectors.toSet());
final Set<String> oldQuestData = getQuesterQuestData(uniqueId).keySet().stream().map(Quest::getId).collect(Collectors.toSet());
oldQuestData.removeAll(questData);
try (final Connection c = connectionFactory.getConnection()) {
if (oldLastKnownName != null && lastKnownName != null && !lastKnownName.equals(oldLastKnownName)) {
@ -263,11 +338,53 @@ public class SqlStorage implements StorageImplementation {
}
}
}
if (!oldQuestData.isEmpty()) {
for (final String questId : oldQuestData) {
try (PreparedStatement ps = c.prepareStatement(statementProcessor.apply(PLAYER_QUEST_DATA_DELETE_FOR_UUID_AND_QUEST))) {
ps.setString(1, uniqueId.toString());
ps.setString(2, questId);
ps.execute();
}
}
} else {
for (final Entry<Quest, QuestData> entry : quester.getQuestData().entrySet()) {
try (PreparedStatement ps = c.prepareStatement(statementProcessor.apply(PLAYER_QUEST_DATA_INSERT))) {
ps.setString(1, uniqueId.toString());
ps.setString(2, entry.getKey().getId());
ps.setString(3, serializeItemStackProgress(entry.getValue().getBlocksBroken()));
ps.setString(4, serializeItemStackProgress(entry.getValue().getBlocksDamaged()));
ps.setString(5, serializeItemStackProgress(entry.getValue().getBlocksPlaced()));
ps.setString(6, serializeItemStackProgress(entry.getValue().getBlocksUsed()));
ps.setString(7, serializeItemStackProgress(entry.getValue().getBlocksCut()));
ps.setString(8, serializeItemStackProgress(entry.getValue().getItemsCrafted()));
ps.setString(9, serializeItemStackProgress(entry.getValue().getItemsSmelted()));
ps.setString(10, serializeItemStackProgress(entry.getValue().getItemsEnchanted()));
ps.setString(11, serializeItemStackProgress(entry.getValue().getItemsBrewed()));
ps.setString(12, serializeItemStackProgress(entry.getValue().getItemsConsumed()));
ps.setString(13, serializeItemStackProgress(entry.getValue().getItemsDelivered()));
ps.setString(14, serializeProgress(entry.getValue().getCitizensInteracted()));
ps.setString(15, serializeProgress(entry.getValue().getCitizensNumKilled()));
ps.setString(16, serializeProgress(entry.getValue().getMobNumKilled()));
ps.setString(17, serializeProgress(entry.getValue().getMobsTamed()));
ps.setInt(18, entry.getValue().getFishCaught());
ps.setInt(19, entry.getValue().getCowsMilked());
ps.setString(20, serializeProgress(entry.getValue().getSheepSheared()));
ps.setInt(21, entry.getValue().getPlayersKilled());
ps.setString(22, serializeProgress(entry.getValue().getLocationsReached()));
ps.setString(23, serializeProgress(entry.getValue().getPasswordsSaid()));
ps.setString(24, serializeProgress(entry.getValue().getCustomObjectiveCounts()));
ps.setLong(25, entry.getValue().getDelayStartTime());
ps.setLong(26, entry.getValue().getDelayTimeLeft());
ps.execute();
}
}
}
}
}
@Override
public void deleteQuesterData(final UUID uniqueId) throws Exception {
public void deleteQuester(final UUID uniqueId) throws Exception {
try (Connection c = connectionFactory.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(statementProcessor.apply(PLAYER_DELETE))) {
ps.setString(1, uniqueId.toString());
@ -285,6 +402,10 @@ public class SqlStorage implements StorageImplementation {
ps.setString(1, uniqueId.toString());
ps.execute();
}
try (PreparedStatement ps = c.prepareStatement(statementProcessor.apply(PLAYER_QUEST_DATA_DELETE))) {
ps.setString(1, uniqueId.toString());
ps.execute();
}
}
}
@ -320,6 +441,62 @@ public class SqlStorage implements StorageImplementation {
}
return currentQuests;
}
@SuppressWarnings("unchecked")
public ConcurrentHashMap<Quest, QuestData> getQuesterQuestData(final UUID uniqueId) throws Exception {
final Quester quester = plugin.getQuester(uniqueId);
final ConcurrentHashMap<Quest, QuestData> questData = new ConcurrentHashMap<Quest, QuestData>();
try (Connection c = connectionFactory.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(statementProcessor.apply(PLAYER_QUEST_DATA_SELECT_BY_UUID))) {
ps.setString(1, uniqueId.toString());
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
final Quest quest = plugin.getQuestById(rs.getString("quest_id"));
QuestData data = new QuestData(quester);
if (quest != null && quester.getCurrentStage(quest) != null) {
data.blocksBroken.addAll(deserializeItemStackProgress(rs.getString("blocks_broken"),
quester.getCurrentStage(quest).getBlocksToBreak()));
data.blocksDamaged.addAll(deserializeItemStackProgress(rs.getString("blocks_damaged"),
quester.getCurrentStage(quest).getBlocksToDamage()));
data.blocksPlaced.addAll(deserializeItemStackProgress(rs.getString("blocks_placed"),
quester.getCurrentStage(quest).getBlocksToPlace()));
data.blocksUsed.addAll(deserializeItemStackProgress(rs.getString("blocks_used"),
quester.getCurrentStage(quest).getBlocksToUse()));
data.blocksCut.addAll(deserializeItemStackProgress(rs.getString("blocks_cut"),
quester.getCurrentStage(quest).getBlocksToCut()));
data.itemsCrafted.addAll(deserializeItemStackProgress(rs.getString("items_crafted"),
quester.getCurrentStage(quest).getItemsToCraft()));
data.itemsSmelted.addAll(deserializeItemStackProgress(rs.getString("items_smelted"),
quester.getCurrentStage(quest).getItemsToSmelt()));
data.itemsEnchanted.addAll(deserializeItemStackProgress(rs.getString("items_enchanted"),
quester.getCurrentStage(quest).getItemsToEnchant()));
data.itemsBrewed.addAll(deserializeItemStackProgress(rs.getString("items_brewed"),
quester.getCurrentStage(quest).getItemsToBrew()));
data.itemsConsumed.addAll(deserializeItemStackProgress(rs.getString("items_consumed"),
quester.getCurrentStage(quest).getItemsToConsume()));
data.itemsDelivered.addAll(deserializeItemStackProgress(rs.getString("items_delivered"),
quester.getCurrentStage(quest).getItemsToDeliver()));
data.citizensInteracted.addAll(deserializeBooleanProgress(rs.getString("npcs_interacted")));
data.citizensNumKilled.addAll(deserializeIntProgress(rs.getString("npcs_killed")));
data.mobNumKilled.addAll(deserializeIntProgress(rs.getString("mobs_killed")));
data.mobsTamed.addAll(deserializeIntProgress(rs.getString("mobs_tamed")));
data.setFishCaught(rs.getInt("fish_caught"));
data.setCowsMilked(rs.getInt("cows_milked"));
data.sheepSheared.addAll(deserializeIntProgress(rs.getString("sheep_sheared")));
data.setPlayersKilled(rs.getInt("players_killed"));
data.locationsReached.addAll(deserializeBooleanProgress(rs.getString("locations_reached")));
data.passwordsSaid.addAll(deserializeBooleanProgress(rs.getString("passwords_said")));
data.customObjectiveCounts.addAll(deserializeIntProgress(rs.getString("custom_counts")));
data.setDelayStartTime(rs.getLong("delay_start_time"));
data.setDelayTimeLeft(rs.getLong("delay_time_left"));
questData.put(quest, data);
}
}
}
}
}
return questData;
}
public ConcurrentSkipListSet<Quest> getQuesterCompletedQuests(final UUID uniqueId) throws Exception {
final ConcurrentSkipListSet<Quest> completedQuests = new ConcurrentSkipListSet<Quest>();
@ -388,13 +565,70 @@ public class SqlStorage implements StorageImplementation {
} catch (final IllegalArgumentException e) {
continue;
}
if (id != null) {
ids.add(id);
}
ids.add(id);
}
}
}
}
return ids;
}
public String serializeProgress(LinkedList<?> list) {
if (list.isEmpty()) {
return null;
} else if (list.size() == 1) {
return String.valueOf(list.get(0));
} else {
return list.stream().map(String::valueOf).collect(Collectors.joining(",", "{", "}"));
}
}
public LinkedList<Integer> deserializeIntProgress(String string) {
LinkedList<Integer> list = new LinkedList<Integer>();
if (string != null) {
string = string.replace("{", "").replace("}", "");
for (String section : string.split(",")) {
list.add(Integer.parseInt(section));
}
}
return list;
}
public LinkedList<Boolean> deserializeBooleanProgress(String string) {
LinkedList<Boolean> list = new LinkedList<Boolean>();
if (string != null) {
string = string.replace("{", "").replace("}", "");
for (String section : string.split(",")) {
list.add(Boolean.parseBoolean(section));
}
}
return list;
}
public String serializeItemStackProgress(LinkedList<ItemStack> list) {
if (list.isEmpty()) {
return null;
} else if (list.size() == 1) {
return String.valueOf(list.get(0).getAmount());
} else {
return list.stream().map(n -> String.valueOf(n.getAmount())).collect(Collectors.joining(",", "{", "}"));
}
}
public LinkedList<ItemStack> deserializeItemStackProgress(String string, LinkedList<ItemStack> objective) {
LinkedList<ItemStack> list = new LinkedList<ItemStack>();
if (string != null) {
string = string.replace("{", "").replace("}", "");
int index = 0;
for (String section : string.split(",")) {
int amt = Integer.parseInt(section);
final ItemStack is = objective.get(index);
final ItemStack temp = is.clone();
temp.setAmount(amt);
list.add(temp);
index++;
}
}
return list;
}
}

View File

@ -12,14 +12,6 @@
package me.blackvein.quests.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
@ -35,9 +27,54 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@SuppressWarnings("deprecation")
public class ItemUtil {
/*public static String toBase64(ItemStack itemStack) {
if (itemStack == null) {
return null;
}
try {
final ByteArrayOutputStream io = new ByteArrayOutputStream();
final BukkitObjectOutputStream os = new BukkitObjectOutputStream(io);
os.writeObject(itemStack);
os.flush();
final byte[] serializedObject = io.toByteArray();
return Base64.getEncoder().encodeToString(serializedObject);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static ItemStack fromBase64(String encodedObject) {
if (encodedObject == null) {
return null;
}
final byte[] serializedObject = Base64.getDecoder().decode(encodedObject);
try {
final ByteArrayInputStream in = new ByteArrayInputStream((serializedObject));
final BukkitObjectInputStream is = new BukkitObjectInputStream(in);
final Object object = is.readObject();
if (object instanceof ItemStack) {
return (ItemStack)object;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}*/
/**
* Compare two stacks by name, amount, durability, display name, lore, enchantments, stored enchants and item flags
*
@ -199,14 +236,25 @@ public class ItemUtil {
* @return ItemStack, or null if invalid format
*/
public static ItemStack processItemStack(final String material, final int amount, final short durability) {
if (material == null) {
return null;
}
try {
return new ItemStack(Material.getMaterial(material.toUpperCase()), amount, durability);
final Material mat = Material.getMaterial(material.toUpperCase());
if (mat == null) {
return null;
}
return new ItemStack(mat, amount, durability);
} catch (final Exception e) {
try {
Bukkit.getLogger().warning(material + " x " + amount
+ " is invalid! You may need to update your quests.yml or actions.yml "
+ "in accordance with https://bit.ly/2BkBNNN");
return new ItemStack(Material.matchMaterial(material, true), amount, durability);
final Material mat = Material.matchMaterial(material, true);
if (mat == null) {
return null;
}
return new ItemStack(mat, amount, durability);
} catch (final Exception e2) {
Bukkit.getLogger().severe("Unable to use LEGACY_" + material + " as item name");
e2.printStackTrace();
@ -217,11 +265,12 @@ public class ItemUtil {
/**
* Get ItemStack from formatted string. See serialize() for reverse function.
*
*
* <p>Supplied format = name-name:amount-amount:data-data:enchantment-enchantment level:displayname-displayname
* :lore-lore
* <p>May continue with extraneous data such as :ItemFlags-flags:stored-enchants:{enc, level}:internal-hashstring
*
*
* @deprecated Legacy code, do not use
* @param data formatted string
* @return ItemStack, or null if invalid format
*/
@ -265,7 +314,7 @@ public class ItemUtil {
if (e != null) {
enchs.put(e, Integer.parseInt(temp[1]));
} else {
Bukkit.getLogger().severe("Legacy enchantment name \'" + temp[0] + "\' on " + name
Bukkit.getLogger().severe("Legacy enchantment name \'" + temp[0] + "\' on " + name
+ " is invalid. Make sure it is spelled correctly");
}
} else {
@ -273,12 +322,12 @@ public class ItemUtil {
if (Enchantment.getByName(temp[0]) != null) {
enchs.put(Enchantment.getByName(temp[0]), Integer.parseInt(temp[1]));
} else {
Bukkit.getLogger().severe("Enum enchantment name \'" + temp[0] + "\' on " + name
Bukkit.getLogger().severe("Enum enchantment name \'" + temp[0] + "\' on " + name
+ " is invalid. Make sure it is spelled correctly");
}
}
} catch (final Exception e) {
Bukkit.getLogger().severe("The enchantment name \'" + temp[0] + "\' on " + name
Bukkit.getLogger().severe("The enchantment name \'" + temp[0] + "\' on " + name
+ " is invalid. Make sure quests.yml is UTF-8 encoded");
return null;
}
@ -309,7 +358,7 @@ public class ItemUtil {
final int dash = arg.lastIndexOf('-');
final String key = arg.substring(0, dash);
final String value = arg.substring(dash + 1);
int i = -1;
try {
// Num such as book generation
@ -317,7 +366,7 @@ public class ItemUtil {
} catch (final NumberFormatException e) {
// Do nothing
}
if (i > -1) {
extra.put(key, i);
} else if (value.startsWith("[") && value.endsWith("]")) {
@ -433,10 +482,11 @@ public class ItemUtil {
/**
* Get formatted string from ItemStack. See readItemStack() for reverse function.
*
*
* <p>Returned format = name-name:amount-amount:data-data:enchantment-enchantment level:displayname-displayname
* :lore-lore:
*
*
* @deprecated Legacy code, do not use
* @param is ItemStack
* @return formatted string, or null if invalid stack
*/
@ -465,10 +515,10 @@ public class ItemUtil {
serial += ":lore-" + s;
}
}
final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
map.putAll(meta.serialize());
if (map.containsKey("lore")) {
map.remove("lore");
}
@ -481,11 +531,11 @@ public class ItemUtil {
}
return serial;
}
/**
* Essentially the reverse of ItemMeta.serialize()
*
* @param ItemMeta class, key/value map of metadata
* @param itemMetaClass key/value map of metadata
* @return ItemMeta
*/
public static ItemMeta deserializeItemMeta(final Class<? extends ItemMeta> itemMetaClass, final Map<String, Object> args) {
@ -516,7 +566,7 @@ public class ItemUtil {
if (is.getDurability() != 0) {
text += ChatColor.AQUA + ":" + is.getDurability();
}
if (is.getEnchantments().isEmpty() == false) {
if (!is.getEnchantments().isEmpty()) {
text += " " + ChatColor.GRAY + Lang.get("with") + ChatColor.DARK_PURPLE;
for (final Entry<Enchantment, Integer> e : is.getEnchantments().entrySet()) {
text += " " + ItemUtil.getPrettyEnchantmentName(e.getKey()) + ":" + e.getValue();
@ -528,8 +578,7 @@ public class ItemUtil {
}
/**
* Returns a formatted display name. If none exists, returns item name.
* Also returns formatted durability and amount.
* Returns a formatted display name, plus durability and amount. If none exists, returns item name.
*
* Format is ([display]name:durability) x (amount)
*
@ -580,11 +629,10 @@ public class ItemUtil {
* @return true if stack is not null or Material.AIR
*/
public static boolean isItem(final ItemStack is) {
if (is == null)
if (is == null) {
return false;
if (is.getType().equals(Material.AIR))
return false;
return true;
}
return !is.getType().equals(Material.AIR);
}
/**
@ -594,12 +642,15 @@ public class ItemUtil {
* @return true if display name equals colored journal title
*/
public static boolean isJournal(final ItemStack is) {
if (is == null)
if (is == null) {
return false;
if (is.hasItemMeta() == false)
}
if (!is.hasItemMeta()) {
return false;
if (is.getItemMeta().hasDisplayName() == false)
}
if (!is.getItemMeta().hasDisplayName()) {
return false;
}
return is.getItemMeta().getDisplayName().equals(ChatColor.LIGHT_PURPLE + Lang.get("journalTitle"));
}
@ -611,7 +662,11 @@ public class ItemUtil {
* @return cleaned-up string
*/
public static String getPrettyItemName(final String itemName) {
final String baseString = Material.matchMaterial(itemName).toString();
final Material material = Material.matchMaterial(itemName);
if (material == null) {
return "invalid";
}
final String baseString = material.toString();
final String[] substrings = baseString.split("_");
String prettyString = "";
int size = 1;
@ -668,7 +723,7 @@ public class ItemUtil {
/**
* Gets Enchantment from name as it appears in lang file
*
* @deprecated Use {@link #getProperEnchantmentType(String)}
* @deprecated Use {@link #getEnchantmentFromProperName(String)}
* @param enchant Name to match lang value to
* @return Enchantment or null if invalid
*/
@ -728,8 +783,10 @@ public class ItemUtil {
}
public static Enchantment getEnchantmentFromPrettyName(String enchant) {
while (MiscUtil.spaceToCapital(enchant) != null) {
enchant = MiscUtil.spaceToCapital(enchant);
if (enchant != null) {
while (MiscUtil.spaceToCapital(enchant) != null) {
enchant = MiscUtil.spaceToCapital(enchant);
}
}
return getEnchantmentFromProperName(enchant);
}

View File

@ -179,8 +179,8 @@ stageEditorSetTameAmounts: "Set tame amounts"
stageEditorSetShearColors: "Set sheep colors"
stageEditorSetShearAmounts: "Set shear amounts"
stageEditorPassword: "Password"
stageEditorAddPasswordDisplay: "Add password display"
stageEditorAddPasswordPhrases: "Add password phrase(s)"
stageEditorAddPasswordDisplay: "Add password displays"
stageEditorAddPasswordPhrases: "Add password phrases"
stageEditorCustom: "Custom objectives"
stageEditorNoModules: "No modules loaded"
stageEditorModuleNotFound: "Custom objective module not found."
@ -222,7 +222,7 @@ stageEditorDelayMessagePrompt: "Enter delay message, <clear>, <cancel>"
stageEditorScriptPrompt: "Enter script name, <clear>, <cancel>"
stageEditorStartMessagePrompt: "Enter start message, <clear>, <cancel>"
stageEditorCompleteMessagePrompt: "Enter complete message, <clear>, <cancel>"
stageEditorPasswordDisplayPrompt: "Enter password hint message, <cancel>"
stageEditorPasswordDisplayPrompt: "Enter password hint message, <semicolon>, <cancel>"
stageEditorPasswordPhrasePrompt: "Enter password phrases to accept, <semicolon>, <cancel>"
stageEditorDeliveryAddItem: "Add item"
stageEditorDeliveryNPCs: "Set NPC IDs"