From 1ad626fdcf2fc88f4a47c96935473cf07b8826ba Mon Sep 17 00:00:00 2001 From: Thomas Persson Date: Tue, 3 Feb 2015 11:34:01 +0100 Subject: [PATCH 1/3] First push Various changes to get the plugin updated for 1.8 Not much done as of yet, but plugin is stable and ready --- .classpath | 17 ++++++++++++ .gitignore | 1 + .project | 17 ++++++++++++ .../communitybridge/main/BukkitWrapper.java | 3 +++ .../communitybridge/main/CommunityBridge.java | 26 ++++++++----------- .../communitybridge/main/WebApplication.java | 2 +- src/plugin.yml | 4 +-- 7 files changed, 52 insertions(+), 18 deletions(-) create mode 100644 .classpath create mode 100644 .project diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..6a3d1a7 --- /dev/null +++ b/.classpath @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore index 2137035..172fe51 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ nb-configuration.xml *\.tex~ *\.yml~ *.synctex.gz +/bin diff --git a/.project b/.project new file mode 100644 index 0000000..d722c75 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + CommunityBridge + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/src/org/communitybridge/main/BukkitWrapper.java b/src/org/communitybridge/main/BukkitWrapper.java index 9d3461f..142951e 100644 --- a/src/org/communitybridge/main/BukkitWrapper.java +++ b/src/org/communitybridge/main/BukkitWrapper.java @@ -1,6 +1,7 @@ package org.communitybridge.main; import java.util.UUID; + import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -15,6 +16,7 @@ public OfflinePlayer getOfflinePlayer(UUID uuid) return Bukkit.getOfflinePlayer(uuid); } + @SuppressWarnings("deprecation") public OfflinePlayer getOfflinePlayer(String name) { return Bukkit.getOfflinePlayer(name); @@ -40,6 +42,7 @@ public PluginManager getPluginManager() return Bukkit.getPluginManager(); } + @SuppressWarnings("deprecation") public Player[] getOnlinePlayers() { return Bukkit.getOnlinePlayers(); diff --git a/src/org/communitybridge/main/CommunityBridge.java b/src/org/communitybridge/main/CommunityBridge.java index 705c5c2..3e9198d 100644 --- a/src/org/communitybridge/main/CommunityBridge.java +++ b/src/org/communitybridge/main/CommunityBridge.java @@ -2,7 +2,9 @@ import java.io.IOException; import java.util.logging.Level; + import net.milkbowl.vault.economy.Economy; + import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -242,19 +244,14 @@ public void run() * If linking-kick-unregistered is turned on, an unregistered player will * be kicked. */ - private void remindPlayer(Player player) - { + private void remindPlayer(Player player) { String userID = environment.getUserPlayerLinker().getUserID(player); - if (userID == null || userID.isEmpty()) - { + if (userID == null || userID.isEmpty()) { String playerName = player.getName(); - if (environment.getConfiguration().linkingKickUnregistered) - { + if (environment.getConfiguration().linkingKickUnregistered) { player.kickPlayer(environment.getConfiguration().messages.get("link-unregistered-player")); environment.getLog().info(playerName + " kicked because they are not registered."); - } - else - { + } else { player.sendMessage(ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-reminder")); environment.getLog().fine(playerName + " issued unregistered reminder notice"); } @@ -265,13 +262,12 @@ private void remindPlayer(Player player) * Calls remindPlayer() for all connected players. Called by the reminder * task. */ - private void remindUnregisteredPlayers() - { - environment.getLog().finest("Running unregistered auto reminder."); + @SuppressWarnings("deprecation") +private void remindUnregisteredPlayers() { + environment.getLog().finest("Running unregistered auto reminder."); - for (Player player : Bukkit.getOnlinePlayers()) - { - remindPlayer(player); + for (Player player : Bukkit.getOnlinePlayers()) { + remindPlayer(player); } environment.getLog().finest("Unregistered auto reminder complete."); } diff --git a/src/org/communitybridge/main/WebApplication.java b/src/org/communitybridge/main/WebApplication.java index 1b140a1..dbf87a0 100644 --- a/src/org/communitybridge/main/WebApplication.java +++ b/src/org/communitybridge/main/WebApplication.java @@ -532,7 +532,7 @@ else if (key.equalsIgnoreCase(configuration.gametimeColumnOrKey)) if (configuration.healthEnabled) { - playerStatistics.setHealth((double)player.getHealth()); + playerStatistics.setHealth((double)player.getHealthScale()); } if (configuration.lifeticksEnabled) diff --git a/src/plugin.yml b/src/plugin.yml index 21df0b2..eb2abdd 100644 --- a/src/plugin.yml +++ b/src/plugin.yml @@ -1,7 +1,7 @@ name: CommunityBridge -version: 2.5.2.562 +version: 2.6.0.000 description: Community Bridging plugin based off of ChillerCrafts ForumBridge plugin -authors: [Feaelin, NoRC, ChillerCraft] +authors: [TEKAA92, DukeofRealms, Feaelin, NoRC, ChillerCraft] website: http://dev.bukkit.org/server-mods/communitybridge-fm/ softdepend: [bPermissions, GroupManager, PermissionsBukkit, PermissionsEx, Vault, zPermissions] From 7e9a5f4c7a13565f4768fd497c0f1d1a8dc97520 Mon Sep 17 00:00:00 2001 From: Thomas Persson Date: Tue, 3 Feb 2015 11:38:07 +0100 Subject: [PATCH 2/3] Changed plugin.yml changed website in the plugin.yml --- src/plugin.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugin.yml b/src/plugin.yml index eb2abdd..6d35c53 100644 --- a/src/plugin.yml +++ b/src/plugin.yml @@ -2,7 +2,7 @@ name: CommunityBridge version: 2.6.0.000 description: Community Bridging plugin based off of ChillerCrafts ForumBridge plugin authors: [TEKAA92, DukeofRealms, Feaelin, NoRC, ChillerCraft] -website: http://dev.bukkit.org/server-mods/communitybridge-fm/ +website: http://www.spigotmc.org/resources/communitybridge.2232/ softdepend: [bPermissions, GroupManager, PermissionsBukkit, PermissionsEx, Vault, zPermissions] main: org.communitybridge.main.CommunityBridge From e1fea9b7add4f3385c681a3281154723d77923c3 Mon Sep 17 00:00:00 2001 From: Thomas Persson Date: Thu, 5 Feb 2015 11:25:45 +0100 Subject: [PATCH 3/3] GitHub recommended reindentations Removed space whitespaces and replaced with Tab whitespaces --- .gitattributes | 17 + .gitignore | 52 +- build.number | 6 +- build.xml | 48 +- communitybridge.mf | 4 +- ...mmunitybridgedeveloperdocumentation.kilepr | 114 +-- manifest.mf | 6 +- nbproject/coverage.properties | 12 +- nbproject/project.properties | 226 ++--- nbproject/project.xml | 30 +- .../main/CBCommandExecutor.java | 320 +++---- .../communitybridge/main/CommunityBridge.java | 800 +++++++++--------- .../communitybridge/main/DatabaseHandler.java | 562 ++++++------ .../communitybridge/main/PlayerListener.java | 348 ++++---- src/org/communitybridge/main/SQL.java | 154 ++-- .../permissionhandlers/PermissionHandler.java | 132 +-- .../PermissionHandlerGroupManager.java | 408 ++++----- .../PermissionHandlerPermissionsBukkit.java | 243 +++--- .../PermissionHandlerPermissionsEx.java | 266 +++--- src/org/communitybridge/utility/Log.java | 398 ++++----- .../utility/StringUtilities.java | 442 +++++----- .../achievement/AchievementAvatarTest.java | 242 +++--- .../achievement/AchievementTest.java | 412 ++++----- .../communitybridge/linker/UserIDDaoTest.java | 476 +++++------ .../linker/UserPlayerLinkerTest.java | 564 ++++++------ .../main/PlayerStatisticsTest.java | 108 +-- .../PermissionHandlerTest.java | 482 +++++------ .../MoneySynchronizerTest.java | 442 +++++----- .../PlayerFileFetcherTest.java | 188 ++-- .../synchronization/PlayerStateTest.java | 772 ++++++++--------- .../PlayerSynchronizationDispatcherTest.java | 430 +++++----- .../synchronization/SynchronizerTest.java | 80 +- .../dao/JunctionWebGroupDaoTest.java | 492 +++++------ .../dao/KeyValueWebGroupDaoTest.java | 696 +++++++-------- .../synchronization/dao/MoneyDaoTest.java | 246 +++--- .../dao/MultipleKeyValueWebGroupDaoTest.java | 434 +++++----- .../utility/StringUtilitiesTest.java | 752 ++++++++-------- 37 files changed, 5712 insertions(+), 5692 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bdb0cab --- /dev/null +++ b/.gitattributes @@ -0,0 +1,17 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 172fe51..0b3ae53 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,27 @@ -# NetBeans specific # -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -nbactions.xml -nb-configuration.xml - -# Class Files # -*.class - -# Package Files # -*.jar -*.war -*.ear -/nbproject/genfiles.properties -/nbproject/build-impl.xml -*.log -*.aux -/coverage -/output -*\.txt~ -*\.tex~ -*\.yml~ -*.synctex.gz +# NetBeans specific # +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +nbactions.xml +nb-configuration.xml + +# Class Files # +*.class + +# Package Files # +*.jar +*.war +*.ear +/nbproject/genfiles.properties +/nbproject/build-impl.xml +*.log +*.aux +/coverage +/output +*\.txt~ +*\.tex~ +*\.yml~ +*.synctex.gz /bin diff --git a/build.number b/build.number index 0135115..737a53f 100644 --- a/build.number +++ b/build.number @@ -1,3 +1,3 @@ -#Build Number for ANT. Do not edit! -#Fri Aug 22 05:46:37 CDT 2014 -build.number=563 +#Build Number for ANT. Do not edit! +#Fri Aug 22 05:46:37 CDT 2014 +build.number=563 diff --git a/build.xml b/build.xml index 9081b26..201accf 100644 --- a/build.xml +++ b/build.xml @@ -1,24 +1,24 @@ - - - Builds, tests, and runs the project CommunityBridge. - - - - - - - - - - - - - - - - - - - - - + + + Builds, tests, and runs the project CommunityBridge. + + + + + + + + + + + + + + + + + + + + + diff --git a/communitybridge.mf b/communitybridge.mf index 58630c0..59499bc 100644 --- a/communitybridge.mf +++ b/communitybridge.mf @@ -1,2 +1,2 @@ -Manifest-Version: 1.0 - +Manifest-Version: 1.0 + diff --git a/documentation/developer/communitybridgedeveloperdocumentation.kilepr b/documentation/developer/communitybridgedeveloperdocumentation.kilepr index 8ec21ab..010c807 100644 --- a/documentation/developer/communitybridgedeveloperdocumentation.kilepr +++ b/documentation/developer/communitybridgedeveloperdocumentation.kilepr @@ -1,57 +1,57 @@ -[General] -bibliographyBackendAutoDetected= -bibliographyBackendUserOverride= -def_graphic_ext=eps -img_extIsRegExp=false -img_extensions=.eps .jpg .jpeg .png .pdf .ps .fig .gif -kile_livePreviewEnabled=true -kile_livePreviewStatusUserSpecified=false -kile_livePreviewTool=LivePreview-PDFLaTeX -kileprversion=2 -kileversion=2.9.60 -lastDocument=developer documentation.tex -masterDocument= -name=CommunityBridge Developer Documentation -pkg_extIsRegExp=false -pkg_extensions=.cls .sty .bbx .cbx .lbx -src_extIsRegExp=false -src_extensions=.tex .ltx .latex .dtx .ins - -[Tools] -MakeIndex= -QuickBuild= - -[document-settings,item:developer documentation.tex] -Bookmarks= -Encoding=UTF-8 -FoldedColumns= -FoldedLines= -Highlighting=LaTeX -Indentation Mode=normal -Mode=LaTeX - -[item:communitybridgedeveloperdocumentation.kilepr] -archive=true -column=1 -encoding= -highlight= -line=0 -mode= -open=false -order=-1 - -[item:developer documentation.tex] -archive=true -column=15 -encoding=UTF-8 -highlight=LaTeX -line=138 -mode=LaTeX -open=true -order=0 - -[view-settings,view=0,item:developer documentation.tex] -CursorColumn=15 -CursorLine=138 -JumpList= -ViMarks= +[General] +bibliographyBackendAutoDetected= +bibliographyBackendUserOverride= +def_graphic_ext=eps +img_extIsRegExp=false +img_extensions=.eps .jpg .jpeg .png .pdf .ps .fig .gif +kile_livePreviewEnabled=true +kile_livePreviewStatusUserSpecified=false +kile_livePreviewTool=LivePreview-PDFLaTeX +kileprversion=2 +kileversion=2.9.60 +lastDocument=developer documentation.tex +masterDocument= +name=CommunityBridge Developer Documentation +pkg_extIsRegExp=false +pkg_extensions=.cls .sty .bbx .cbx .lbx +src_extIsRegExp=false +src_extensions=.tex .ltx .latex .dtx .ins + +[Tools] +MakeIndex= +QuickBuild= + +[document-settings,item:developer documentation.tex] +Bookmarks= +Encoding=UTF-8 +FoldedColumns= +FoldedLines= +Highlighting=LaTeX +Indentation Mode=normal +Mode=LaTeX + +[item:communitybridgedeveloperdocumentation.kilepr] +archive=true +column=1 +encoding= +highlight= +line=0 +mode= +open=false +order=-1 + +[item:developer documentation.tex] +archive=true +column=15 +encoding=UTF-8 +highlight=LaTeX +line=138 +mode=LaTeX +open=true +order=0 + +[view-settings,view=0,item:developer documentation.tex] +CursorColumn=15 +CursorLine=138 +JumpList= +ViMarks= diff --git a/manifest.mf b/manifest.mf index 1574df4..328e8e5 100644 --- a/manifest.mf +++ b/manifest.mf @@ -1,3 +1,3 @@ -Manifest-Version: 1.0 -X-COMMENT: Main-Class will be added automatically by build - +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/nbproject/coverage.properties b/nbproject/coverage.properties index 0e1e8c4..25df1b1 100644 --- a/nbproject/coverage.properties +++ b/nbproject/coverage.properties @@ -1,6 +1,6 @@ -#coverage viewer module properties for project -#Fri Aug 01 21:36:09 CDT 2014 -coverage.activity=OFF -project.type=java -coverage.coverageFile=coverage/coverage.emma -coverage.templateFile=coverage/template.emma +#coverage viewer module properties for project +#Fri Aug 01 21:36:09 CDT 2014 +coverage.activity=OFF +project.type=java +coverage.coverageFile=coverage/coverage.emma +coverage.templateFile=coverage/template.emma diff --git a/nbproject/project.properties b/nbproject/project.properties index 18b0bd7..519c3ce 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,113 +1,113 @@ -annotation.processing.enabled=true -annotation.processing.enabled.in.editor=true -annotation.processing.processors.list= -annotation.processing.run.all.processors=true -annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output -application.desc= -application.title=CommunityBridge -application.vendor=Feaelin (Iain E. Davis) -build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form -# This directory is removed when the project is cleaned: -build.dir=build -build.generated.dir=${build.dir}/generated -build.generated.sources.dir=${build.dir}/generated-sources -# Only compile against the classpath explicitly listed here: -build.sysclasspath=ignore -build.test.classes.dir=${build.dir}/test/classes -build.test.results.dir=${build.dir}/test/results -# Uncomment to specify the preferred debugger connection transport: -#debug.transport=dt_socket -debug.classpath=\ - ${run.classpath} -debug.test.classpath=\ - ${run.test.classpath} -# This directory is removed when the project is cleaned: -dist.dir=dist -dist.jar=${dist.dir}/CommunityBridge.jar -dist.javadoc.dir=${dist.dir}/javadoc -endorsed.classpath= -excludes=org/communitybridge/grouprules/ -file.reference.bPermissions.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\bPermissions.jar -file.reference.bukkit-1.7.9-R0.2.jar=..\\..\\0-Library Jars\\CraftBukkit\\bukkit-1.7.9-R0.2.jar -file.reference.commons-lang3-3.3.1.jar=..\\..\\..\\Java\\0-Library Jars\\commons-lang3-3.3.1\\commons-lang3-3.3.1.jar -file.reference.CommunityBridge-src=src -file.reference.CommunityBridge-test=test -file.reference.EssentialsGroupManager.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\EssentialsGroupManager.jar -file.reference.hamcrest-core-1.3.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\hamcrest-core-1.3.jar -file.reference.javassist.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\javassist.jar -file.reference.junit-4.11.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\junit-4.11.jar -file.reference.mockito-all-1.9.5.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\mockito-all-1.9.5.jar -file.reference.PermissionsBukkit-2.3.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsBukkit-2.3.jar -file.reference.PermissionsEx.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsEx.jar -file.reference.powermock-mockito-1.5.4-full.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\powermock-mockito-1.5.4-full.jar -file.reference.Vault-1.4.1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\Vault-1.4.1.jar -file.reference.zPermissions-1.3beta1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\zPermissions-1.3beta1.jar -includes=** -jar.archive.disabled=${jnlp.enabled} -jar.compress=true -jar.index=${jnlp.enabled} -javac.classpath=\ - ${file.reference.bPermissions.jar}:\ - ${file.reference.EssentialsGroupManager.jar}:\ - ${file.reference.PermissionsEx.jar}:\ - ${file.reference.PermissionsBukkit-2.3.jar}:\ - ${file.reference.zPermissions-1.3beta1.jar}:\ - ${file.reference.Vault-1.4.1.jar}:\ - ${file.reference.bukkit-1.7.9-R0.2.jar} -# Space-separated list of extra javac options -javac.compilerargs=-Xlint:deprecation -Xlint:unchecked -javac.deprecation=true -javac.processorpath=\ - ${javac.classpath} -javac.source=1.6 -javac.target=1.6 -javac.test.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir}:\ - ${file.reference.junit-4.11.jar}:\ - ${file.reference.hamcrest-core-1.3.jar}:\ - ${file.reference.javassist.jar}:\ - ${file.reference.mockito-all-1.9.5.jar}:\ - ${file.reference.powermock-mockito-1.5.4-full.jar}:\ - ${file.reference.commons-lang3-3.3.1.jar} -javac.test.processorpath=\ - ${javac.test.classpath} -javadoc.additionalparam= -javadoc.author=true -javadoc.encoding=${source.encoding} -javadoc.noindex=false -javadoc.nonavbar=false -javadoc.notree=false -javadoc.private=true -javadoc.splitindex=true -javadoc.use=true -javadoc.version=true -javadoc.windowtitle= -jnlp.codebase.type=no.codebase -jnlp.descriptor=application -jnlp.enabled=false -jnlp.mixed.code=default -jnlp.offline-allowed=false -jnlp.signed=false -jnlp.signing= -jnlp.signing.alias= -jnlp.signing.keystore= -main.class= -manifest.file=manifest.mf -meta.inf.dir=${src.dir}/META-INF -mkdist.disabled=true -platform.active=default_platform -run.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -# Space-separated list of JVM arguments used when running the project. -# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. -# To set system properties for unit tests define test-sys-prop.name=value: -run.jvmargs=-Xms1024m -Xmx2048m -run.test.classpath=\ - ${javac.test.classpath}:\ - ${build.test.classes.dir} -source.encoding=UTF-8 -src.dir=${file.reference.CommunityBridge-src} -test.test.dir=test +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.desc= +application.title=CommunityBridge +application.vendor=Feaelin (Iain E. Davis) +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/CommunityBridge.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes=org/communitybridge/grouprules/ +file.reference.bPermissions.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\bPermissions.jar +file.reference.bukkit-1.7.9-R0.2.jar=..\\..\\0-Library Jars\\CraftBukkit\\bukkit-1.7.9-R0.2.jar +file.reference.commons-lang3-3.3.1.jar=..\\..\\..\\Java\\0-Library Jars\\commons-lang3-3.3.1\\commons-lang3-3.3.1.jar +file.reference.CommunityBridge-src=src +file.reference.CommunityBridge-test=test +file.reference.EssentialsGroupManager.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\EssentialsGroupManager.jar +file.reference.hamcrest-core-1.3.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\hamcrest-core-1.3.jar +file.reference.javassist.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\javassist.jar +file.reference.junit-4.11.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\junit-4.11.jar +file.reference.mockito-all-1.9.5.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\mockito-all-1.9.5.jar +file.reference.PermissionsBukkit-2.3.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsBukkit-2.3.jar +file.reference.PermissionsEx.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsEx.jar +file.reference.powermock-mockito-1.5.4-full.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\powermock-mockito-1.5.4-full.jar +file.reference.Vault-1.4.1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\Vault-1.4.1.jar +file.reference.zPermissions-1.3beta1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\zPermissions-1.3beta1.jar +includes=** +jar.archive.disabled=${jnlp.enabled} +jar.compress=true +jar.index=${jnlp.enabled} +javac.classpath=\ + ${file.reference.bPermissions.jar}:\ + ${file.reference.EssentialsGroupManager.jar}:\ + ${file.reference.PermissionsEx.jar}:\ + ${file.reference.PermissionsBukkit-2.3.jar}:\ + ${file.reference.zPermissions-1.3beta1.jar}:\ + ${file.reference.Vault-1.4.1.jar}:\ + ${file.reference.bukkit-1.7.9-R0.2.jar} +# Space-separated list of extra javac options +javac.compilerargs=-Xlint:deprecation -Xlint:unchecked +javac.deprecation=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.11.jar}:\ + ${file.reference.hamcrest-core-1.3.jar}:\ + ${file.reference.javassist.jar}:\ + ${file.reference.mockito-all-1.9.5.jar}:\ + ${file.reference.powermock-mockito-1.5.4-full.jar}:\ + ${file.reference.commons-lang3-3.3.1.jar} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=true +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=true +javadoc.splitindex=true +javadoc.use=true +javadoc.version=true +javadoc.windowtitle= +jnlp.codebase.type=no.codebase +jnlp.descriptor=application +jnlp.enabled=false +jnlp.mixed.code=default +jnlp.offline-allowed=false +jnlp.signed=false +jnlp.signing= +jnlp.signing.alias= +jnlp.signing.keystore= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=true +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs=-Xms1024m -Xmx2048m +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=${file.reference.CommunityBridge-src} +test.test.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml index 0218a5c..be76886 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -1,15 +1,15 @@ - - - org.netbeans.modules.java.j2seproject - - - CommunityBridge - - - - - - - - - + + + org.netbeans.modules.java.j2seproject + + + CommunityBridge + + + + + + + + + diff --git a/src/org/communitybridge/main/CBCommandExecutor.java b/src/org/communitybridge/main/CBCommandExecutor.java index d5ba637..226a7d5 100644 --- a/src/org/communitybridge/main/CBCommandExecutor.java +++ b/src/org/communitybridge/main/CBCommandExecutor.java @@ -1,160 +1,160 @@ -package org.communitybridge.main; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public class CBCommandExecutor implements CommandExecutor -{ - private Environment environment; - - private BukkitWrapper bukkit; - - public CBCommandExecutor(Environment environment) - { - this.environment = environment; - this.bukkit = new BukkitWrapper(); - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] arguments) - { - label = label.toLowerCase(); - if (label.equals("cbreload")) - { - commandReload(arguments, sender); - return true; - } - - if (CommunityBridge.isActive() == false) - { - sendOrLog(sender, environment.getConfiguration().messages.get("communitybridge-inactive"), ChatColor.RED, false); - return true; - } - - if (label.equals("cbsync")) - { - if (arguments.length == 1 && (!(sender instanceof Player) || ((Player)sender).hasPermission("communitybridge.cbsynctarget"))) - { - commandSyncTarget(sender, arguments[0]); - } - else - { - commandSync(sender); - } - return true; - } - - if (label.equals("cbsyncall")) - { - commandSyncAll(sender); - return true; - } - - return true; - } - - private void sendAndLog(CommandSender sender, String message, ChatColor color, boolean who) - { - if (sender instanceof Player) - { - sender.sendMessage(color + message); - } - - if (who) - { - message = "(" + sender.getName() + ") " + message; - } - - environment.getLog().info(message); - } - - private void sendOrLog(CommandSender sender, String message, ChatColor color, boolean who) - { - if (sender instanceof Player) - { - sender.sendMessage(color + message); - } - else - { - if (who) - { - message = "(" + sender.getName() + ") " + message; - } - environment.getLog().info(message); - } - } - - private void commandReload(String[] arguments, CommandSender sender) - { - if (arguments.length > 1) - { - sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-too-many-arguments"), ChatColor.RED, false); - } - - sendAndLog(sender, environment.getConfiguration().messages.get("cbreload"), ChatColor.GREEN, true); - - String error; - String filename; - if (arguments.length == 1) - { - filename = arguments[0]; - } - else - { - filename = "config.yml"; - } - - error = environment.getConfiguration().reload(filename); - - if (error == null) - { - sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-success").replace("~FILENAME~", filename), ChatColor.GREEN, false); - if (CommunityBridge.isActive()) - { - environment.getConfiguration().report(); - } - } - else - { - sendOrLog(sender, error, ChatColor.RED, false); - } - } - - private void commandSync(CommandSender sender) - { - if (sender instanceof Player) - { - sendOrLog(sender, environment.getConfiguration().messages.get("cbsync"), ChatColor.GREEN, false); - environment.getWebApplication().runSynchronizePlayer(environment, (Player) sender, true); - } - else - { - sendOrLog(sender, environment.getConfiguration().messages.get("cbsync-ingame"), ChatColor.RED, false); - } - } - - private void commandSyncAll(CommandSender sender) - { - sendAndLog(sender, environment.getConfiguration().messages.get("cbsyncall"), ChatColor.GREEN, true); - environment.getWebApplication().runSynchronizeAll(); - } - - private void commandSyncTarget(CommandSender sender, String playerName) - { - Player player = bukkit.getServer().getPlayerExact(playerName); - if (player == null) - { - String message = environment.getConfiguration().messages.get("cbsync-target-not-found").replace("~PLAYERNAME~", playerName); - sendOrLog(sender, message, ChatColor.RED, false); - } - else - { - String message = environment.getConfiguration().messages.get("cbsync-target").replace("~PLAYERNAME~", player.getName()); - sendAndLog(sender, message, ChatColor.GREEN, true); - environment.getWebApplication().runSynchronizePlayer(environment, player, true); - } - } -} +package org.communitybridge.main; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CBCommandExecutor implements CommandExecutor +{ + private Environment environment; + + private BukkitWrapper bukkit; + + public CBCommandExecutor(Environment environment) + { + this.environment = environment; + this.bukkit = new BukkitWrapper(); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] arguments) + { + label = label.toLowerCase(); + if (label.equals("cbreload")) + { + commandReload(arguments, sender); + return true; + } + + if (CommunityBridge.isActive() == false) + { + sendOrLog(sender, environment.getConfiguration().messages.get("communitybridge-inactive"), ChatColor.RED, false); + return true; + } + + if (label.equals("cbsync")) + { + if (arguments.length == 1 && (!(sender instanceof Player) || ((Player)sender).hasPermission("communitybridge.cbsynctarget"))) + { + commandSyncTarget(sender, arguments[0]); + } + else + { + commandSync(sender); + } + return true; + } + + if (label.equals("cbsyncall")) + { + commandSyncAll(sender); + return true; + } + + return true; + } + + private void sendAndLog(CommandSender sender, String message, ChatColor color, boolean who) + { + if (sender instanceof Player) + { + sender.sendMessage(color + message); + } + + if (who) + { + message = "(" + sender.getName() + ") " + message; + } + + environment.getLog().info(message); + } + + private void sendOrLog(CommandSender sender, String message, ChatColor color, boolean who) + { + if (sender instanceof Player) + { + sender.sendMessage(color + message); + } + else + { + if (who) + { + message = "(" + sender.getName() + ") " + message; + } + environment.getLog().info(message); + } + } + + private void commandReload(String[] arguments, CommandSender sender) + { + if (arguments.length > 1) + { + sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-too-many-arguments"), ChatColor.RED, false); + } + + sendAndLog(sender, environment.getConfiguration().messages.get("cbreload"), ChatColor.GREEN, true); + + String error; + String filename; + if (arguments.length == 1) + { + filename = arguments[0]; + } + else + { + filename = "config.yml"; + } + + error = environment.getConfiguration().reload(filename); + + if (error == null) + { + sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-success").replace("~FILENAME~", filename), ChatColor.GREEN, false); + if (CommunityBridge.isActive()) + { + environment.getConfiguration().report(); + } + } + else + { + sendOrLog(sender, error, ChatColor.RED, false); + } + } + + private void commandSync(CommandSender sender) + { + if (sender instanceof Player) + { + sendOrLog(sender, environment.getConfiguration().messages.get("cbsync"), ChatColor.GREEN, false); + environment.getWebApplication().runSynchronizePlayer(environment, (Player) sender, true); + } + else + { + sendOrLog(sender, environment.getConfiguration().messages.get("cbsync-ingame"), ChatColor.RED, false); + } + } + + private void commandSyncAll(CommandSender sender) + { + sendAndLog(sender, environment.getConfiguration().messages.get("cbsyncall"), ChatColor.GREEN, true); + environment.getWebApplication().runSynchronizeAll(); + } + + private void commandSyncTarget(CommandSender sender, String playerName) + { + Player player = bukkit.getServer().getPlayerExact(playerName); + if (player == null) + { + String message = environment.getConfiguration().messages.get("cbsync-target-not-found").replace("~PLAYERNAME~", playerName); + sendOrLog(sender, message, ChatColor.RED, false); + } + else + { + String message = environment.getConfiguration().messages.get("cbsync-target").replace("~PLAYERNAME~", player.getName()); + sendAndLog(sender, message, ChatColor.GREEN, true); + environment.getWebApplication().runSynchronizePlayer(environment, player, true); + } + } +} diff --git a/src/org/communitybridge/main/CommunityBridge.java b/src/org/communitybridge/main/CommunityBridge.java index 3e9198d..fa38102 100644 --- a/src/org/communitybridge/main/CommunityBridge.java +++ b/src/org/communitybridge/main/CommunityBridge.java @@ -1,400 +1,400 @@ -package org.communitybridge.main; - -import java.io.IOException; -import java.util.logging.Level; - -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; -import org.communitybridge.linker.UserPlayerLinker; -import org.communitybridge.main.CBMetrics.Graph; -import org.communitybridge.utility.Log; -import org.communitybridge.permissionhandlers.*; -import org.communitybridge.utility.MinecraftUtilities; -import org.communitybridge.utility.StringUtilities; - -/** - * Main plugin class - * - * During a normal startup, first CraftBukkit calls the onEnable method, - * which in turn calls activate(). If, however, the configuration has a - * problem, instead of disabling the plugin, which would disable the - * configuration reload command, we "deactivate" instead. This leaves the - * plugin "enabled" in the eyes of CraftBukkit so that the reload can be - * used, but "disabled" in reality to prevent things from going wrong when - * the configuration is broken. Correspondingly, during a configuration - * reload, first deactivate() is called if necessary, the new configuration - * is loaded, and then activate() is called. - * - * @author Iain E. Davis - */ - -public class CommunityBridge extends JavaPlugin -{ - private Environment environment = new Environment(); - - private static boolean active; - private static CBMetrics metrics; - - @Override - public void onEnable() - { - setupEnvironment(); - javaVersionCheck(); - - if (StringUtilities.compareVersion(MinecraftUtilities.getBukkitVersion(), "1.7.9") < 0) - { - environment.getLog().severe("This version of CommunityBridge requires Bukkit 1.7.9 or later."); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - - CBCommandExecutor command = new CBCommandExecutor(environment); - getCommand("cbreload").setExecutor(command); - getCommand("cbsync").setExecutor(command); - getCommand("cbsyncall").setExecutor(command); - -// getCommand("cbban").setExecutor(new CBCommandExecutor(config, log)); -// getCommand("cbunban").setExecutor(new CBCommandExecutor(config, log)); -// getCommand("cbrank").setExecutor(new CBCommandExecutor(config, log)); - - activate(); - - if (CommunityBridge.isActive()) - { - environment.getLog().info("CommunityBridge is now active."); - } - } - - private void setupEnvironment() - { - environment.setBukkit(new BukkitWrapper()); - environment.setPlugin(this); - environment.setLog(new Log(this.getLogger(), Level.CONFIG)); - environment.setConfiguration(new Configuration(environment)); - - // PermissionHandler set by Configuration initialization. - - environment.setUserPlayerLinker(new UserPlayerLinker(environment, Bukkit.getMaxPlayers() * 4)); - } - - public void activate() - { - if (environment.getConfiguration().databaseUsername.equals("username") - && environment.getConfiguration().databasePassword.equals("password")) - { - environment.getLog().severe("You need to set configuration options in the config.yml."); - deactivate(); - return; - } - - environment.setWebApplication(new WebApplication(environment)); - - getServer().getPluginManager().registerEvents(new PlayerListener(environment), this); - - if (environment.getConfiguration().economyEnabled || environment.getConfiguration().walletEnabled) - { - if (getServer().getPluginManager().getPlugin("Vault") == null) - { - environment.getLog().warning("Vault not present. Temporarily disabling economy based features."); - disableEconomyBasedFeatures(); - } - else - { - RegisteredServiceProvider rsp = Bukkit.getServicesManager().getRegistration(Economy.class); - if (rsp == null) - { - environment.getLog().warning("Failure getting economy service registration. Is an economy plugin installed? Temporarily disabling economy based features."); - disableEconomyBasedFeatures(); - } - else - { - environment.setEconomy(rsp.getProvider()); - if (environment.getEconomy() == null) - { - environment.getLog().warning("Failure getting economy provider. Temporarily disabling economy based features."); - disableEconomyBasedFeatures(); - } - } - } - } - - activateMetrics(); - - if (environment.getConfiguration().linkingAutoRemind) - { - reminderStart(); - } - - if (environment.getConfiguration().autoSync) - { - autosyncStart(); - } - - active = true; - environment.getLog().finest("CommunityBridge activated."); - } - - /** - * Handles any clean up that needs done when the plugin is disabled. - */ - @Override - public void onDisable() - { - deactivate(); - -// getCommand("cbban").setExecutor(null); -// getCommand("cbunban").setExecutor(null); -// getCommand("cbrank").setExecutor(null); - getCommand("cbreload").setExecutor(null); - getCommand("cbsync").setExecutor(null); - getCommand("cbsyncall").setExecutor(null); - - environment.getLog().config("Disabled..."); - environment = null; - } - - /** - * Handles any clean up that needs to be done when the plugin is deactivated. - */ - public void deactivate() - { - active = false; - - // Cancel the tasks: autoRemind and autoSync - Bukkit.getServer().getScheduler().cancelTasks(this); - - // Drop all of our listeners - HandlerList.unregisterAll(this); - - if (metrics != null) - { - try - { - metrics.cancelTask(); - } - catch (NoSuchMethodError exception) - { - environment.getLog().warning("Metrics cancelTask() method unavailable: " + exception.getMessage()); - } - metrics = null; - } - - if (environment.getSql() != null) - { - environment.getSql().close(); - } - - if (environment.getEconomy() != null) - { - environment.setEconomy(null); - } - - environment.getLog().finest("CommunityBridge deactivated."); - } - - public static boolean isActive() - { - return active; - } - - private void reminderStart() - { - MinecraftUtilities.startTaskTimer(this, - calculateTaskTicks(environment.getConfiguration().linkingAutoEvery), - new Runnable() - { - @Override - public void run() - { - remindUnregisteredPlayers(); - } - } - ); - environment.getLog().fine("Auto reminder started."); - } - - /** - * Called by activate() if the auto sync is turned on, this starts up the - * auto synchronization task runner. - */ - private void autosyncStart() - { - MinecraftUtilities.startTaskTimer(this, - calculateTaskTicks(environment.getConfiguration().autoSyncEvery), - new Runnable() - { - @Override - public void run() - { - environment.getWebApplication().synchronizeAll(); - } - } - ); - environment.getLog().fine("Auto synchronization started."); - } - - /** - * Reminds a single player to register if they are not registered. - * If linking-kick-unregistered is turned on, an unregistered player will - * be kicked. - */ - private void remindPlayer(Player player) { - String userID = environment.getUserPlayerLinker().getUserID(player); - if (userID == null || userID.isEmpty()) { - String playerName = player.getName(); - if (environment.getConfiguration().linkingKickUnregistered) { - player.kickPlayer(environment.getConfiguration().messages.get("link-unregistered-player")); - environment.getLog().info(playerName + " kicked because they are not registered."); - } else { - player.sendMessage(ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-reminder")); - environment.getLog().fine(playerName + " issued unregistered reminder notice"); - } - } - } - - /** - * Calls remindPlayer() for all connected players. Called by the reminder - * task. - */ - @SuppressWarnings("deprecation") -private void remindUnregisteredPlayers() { - environment.getLog().finest("Running unregistered auto reminder."); - - for (Player player : Bukkit.getOnlinePlayers()) { - remindPlayer(player); - } - environment.getLog().finest("Unregistered auto reminder complete."); - } - - private void activateMetrics() - { - if (environment.getConfiguration().usePluginMetrics) - { - try - { - metrics = new CBMetrics(this); - Graph permsGraph = metrics.createGraph("Permissions Plugin Used"); - - if (environment.getPermissionHandler() == null) - { - permsGraph.addPlotter(new CBMetrics.Plotter("None") - { - @Override - public int getValue() - { - return 1; - } - }); - } - else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("bPerms")) - { - permsGraph.addPlotter(new CBMetrics.Plotter("bPermissions") - { - @Override - public int getValue() - { - return 1; - } - }); - } - else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("GroupManager")) - { - permsGraph.addPlotter(new CBMetrics.Plotter("GroupManager") - { - @Override - public int getValue() - { - return 1; - } - }); - } - else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("PermsBukkit")) - { - permsGraph.addPlotter(new CBMetrics.Plotter("PermissionsBukkit") - { - @Override - public int getValue() - { - return 1; - } - }); - } - else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("PEX")) - { - permsGraph.addPlotter(new CBMetrics.Plotter("PermissionsEx") - { - @Override - public int getValue() - { - return 1; - } - }); - } - else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("Vault")) - { - permsGraph.addPlotter(new CBMetrics.Plotter("Vault") - { - @Override - public int getValue() - { - return 1; - } - }); - } - metrics.start(); - environment.getLog().fine("Plugin Metrics activated."); - } - catch (IOException e) - { - environment.getLog().warning("Plugin Metrics activation failed."); - } - } - } - - private long calculateTaskTicks(final long every) - { - if (environment.getConfiguration().autoEveryUnit.startsWith("sec")) - { - return every * 20; // 20 ticks per second. - } - else if (environment.getConfiguration().autoEveryUnit.startsWith("min")) - { - return every * 1200; // 20 ticks per second, 60 sec/minute - } - else if (environment.getConfiguration().autoEveryUnit.startsWith("hou")) - { - return every * 72000; // 20 ticks/s 60s/m, 60m/h - } - else if (environment.getConfiguration().autoEveryUnit.startsWith("day")) - { - return every * 1728000; // 20 ticks/s 60s/m, 60m/h, 24h/day - } - else - { - // Effectively defaulting to ticks. - return every; - } - } - - private void javaVersionCheck() - { - int javaVersion = Integer.parseInt(System.getProperty("java.version").split("\\.")[1]); - - if (javaVersion < 7) - { - environment.getLog().warning("Future versions of CommunityBridge may require Java 7 or later. It is recommended you upgrade your JRE."); - } - } - - private void disableEconomyBasedFeatures() - { - environment.getConfiguration().economyEnabled = false; - environment.getConfiguration().walletEnabled = false; - } -} +package org.communitybridge.main; + +import java.io.IOException; +import java.util.logging.Level; + +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.communitybridge.linker.UserPlayerLinker; +import org.communitybridge.main.CBMetrics.Graph; +import org.communitybridge.utility.Log; +import org.communitybridge.permissionhandlers.*; +import org.communitybridge.utility.MinecraftUtilities; +import org.communitybridge.utility.StringUtilities; + +/** + * Main plugin class + * + * During a normal startup, first CraftBukkit calls the onEnable method, + * which in turn calls activate(). If, however, the configuration has a + * problem, instead of disabling the plugin, which would disable the + * configuration reload command, we "deactivate" instead. This leaves the + * plugin "enabled" in the eyes of CraftBukkit so that the reload can be + * used, but "disabled" in reality to prevent things from going wrong when + * the configuration is broken. Correspondingly, during a configuration + * reload, first deactivate() is called if necessary, the new configuration + * is loaded, and then activate() is called. + * + * @author Iain E. Davis + */ + +public class CommunityBridge extends JavaPlugin +{ + private Environment environment = new Environment(); + + private static boolean active; + private static CBMetrics metrics; + + @Override + public void onEnable() + { + setupEnvironment(); + javaVersionCheck(); + + if (StringUtilities.compareVersion(MinecraftUtilities.getBukkitVersion(), "1.7.9") < 0) + { + environment.getLog().severe("This version of CommunityBridge requires Bukkit 1.7.9 or later."); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + + CBCommandExecutor command = new CBCommandExecutor(environment); + getCommand("cbreload").setExecutor(command); + getCommand("cbsync").setExecutor(command); + getCommand("cbsyncall").setExecutor(command); + +// getCommand("cbban").setExecutor(new CBCommandExecutor(config, log)); +// getCommand("cbunban").setExecutor(new CBCommandExecutor(config, log)); +// getCommand("cbrank").setExecutor(new CBCommandExecutor(config, log)); + + activate(); + + if (CommunityBridge.isActive()) + { + environment.getLog().info("CommunityBridge is now active."); + } + } + + private void setupEnvironment() + { + environment.setBukkit(new BukkitWrapper()); + environment.setPlugin(this); + environment.setLog(new Log(this.getLogger(), Level.CONFIG)); + environment.setConfiguration(new Configuration(environment)); + + // PermissionHandler set by Configuration initialization. + + environment.setUserPlayerLinker(new UserPlayerLinker(environment, Bukkit.getMaxPlayers() * 4)); + } + + public void activate() + { + if (environment.getConfiguration().databaseUsername.equals("username") + && environment.getConfiguration().databasePassword.equals("password")) + { + environment.getLog().severe("You need to set configuration options in the config.yml."); + deactivate(); + return; + } + + environment.setWebApplication(new WebApplication(environment)); + + getServer().getPluginManager().registerEvents(new PlayerListener(environment), this); + + if (environment.getConfiguration().economyEnabled || environment.getConfiguration().walletEnabled) + { + if (getServer().getPluginManager().getPlugin("Vault") == null) + { + environment.getLog().warning("Vault not present. Temporarily disabling economy based features."); + disableEconomyBasedFeatures(); + } + else + { + RegisteredServiceProvider rsp = Bukkit.getServicesManager().getRegistration(Economy.class); + if (rsp == null) + { + environment.getLog().warning("Failure getting economy service registration. Is an economy plugin installed? Temporarily disabling economy based features."); + disableEconomyBasedFeatures(); + } + else + { + environment.setEconomy(rsp.getProvider()); + if (environment.getEconomy() == null) + { + environment.getLog().warning("Failure getting economy provider. Temporarily disabling economy based features."); + disableEconomyBasedFeatures(); + } + } + } + } + + activateMetrics(); + + if (environment.getConfiguration().linkingAutoRemind) + { + reminderStart(); + } + + if (environment.getConfiguration().autoSync) + { + autosyncStart(); + } + + active = true; + environment.getLog().finest("CommunityBridge activated."); + } + + /** + * Handles any clean up that needs done when the plugin is disabled. + */ + @Override + public void onDisable() + { + deactivate(); + +// getCommand("cbban").setExecutor(null); +// getCommand("cbunban").setExecutor(null); +// getCommand("cbrank").setExecutor(null); + getCommand("cbreload").setExecutor(null); + getCommand("cbsync").setExecutor(null); + getCommand("cbsyncall").setExecutor(null); + + environment.getLog().config("Disabled..."); + environment = null; + } + + /** + * Handles any clean up that needs to be done when the plugin is deactivated. + */ + public void deactivate() + { + active = false; + + // Cancel the tasks: autoRemind and autoSync + Bukkit.getServer().getScheduler().cancelTasks(this); + + // Drop all of our listeners + HandlerList.unregisterAll(this); + + if (metrics != null) + { + try + { + metrics.cancelTask(); + } + catch (NoSuchMethodError exception) + { + environment.getLog().warning("Metrics cancelTask() method unavailable: " + exception.getMessage()); + } + metrics = null; + } + + if (environment.getSql() != null) + { + environment.getSql().close(); + } + + if (environment.getEconomy() != null) + { + environment.setEconomy(null); + } + + environment.getLog().finest("CommunityBridge deactivated."); + } + + public static boolean isActive() + { + return active; + } + + private void reminderStart() + { + MinecraftUtilities.startTaskTimer(this, + calculateTaskTicks(environment.getConfiguration().linkingAutoEvery), + new Runnable() + { + @Override + public void run() + { + remindUnregisteredPlayers(); + } + } + ); + environment.getLog().fine("Auto reminder started."); + } + + /** + * Called by activate() if the auto sync is turned on, this starts up the + * auto synchronization task runner. + */ + private void autosyncStart() + { + MinecraftUtilities.startTaskTimer(this, + calculateTaskTicks(environment.getConfiguration().autoSyncEvery), + new Runnable() + { + @Override + public void run() + { + environment.getWebApplication().synchronizeAll(); + } + } + ); + environment.getLog().fine("Auto synchronization started."); + } + + /** + * Reminds a single player to register if they are not registered. + * If linking-kick-unregistered is turned on, an unregistered player will + * be kicked. + */ + private void remindPlayer(Player player) { + String userID = environment.getUserPlayerLinker().getUserID(player); + if (userID == null || userID.isEmpty()) { + String playerName = player.getName(); + if (environment.getConfiguration().linkingKickUnregistered) { + player.kickPlayer(environment.getConfiguration().messages.get("link-unregistered-player")); + environment.getLog().info(playerName + " kicked because they are not registered."); + } else { + player.sendMessage(ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-reminder")); + environment.getLog().fine(playerName + " issued unregistered reminder notice"); + } + } + } + + /** + * Calls remindPlayer() for all connected players. Called by the reminder + * task. + */ + @SuppressWarnings("deprecation") +private void remindUnregisteredPlayers() { + environment.getLog().finest("Running unregistered auto reminder."); + + for (Player player : Bukkit.getOnlinePlayers()) { + remindPlayer(player); + } + environment.getLog().finest("Unregistered auto reminder complete."); + } + + private void activateMetrics() + { + if (environment.getConfiguration().usePluginMetrics) + { + try + { + metrics = new CBMetrics(this); + Graph permsGraph = metrics.createGraph("Permissions Plugin Used"); + + if (environment.getPermissionHandler() == null) + { + permsGraph.addPlotter(new CBMetrics.Plotter("None") + { + @Override + public int getValue() + { + return 1; + } + }); + } + else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("bPerms")) + { + permsGraph.addPlotter(new CBMetrics.Plotter("bPermissions") + { + @Override + public int getValue() + { + return 1; + } + }); + } + else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("GroupManager")) + { + permsGraph.addPlotter(new CBMetrics.Plotter("GroupManager") + { + @Override + public int getValue() + { + return 1; + } + }); + } + else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("PermsBukkit")) + { + permsGraph.addPlotter(new CBMetrics.Plotter("PermissionsBukkit") + { + @Override + public int getValue() + { + return 1; + } + }); + } + else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("PEX")) + { + permsGraph.addPlotter(new CBMetrics.Plotter("PermissionsEx") + { + @Override + public int getValue() + { + return 1; + } + }); + } + else if (environment.getConfiguration().permissionsSystem.equalsIgnoreCase("Vault")) + { + permsGraph.addPlotter(new CBMetrics.Plotter("Vault") + { + @Override + public int getValue() + { + return 1; + } + }); + } + metrics.start(); + environment.getLog().fine("Plugin Metrics activated."); + } + catch (IOException e) + { + environment.getLog().warning("Plugin Metrics activation failed."); + } + } + } + + private long calculateTaskTicks(final long every) + { + if (environment.getConfiguration().autoEveryUnit.startsWith("sec")) + { + return every * 20; // 20 ticks per second. + } + else if (environment.getConfiguration().autoEveryUnit.startsWith("min")) + { + return every * 1200; // 20 ticks per second, 60 sec/minute + } + else if (environment.getConfiguration().autoEveryUnit.startsWith("hou")) + { + return every * 72000; // 20 ticks/s 60s/m, 60m/h + } + else if (environment.getConfiguration().autoEveryUnit.startsWith("day")) + { + return every * 1728000; // 20 ticks/s 60s/m, 60m/h, 24h/day + } + else + { + // Effectively defaulting to ticks. + return every; + } + } + + private void javaVersionCheck() + { + int javaVersion = Integer.parseInt(System.getProperty("java.version").split("\\.")[1]); + + if (javaVersion < 7) + { + environment.getLog().warning("Future versions of CommunityBridge may require Java 7 or later. It is recommended you upgrade your JRE."); + } + } + + private void disableEconomyBasedFeatures() + { + environment.getConfiguration().economyEnabled = false; + environment.getConfiguration().walletEnabled = false; + } +} diff --git a/src/org/communitybridge/main/DatabaseHandler.java b/src/org/communitybridge/main/DatabaseHandler.java index a2e6514..c07ed43 100644 --- a/src/org/communitybridge/main/DatabaseHandler.java +++ b/src/org/communitybridge/main/DatabaseHandler.java @@ -1,281 +1,281 @@ -package org.communitybridge.main; - -import java.net.MalformedURLException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; -import org.communitybridge.utility.Log; - -public class DatabaseHandler -{ - private Log log; - private Connection connection; - private String dblocation; - private String username; - private String password; - private String database; - private String localAddress; - - public DatabaseHandler(Log log, String dbLocation, String database, String username, String password, String localAddress) - { - this.log = log; - this.dblocation = dbLocation; - this.database = database; - this.username = username; - this.password = password; - this.localAddress = localAddress; - } - - private void openConnection() throws MalformedURLException, InstantiationException, IllegalAccessException - { - try - { - Class.forName("com.mysql.jdbc.Driver"); - Properties properties = new Properties(); - properties.setProperty("user", username); - properties.setProperty("password", password); - if (!localAddress.isEmpty()) - { - properties.setProperty("localSocketAddress", localAddress); - } - connection = DriverManager.getConnection("jdbc:mysql://" + dblocation + "/" + database, properties); - } - catch (ClassNotFoundException exception) - { - log.severe("No MySQL Driver Found:" + exception.getMessage()); - connection = null; - } - catch (SQLException exception) - { - log.severe("Could not connect to MySQL Server:" + exception.getMessage()); - connection = null; - } - } - - public boolean checkConnection() - { - if (this.connection == null) - { - try - { - openConnection(); - if (this.connection == null) - { - return false; - } - return true; - } - catch (MalformedURLException exception) - { - log.severe("MalformedURLException! " + exception.getMessage()); - } - catch (InstantiationException exception) - { - log.severe("InstantiationExceptioon! " + exception.getMessage()); - } - catch (IllegalAccessException exception) - { - log.severe("IllegalAccessException! " + exception.getMessage()); - } - return false; - } - - try - { - return !connection.isClosed(); - } - catch (SQLException e) - { - return false; - } - } - - public void closeConnection() { - try - { - if (this.connection != null) - { - this.connection.close(); - } - } - catch (Exception e) - { - log.warning("Failed to close database connection! " + e.getMessage()); - } - } - - public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException - { - if (this.connection == null) - { - openConnection(); - return this.connection; - } - else - { - try - { - if (this.connection.isClosed()) - { - openConnection(); - } - - Statement statement = connection.createStatement(); - statement.setQueryTimeout(5); - ResultSet result = statement.executeQuery("SELECT 1"); - - if (result.next()) - { - return this.connection; - } - openConnection(); - return this.connection; - } - catch (SQLException exception) - { - try - { - openConnection(); - - Statement statement = connection.createStatement(); - statement.setQueryTimeout(5); - ResultSet result = statement.executeQuery("SELECT 1"); - if (result.next()) - { - return this.connection; - } - } - catch (SQLException exception2) - { - log.warning("Database Connection Exception: " + exception2.getMessage()); - } - } - } - return null; - } - - public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - Connection connectionLocal = getConnection(); - - if (connectionLocal == null) - { - return null; - } - - Statement statement = connectionLocal.createStatement(); - - statement.setQueryTimeout(10); - - return statement.executeQuery(query); - } - - public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - try - { - Connection connectionLocal = getConnection(); - - if (connectionLocal != null) - { - Statement statement = connectionLocal.createStatement(); - statement.executeUpdate(query); - } - } - catch (SQLException exception) - { - if (!exception.toString().contains("not return ResultSet")) - { - throw exception; - } - } - } - - public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException - { - try - { - Connection connectionLocal = getConnection(); - - if (connectionLocal != null) - { - Statement statement = connectionLocal.createStatement(); - statement.executeUpdate(query); - } - } - catch (SQLException exception) - { - if (!exception.toString().contains("not return ResultSet")) - { - log.warning("Exception at SQL UPDATE Query: " + exception); - } - } - } - - public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException - { - try - { - Connection connectionLocal = getConnection(); - - if (connectionLocal != null) - { - Statement statement = connectionLocal.createStatement(); - statement.executeUpdate(query); - } - } - catch (SQLException exception) - { - if (!exception.toString().contains("not return ResultSet")) - { - log.warning("Exception at SQL DELETE Query: " + exception); - } - } - } - - public boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException - { - try - { - Connection connectionLocal = getConnection(); - - if (connectionLocal == null) - { - return false; - } - Statement statement = connectionLocal.createStatement(); - - ResultSet result = statement.executeQuery("SELECT * FROM " + table); - - if (result == null) - { - return false; - } - return true; - } - catch (SQLException exception) - { - if (exception.getMessage().contains("exist")) - { - return false; - } - - log.warning("Exception at SQL Query: " + exception.getMessage()); - } - try - { - if (sqlQuery("SELECT * FROM " + table) == null) - { - return true; - } - } - catch (SQLException exception) - { - log.warning("Exception at SQL Query: " + exception.getMessage()); - } - return false; - } -} +package org.communitybridge.main; + +import java.net.MalformedURLException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import org.communitybridge.utility.Log; + +public class DatabaseHandler +{ + private Log log; + private Connection connection; + private String dblocation; + private String username; + private String password; + private String database; + private String localAddress; + + public DatabaseHandler(Log log, String dbLocation, String database, String username, String password, String localAddress) + { + this.log = log; + this.dblocation = dbLocation; + this.database = database; + this.username = username; + this.password = password; + this.localAddress = localAddress; + } + + private void openConnection() throws MalformedURLException, InstantiationException, IllegalAccessException + { + try + { + Class.forName("com.mysql.jdbc.Driver"); + Properties properties = new Properties(); + properties.setProperty("user", username); + properties.setProperty("password", password); + if (!localAddress.isEmpty()) + { + properties.setProperty("localSocketAddress", localAddress); + } + connection = DriverManager.getConnection("jdbc:mysql://" + dblocation + "/" + database, properties); + } + catch (ClassNotFoundException exception) + { + log.severe("No MySQL Driver Found:" + exception.getMessage()); + connection = null; + } + catch (SQLException exception) + { + log.severe("Could not connect to MySQL Server:" + exception.getMessage()); + connection = null; + } + } + + public boolean checkConnection() + { + if (this.connection == null) + { + try + { + openConnection(); + if (this.connection == null) + { + return false; + } + return true; + } + catch (MalformedURLException exception) + { + log.severe("MalformedURLException! " + exception.getMessage()); + } + catch (InstantiationException exception) + { + log.severe("InstantiationExceptioon! " + exception.getMessage()); + } + catch (IllegalAccessException exception) + { + log.severe("IllegalAccessException! " + exception.getMessage()); + } + return false; + } + + try + { + return !connection.isClosed(); + } + catch (SQLException e) + { + return false; + } + } + + public void closeConnection() { + try + { + if (this.connection != null) + { + this.connection.close(); + } + } + catch (Exception e) + { + log.warning("Failed to close database connection! " + e.getMessage()); + } + } + + public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException + { + if (this.connection == null) + { + openConnection(); + return this.connection; + } + else + { + try + { + if (this.connection.isClosed()) + { + openConnection(); + } + + Statement statement = connection.createStatement(); + statement.setQueryTimeout(5); + ResultSet result = statement.executeQuery("SELECT 1"); + + if (result.next()) + { + return this.connection; + } + openConnection(); + return this.connection; + } + catch (SQLException exception) + { + try + { + openConnection(); + + Statement statement = connection.createStatement(); + statement.setQueryTimeout(5); + ResultSet result = statement.executeQuery("SELECT 1"); + if (result.next()) + { + return this.connection; + } + } + catch (SQLException exception2) + { + log.warning("Database Connection Exception: " + exception2.getMessage()); + } + } + } + return null; + } + + public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + Connection connectionLocal = getConnection(); + + if (connectionLocal == null) + { + return null; + } + + Statement statement = connectionLocal.createStatement(); + + statement.setQueryTimeout(10); + + return statement.executeQuery(query); + } + + public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + try + { + Connection connectionLocal = getConnection(); + + if (connectionLocal != null) + { + Statement statement = connectionLocal.createStatement(); + statement.executeUpdate(query); + } + } + catch (SQLException exception) + { + if (!exception.toString().contains("not return ResultSet")) + { + throw exception; + } + } + } + + public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException + { + try + { + Connection connectionLocal = getConnection(); + + if (connectionLocal != null) + { + Statement statement = connectionLocal.createStatement(); + statement.executeUpdate(query); + } + } + catch (SQLException exception) + { + if (!exception.toString().contains("not return ResultSet")) + { + log.warning("Exception at SQL UPDATE Query: " + exception); + } + } + } + + public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException + { + try + { + Connection connectionLocal = getConnection(); + + if (connectionLocal != null) + { + Statement statement = connectionLocal.createStatement(); + statement.executeUpdate(query); + } + } + catch (SQLException exception) + { + if (!exception.toString().contains("not return ResultSet")) + { + log.warning("Exception at SQL DELETE Query: " + exception); + } + } + } + + public boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException + { + try + { + Connection connectionLocal = getConnection(); + + if (connectionLocal == null) + { + return false; + } + Statement statement = connectionLocal.createStatement(); + + ResultSet result = statement.executeQuery("SELECT * FROM " + table); + + if (result == null) + { + return false; + } + return true; + } + catch (SQLException exception) + { + if (exception.getMessage().contains("exist")) + { + return false; + } + + log.warning("Exception at SQL Query: " + exception.getMessage()); + } + try + { + if (sqlQuery("SELECT * FROM " + table) == null) + { + return true; + } + } + catch (SQLException exception) + { + log.warning("Exception at SQL Query: " + exception.getMessage()); + } + return false; + } +} diff --git a/src/org/communitybridge/main/PlayerListener.java b/src/org/communitybridge/main/PlayerListener.java index 5f2fd83..0b8cf1b 100644 --- a/src/org/communitybridge/main/PlayerListener.java +++ b/src/org/communitybridge/main/PlayerListener.java @@ -1,174 +1,174 @@ -package org.communitybridge.main; - -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -public class PlayerListener implements Listener -{ - private Environment environment; - - public PlayerListener(Environment environment) - { - this.environment = environment; - } - - /** - * This method is called by CraftBukkit as the player connects to the server. - * We perform the initial linking here so that we can reject the login if - * linking-kick-unregistered is turned on. - */ - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) - { - String uuid = event.getUniqueId().toString(); - String name = event.getName(); - environment.getUserPlayerLinker().removeUserIDFromCache(uuid, name); - - String userID = environment.getUserPlayerLinker().getUserID(uuid, name); - if (userID.isEmpty()) - { - preLoginUnregisteredPlayer(event); - } - else - { - preLoginRegisteredPlayer(userID, event); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(PlayerJoinEvent event) - { - Player player = event.getPlayer(); - - if (environment.getUserPlayerLinker().getUserID(player).isEmpty()) - { - joinUnregistered(player); - } - else - { - joinRegistered(player); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerQuit(PlayerQuitEvent event) - { - if (environment.getConfiguration().syncDuringQuit) - { - environment.getWebApplication().runSynchronizePlayer(environment, event.getPlayer(), false); - } - } // onPlayerQuit - - private void preLoginRegisteredPlayer(String userID, AsyncPlayerPreLoginEvent event) - { - environment.getLog().fine(event.getName() + " linked to web application user ID #" + userID + "."); - - if (environment.getConfiguration().avatarEnabled && environment.getConfiguration().requireAvatar && environment.getWebApplication().playerHasAvatar(userID) == false) - { - kickPlayer(event, "require-avatar-message"); - } - - if (environment.getConfiguration().postCountEnabled && environment.getConfiguration().requireMinimumPosts && environment.getWebApplication().getUserPostCount(userID) < environment.getConfiguration().requirePostsPostCount) - { - kickPlayer(event, "require-minimum-posts-message"); - } - } - - private void preLoginUnregisteredPlayer(AsyncPlayerPreLoginEvent event) - { - if (environment.getConfiguration().linkingKickUnregistered) - { - event.setKickMessage(environment.getConfiguration().messages.get("link-unregistered-player")); - event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST); - } - - if (environment.getConfiguration().requireAvatar) - { - kickPlayer(event, "require-avatar-message"); - } - - if (environment.getConfiguration().requireMinimumPosts) - { - kickPlayer(event, "require-minimum-posts-message"); - } - } - - private void kickPlayer(AsyncPlayerPreLoginEvent event, String messageKey) - { - event.setKickMessage(environment.getConfiguration().messages.get(messageKey)); - event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); - } - - private void joinUnregistered(Player player) - { - if (environment.getConfiguration().linkingNotifyUnregistered) - { - String message = ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-player"); - player.sendMessage(message); - } // if config.linkingNotifyUnregistered - - if (!environment.getConfiguration().linkingUnregisteredGroup.isEmpty()) - { - environment.getPermissionHandler().addToGroup(player, environment.getConfiguration().linkingUnregisteredGroup); - if (environment.getConfiguration().linkingNotifyPlayerGroup) - { - String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change"); - message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingUnregisteredGroup); - player.sendMessage(message); - } - - if (environment.getConfiguration().linkingUnregisterFormerRegistered) - { - environment.getPermissionHandler().removeFromGroup(player, environment.getConfiguration().linkingRegisteredGroup); - } - } - } - - private void joinRegistered(Player player) - { - if (environment.getConfiguration().linkingNotifyRegistered) - { - String message = ChatColor.GREEN + environment.getConfiguration().messages.get("link-registered-player"); - player.sendMessage(message); - } - - maybeSwitchToRegistered(player); - - if (environment.getConfiguration().syncDuringJoin) - { - environment.getWebApplication().runSynchronizePlayer(environment, player, true); - } - } - - private void maybeSwitchToRegistered(Player player) - { - // We don't use the linking registered group if it is empty or group - // synchronization is active. - if (environment.getConfiguration().groupSynchronizationActive || environment.getConfiguration().linkingRegisteredGroup.isEmpty()) - { - return; - } - - // if this rule is turned on, we won't change groups unless they're - // a member of the unregistered group or they have no groups. - if (environment.getConfiguration().linkingRegisteredFormerUnregisteredOnly && !environment.getPermissionHandler().isMemberOfGroup(player, environment.getConfiguration().linkingUnregisteredGroup) && !environment.getPermissionHandler().getGroupsPure(player).isEmpty()) - { - return; - } - - environment.getPermissionHandler().switchGroup(player, environment.getConfiguration().linkingUnregisteredGroup, environment.getConfiguration().linkingRegisteredGroup); - - if (environment.getConfiguration().linkingNotifyPlayerGroup) - { - String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change"); - message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingRegisteredGroup); - player.sendMessage(message); - } - } -} +package org.communitybridge.main; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerListener implements Listener +{ + private Environment environment; + + public PlayerListener(Environment environment) + { + this.environment = environment; + } + + /** + * This method is called by CraftBukkit as the player connects to the server. + * We perform the initial linking here so that we can reject the login if + * linking-kick-unregistered is turned on. + */ + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) + { + String uuid = event.getUniqueId().toString(); + String name = event.getName(); + environment.getUserPlayerLinker().removeUserIDFromCache(uuid, name); + + String userID = environment.getUserPlayerLinker().getUserID(uuid, name); + if (userID.isEmpty()) + { + preLoginUnregisteredPlayer(event); + } + else + { + preLoginRegisteredPlayer(userID, event); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent event) + { + Player player = event.getPlayer(); + + if (environment.getUserPlayerLinker().getUserID(player).isEmpty()) + { + joinUnregistered(player); + } + else + { + joinRegistered(player); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(PlayerQuitEvent event) + { + if (environment.getConfiguration().syncDuringQuit) + { + environment.getWebApplication().runSynchronizePlayer(environment, event.getPlayer(), false); + } + } // onPlayerQuit + + private void preLoginRegisteredPlayer(String userID, AsyncPlayerPreLoginEvent event) + { + environment.getLog().fine(event.getName() + " linked to web application user ID #" + userID + "."); + + if (environment.getConfiguration().avatarEnabled && environment.getConfiguration().requireAvatar && environment.getWebApplication().playerHasAvatar(userID) == false) + { + kickPlayer(event, "require-avatar-message"); + } + + if (environment.getConfiguration().postCountEnabled && environment.getConfiguration().requireMinimumPosts && environment.getWebApplication().getUserPostCount(userID) < environment.getConfiguration().requirePostsPostCount) + { + kickPlayer(event, "require-minimum-posts-message"); + } + } + + private void preLoginUnregisteredPlayer(AsyncPlayerPreLoginEvent event) + { + if (environment.getConfiguration().linkingKickUnregistered) + { + event.setKickMessage(environment.getConfiguration().messages.get("link-unregistered-player")); + event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST); + } + + if (environment.getConfiguration().requireAvatar) + { + kickPlayer(event, "require-avatar-message"); + } + + if (environment.getConfiguration().requireMinimumPosts) + { + kickPlayer(event, "require-minimum-posts-message"); + } + } + + private void kickPlayer(AsyncPlayerPreLoginEvent event, String messageKey) + { + event.setKickMessage(environment.getConfiguration().messages.get(messageKey)); + event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); + } + + private void joinUnregistered(Player player) + { + if (environment.getConfiguration().linkingNotifyUnregistered) + { + String message = ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-player"); + player.sendMessage(message); + } // if config.linkingNotifyUnregistered + + if (!environment.getConfiguration().linkingUnregisteredGroup.isEmpty()) + { + environment.getPermissionHandler().addToGroup(player, environment.getConfiguration().linkingUnregisteredGroup); + if (environment.getConfiguration().linkingNotifyPlayerGroup) + { + String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change"); + message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingUnregisteredGroup); + player.sendMessage(message); + } + + if (environment.getConfiguration().linkingUnregisterFormerRegistered) + { + environment.getPermissionHandler().removeFromGroup(player, environment.getConfiguration().linkingRegisteredGroup); + } + } + } + + private void joinRegistered(Player player) + { + if (environment.getConfiguration().linkingNotifyRegistered) + { + String message = ChatColor.GREEN + environment.getConfiguration().messages.get("link-registered-player"); + player.sendMessage(message); + } + + maybeSwitchToRegistered(player); + + if (environment.getConfiguration().syncDuringJoin) + { + environment.getWebApplication().runSynchronizePlayer(environment, player, true); + } + } + + private void maybeSwitchToRegistered(Player player) + { + // We don't use the linking registered group if it is empty or group + // synchronization is active. + if (environment.getConfiguration().groupSynchronizationActive || environment.getConfiguration().linkingRegisteredGroup.isEmpty()) + { + return; + } + + // if this rule is turned on, we won't change groups unless they're + // a member of the unregistered group or they have no groups. + if (environment.getConfiguration().linkingRegisteredFormerUnregisteredOnly && !environment.getPermissionHandler().isMemberOfGroup(player, environment.getConfiguration().linkingUnregisteredGroup) && !environment.getPermissionHandler().getGroupsPure(player).isEmpty()) + { + return; + } + + environment.getPermissionHandler().switchGroup(player, environment.getConfiguration().linkingUnregisteredGroup, environment.getConfiguration().linkingRegisteredGroup); + + if (environment.getConfiguration().linkingNotifyPlayerGroup) + { + String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change"); + message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingRegisteredGroup); + player.sendMessage(message); + } + } +} diff --git a/src/org/communitybridge/main/SQL.java b/src/org/communitybridge/main/SQL.java index 0e5419a..2560fef 100644 --- a/src/org/communitybridge/main/SQL.java +++ b/src/org/communitybridge/main/SQL.java @@ -1,78 +1,78 @@ -package org.communitybridge.main; - -import java.net.MalformedURLException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import org.communitybridge.utility.Log; - -public class SQL -{ - private Log log; - private String host; - private DatabaseHandler manageDB; - private String username; - private String password; - private String database; - private String localAddress; - - public SQL(Log log, String host, String database, String username, String password, String localAddress) - { - this.log = log; - this.database = database; - this.host = host; - this.username = username; - this.password = password; - this.localAddress = localAddress; - } - - public boolean initialize() - { - this.manageDB = new DatabaseHandler(log, host, database, username, password, localAddress); - return false; - } - - public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - log.finest(query); - return this.manageDB.sqlQuery(query); - } - - public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - log.finest(query); - this.manageDB.insertQuery(query); - } - - public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException - { - log.finest(query); - this.manageDB.updateQuery(query); - } - - public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException - { - log.finest(query); - this.manageDB.deleteQuery(query); - } - - public Boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException - { - return this.manageDB.checkTable(table); - } - - public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException - { - return this.manageDB.getConnection(); - } - - public void close() - { - this.manageDB.closeConnection(); - } - - public boolean checkConnection() - { - return this.manageDB.checkConnection(); - } +package org.communitybridge.main; + +import java.net.MalformedURLException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.communitybridge.utility.Log; + +public class SQL +{ + private Log log; + private String host; + private DatabaseHandler manageDB; + private String username; + private String password; + private String database; + private String localAddress; + + public SQL(Log log, String host, String database, String username, String password, String localAddress) + { + this.log = log; + this.database = database; + this.host = host; + this.username = username; + this.password = password; + this.localAddress = localAddress; + } + + public boolean initialize() + { + this.manageDB = new DatabaseHandler(log, host, database, username, password, localAddress); + return false; + } + + public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + log.finest(query); + return this.manageDB.sqlQuery(query); + } + + public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + log.finest(query); + this.manageDB.insertQuery(query); + } + + public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException + { + log.finest(query); + this.manageDB.updateQuery(query); + } + + public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException + { + log.finest(query); + this.manageDB.deleteQuery(query); + } + + public Boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException + { + return this.manageDB.checkTable(table); + } + + public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException + { + return this.manageDB.getConnection(); + } + + public void close() + { + this.manageDB.closeConnection(); + } + + public boolean checkConnection() + { + return this.manageDB.checkConnection(); + } } \ No newline at end of file diff --git a/src/org/communitybridge/permissionhandlers/PermissionHandler.java b/src/org/communitybridge/permissionhandlers/PermissionHandler.java index 42c01da..1e18e02 100644 --- a/src/org/communitybridge/permissionhandlers/PermissionHandler.java +++ b/src/org/communitybridge/permissionhandlers/PermissionHandler.java @@ -1,66 +1,66 @@ -package org.communitybridge.permissionhandlers; - -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.communitybridge.main.BukkitWrapper; -import org.communitybridge.utility.StringUtilities; - -public abstract class PermissionHandler -{ - protected final String NOT_FOUND = " not found."; - protected final String NOT_ENABLED = " is not enabled."; - protected final String WRONG_VERSION = " should be at least version "; - - protected BukkitWrapper bukkit = new BukkitWrapper(); - - public abstract boolean addToGroup(Player player, String groupName); - public abstract List getGroups(Player player); - public abstract List getGroupsPure(Player player); - public abstract String getPrimaryGroup(Player player); - public abstract boolean isMemberOfGroup(Player player, String groupName); - public abstract boolean isPrimaryGroup(Player player, String groupName); - public abstract boolean removeFromGroup(Player player, String groupName); - public abstract boolean setPrimaryGroup(Player player, String groupName, String formerGroupName); - public abstract boolean supportsPrimaryGroups(); - - public void switchGroup(Player player, String formerGroupName, String newGroupName) - { - if (formerGroupName != null && !formerGroupName.isEmpty()) - { - removeFromGroup(player, formerGroupName); - } - addToGroup(player, newGroupName); - } - - protected void validate(Plugin plugin, String name, String version) throws IllegalStateException - { - if (plugin == null) - { - throw new IllegalStateException(name + NOT_FOUND); - } - - if (!plugin.isEnabled()) - { - throw new IllegalStateException(name + NOT_ENABLED); - } - - if (StringUtilities.compareVersion(plugin.getDescription().getVersion(), version) < 0) { - throw new IllegalStateException(name + WRONG_VERSION + version); - } - } - - protected String determineWorld(Player player) - { - String worldName; - if (player == null) - { - worldName = bukkit.getServer().getWorlds().get(0).getName(); - } - else - { - worldName = player.getWorld().getName(); - } - return worldName; - } -} +package org.communitybridge.permissionhandlers; + +import java.util.List; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.communitybridge.main.BukkitWrapper; +import org.communitybridge.utility.StringUtilities; + +public abstract class PermissionHandler +{ + protected final String NOT_FOUND = " not found."; + protected final String NOT_ENABLED = " is not enabled."; + protected final String WRONG_VERSION = " should be at least version "; + + protected BukkitWrapper bukkit = new BukkitWrapper(); + + public abstract boolean addToGroup(Player player, String groupName); + public abstract List getGroups(Player player); + public abstract List getGroupsPure(Player player); + public abstract String getPrimaryGroup(Player player); + public abstract boolean isMemberOfGroup(Player player, String groupName); + public abstract boolean isPrimaryGroup(Player player, String groupName); + public abstract boolean removeFromGroup(Player player, String groupName); + public abstract boolean setPrimaryGroup(Player player, String groupName, String formerGroupName); + public abstract boolean supportsPrimaryGroups(); + + public void switchGroup(Player player, String formerGroupName, String newGroupName) + { + if (formerGroupName != null && !formerGroupName.isEmpty()) + { + removeFromGroup(player, formerGroupName); + } + addToGroup(player, newGroupName); + } + + protected void validate(Plugin plugin, String name, String version) throws IllegalStateException + { + if (plugin == null) + { + throw new IllegalStateException(name + NOT_FOUND); + } + + if (!plugin.isEnabled()) + { + throw new IllegalStateException(name + NOT_ENABLED); + } + + if (StringUtilities.compareVersion(plugin.getDescription().getVersion(), version) < 0) { + throw new IllegalStateException(name + WRONG_VERSION + version); + } + } + + protected String determineWorld(Player player) + { + String worldName; + if (player == null) + { + worldName = bukkit.getServer().getWorlds().get(0).getName(); + } + else + { + worldName = player.getWorld().getName(); + } + return worldName; + } +} diff --git a/src/org/communitybridge/permissionhandlers/PermissionHandlerGroupManager.java b/src/org/communitybridge/permissionhandlers/PermissionHandlerGroupManager.java index c927193..613cc32 100644 --- a/src/org/communitybridge/permissionhandlers/PermissionHandlerGroupManager.java +++ b/src/org/communitybridge/permissionhandlers/PermissionHandlerGroupManager.java @@ -1,204 +1,204 @@ -package org.communitybridge.permissionhandlers; - -import java.util.ArrayList; -import java.util.List; -import org.anjocaido.groupmanager.GroupManager; -import org.anjocaido.groupmanager.data.Group; -import org.anjocaido.groupmanager.data.User; -import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; -import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -/** - * 2013-May-03: GroupManager has a notion of a primary group (an odd notion) - * - */ -public class PermissionHandlerGroupManager extends PermissionHandler -{ - private static GroupManager groupManager; - - public PermissionHandlerGroupManager() throws IllegalStateException - { - Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("GroupManager"); - - validate(plugin, "GroupManager", "2.1.6"); - - groupManager = (GroupManager)plugin; - } - - @Override - public boolean addToGroup(Player player, String groupName) - { - OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); - - if (worldHolder == null) - { - return false; - } - - User user = worldHolder.getUser(player.getName()); - - if (user == null) - { - return false; - } - Group group = getOrCreateGroup(worldHolder, groupName); - - // If it is a primary group, set as a primary group. - if (user.getGroup().equals(worldHolder.getDefaultGroup())) - { - user.setGroup(group, false); - } - else if (group.getInherits().contains(user.getGroup().getName().toLowerCase())) - { - user.setGroup(group, false); - } - else - { - user.addSubGroup(group); - } - - return true; - } - - @Override - public List getGroups(Player player) - { - OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); - - if (worldHolder == null) - { - return new ArrayList(); - } - - User user = worldHolder.getUser(player.getName()); - - if (user == null) - { - return new ArrayList(); - } - - return user.subGroupListStringCopy(); - } - - @Override - public List getGroupsPure(Player player) - { - return getGroups(player); - } - - @Override - public String getPrimaryGroup(Player player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player)); - - if (handler == null) - { - throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler"); - } - - String group = handler.getGroup(player.getName()); - - if (group == null) - { - return ""; - } - else - { - return group; - } - } - - @Override - public boolean isMemberOfGroup(Player player, String groupName) throws RuntimeException - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player)); - - if (handler == null) - { - throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler"); - } - else - { - return handler.inGroup(player.getName(), groupName); - } - } - - @Override - public boolean isPrimaryGroup(Player player, String groupName) - { - return groupName.equalsIgnoreCase(getPrimaryGroup(player)); - } - - @Override - public boolean removeFromGroup(Player player, String groupName) - { - OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); - - if (worldHolder == null) - { - return false; - } - - User user = worldHolder.getUser(player.getName()); - - if (user == null) - { - return false; - } - - if (user.getGroup() != null && user.getGroup().getName().equalsIgnoreCase(groupName)) - { - user.setGroup(worldHolder.getDefaultGroup(), false); - return true; - } - else - { - Group group = getOrCreateGroup(worldHolder, groupName); - return user.removeSubGroup(group); - } - } - - @Override - public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) - { - OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); - - if (worldHolder == null) - { - return false; - } - - User user = worldHolder.getUser(player.getName()); - - if (user == null) - { - return false; - } - - Group group = getOrCreateGroup(worldHolder, groupName); - user.setGroup(group, false); - - return true; - } - - @Override - public boolean supportsPrimaryGroups() - { - return true; - } - - private Group getOrCreateGroup(OverloadedWorldHolder worldHolder, String groupName) - { - Group group = worldHolder.getGroup(groupName); - - if (group == null) - { - group = worldHolder.createGroup(groupName); - } - - return group; - } -} +package org.communitybridge.permissionhandlers; + +import java.util.ArrayList; +import java.util.List; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * 2013-May-03: GroupManager has a notion of a primary group (an odd notion) + * + */ +public class PermissionHandlerGroupManager extends PermissionHandler +{ + private static GroupManager groupManager; + + public PermissionHandlerGroupManager() throws IllegalStateException + { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("GroupManager"); + + validate(plugin, "GroupManager", "2.1.6"); + + groupManager = (GroupManager)plugin; + } + + @Override + public boolean addToGroup(Player player, String groupName) + { + OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); + + if (worldHolder == null) + { + return false; + } + + User user = worldHolder.getUser(player.getName()); + + if (user == null) + { + return false; + } + Group group = getOrCreateGroup(worldHolder, groupName); + + // If it is a primary group, set as a primary group. + if (user.getGroup().equals(worldHolder.getDefaultGroup())) + { + user.setGroup(group, false); + } + else if (group.getInherits().contains(user.getGroup().getName().toLowerCase())) + { + user.setGroup(group, false); + } + else + { + user.addSubGroup(group); + } + + return true; + } + + @Override + public List getGroups(Player player) + { + OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); + + if (worldHolder == null) + { + return new ArrayList(); + } + + User user = worldHolder.getUser(player.getName()); + + if (user == null) + { + return new ArrayList(); + } + + return user.subGroupListStringCopy(); + } + + @Override + public List getGroupsPure(Player player) + { + return getGroups(player); + } + + @Override + public String getPrimaryGroup(Player player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player)); + + if (handler == null) + { + throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler"); + } + + String group = handler.getGroup(player.getName()); + + if (group == null) + { + return ""; + } + else + { + return group; + } + } + + @Override + public boolean isMemberOfGroup(Player player, String groupName) throws RuntimeException + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player)); + + if (handler == null) + { + throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler"); + } + else + { + return handler.inGroup(player.getName(), groupName); + } + } + + @Override + public boolean isPrimaryGroup(Player player, String groupName) + { + return groupName.equalsIgnoreCase(getPrimaryGroup(player)); + } + + @Override + public boolean removeFromGroup(Player player, String groupName) + { + OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); + + if (worldHolder == null) + { + return false; + } + + User user = worldHolder.getUser(player.getName()); + + if (user == null) + { + return false; + } + + if (user.getGroup() != null && user.getGroup().getName().equalsIgnoreCase(groupName)) + { + user.setGroup(worldHolder.getDefaultGroup(), false); + return true; + } + else + { + Group group = getOrCreateGroup(worldHolder, groupName); + return user.removeSubGroup(group); + } + } + + @Override + public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) + { + OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName()); + + if (worldHolder == null) + { + return false; + } + + User user = worldHolder.getUser(player.getName()); + + if (user == null) + { + return false; + } + + Group group = getOrCreateGroup(worldHolder, groupName); + user.setGroup(group, false); + + return true; + } + + @Override + public boolean supportsPrimaryGroups() + { + return true; + } + + private Group getOrCreateGroup(OverloadedWorldHolder worldHolder, String groupName) + { + Group group = worldHolder.getGroup(groupName); + + if (group == null) + { + group = worldHolder.createGroup(groupName); + } + + return group; + } +} diff --git a/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsBukkit.java b/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsBukkit.java index ca8cc67..a2aab8d 100644 --- a/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsBukkit.java +++ b/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsBukkit.java @@ -1,120 +1,123 @@ -package org.communitybridge.permissionhandlers; - -import com.platymuus.bukkit.permissions.Group; -import com.platymuus.bukkit.permissions.PermissionsPlugin; -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -public class PermissionHandlerPermissionsBukkit extends PermissionHandler -{ - private static PermissionsPlugin permissions; - - public PermissionHandlerPermissionsBukkit() throws IllegalStateException - { - if (permissions == null) - { - Plugin plugin; - plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsBukkit"); - validate(plugin, "PermissionsBukkit", "2.3"); - permissions = (PermissionsPlugin) plugin; - } - } - - @Override - public boolean addToGroup(Player player, String groupName) - { - return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player addgroup " + player.getUniqueId().toString() + " " + groupName); - } - - @Override - public List getGroups(Player player) - { - List groupNames = new ArrayList(); - - for (Group group : permissions.getAllGroups()) - { - if (isMemberOfGroup(player, group)) - { - groupNames.add(group.getName()); - } - } - - return groupNames; - } - - @Override - public List getGroupsPure(Player player) - { - return getGroups(player); - } - - @Override - public String getPrimaryGroup(Player player) - { - List groups = getGroups(player); - if (groups.isEmpty()) - { - return ""; - } - return groups.get(0); - } - - @Override - public boolean isMemberOfGroup(Player player, String groupName) - { - Group group = permissions.getGroup(groupName); - - if (group == null) - { - return false; - } - - return isMemberOfGroup(player, group); - } - - private boolean isMemberOfGroup(Player player, Group group) - { - return group.getPlayers().contains(player.getUniqueId().toString()) - ||group.getPlayers().contains(player.getName().toLowerCase()); - } - - @Override - public boolean isPrimaryGroup(Player player, String groupName) - { - String primaryGroup = this.getPrimaryGroup(player); - return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup); - } - - @Override - public boolean removeFromGroup(Player player, String groupName) - { - return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player removegroup " + player.getUniqueId().toString() + " " + groupName); - } - - /** - * PermissionsBukkit doesn't have a primary group, so this calls AddToGroup. - */ - @Override - public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) - { - boolean result; - if (formerGroupName == null) - { - result = true; - } - else - { - result = removeFromGroup(player, formerGroupName); - } - return result && addToGroup(player, groupName); - } - - @Override - public boolean supportsPrimaryGroups() - { - return false; - } -} +package org.communitybridge.permissionhandlers; + +import com.platymuus.bukkit.permissions.Group; +import com.platymuus.bukkit.permissions.PermissionsPlugin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +public class PermissionHandlerPermissionsBukkit extends PermissionHandler +{ + private static PermissionsPlugin permissions; + + public PermissionHandlerPermissionsBukkit() throws IllegalStateException + { + if (permissions == null) + { + Plugin plugin; + plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsBukkit"); + validate(plugin, "PermissionsBukkit", "2.3"); + permissions = (PermissionsPlugin) plugin; + } + } + + @Override + public boolean addToGroup(Player player, String groupName) + { + return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player addgroup " + player.getUniqueId().toString() + " " + groupName); + } + + @Override + public List getGroups(Player player) + { + List groupNames = new ArrayList(); + + for (Group group : permissions.getAllGroups()) + { + if (isMemberOfGroup(player, group)) + { + groupNames.add(group.getName()); + } + } + + return groupNames; + } + + @Override + public List getGroupsPure(Player player) + { + return getGroups(player); + } + + @Override + public String getPrimaryGroup(Player player) + { + List groups = getGroups(player); + if (groups.isEmpty()) + { + return ""; + } + return groups.get(0); + } + + @Override + public boolean isMemberOfGroup(Player player, String groupName) + { + Group group = permissions.getGroup(groupName); + + if (group == null) + { + return false; + } + + return isMemberOfGroup(player, group); + } + + @SuppressWarnings("deprecation") + private boolean isMemberOfGroup(Player player, Group group) + { + return group.getPlayers().contains(player.getUniqueId().toString()) + ||group.getPlayers().contains(player.getName().toLowerCase()); + } + + @Override + public boolean isPrimaryGroup(Player player, String groupName) + { + String primaryGroup = this.getPrimaryGroup(player); + return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup); + } + + @Override + public boolean removeFromGroup(Player player, String groupName) + { + return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player removegroup " + player.getUniqueId().toString() + " " + groupName); + } + + /** + * PermissionsBukkit doesn't have a primary group, so this calls AddToGroup. + */ + @Override + public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) + { + boolean result; + if (formerGroupName == null) + { + result = true; + } + else + { + result = removeFromGroup(player, formerGroupName); + } + return result && addToGroup(player, groupName); + } + + @Override + public boolean supportsPrimaryGroups() + { + return false; + } +} diff --git a/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsEx.java b/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsEx.java index 9f75adf..54b1eec 100644 --- a/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsEx.java +++ b/src/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsEx.java @@ -1,133 +1,133 @@ -package org.communitybridge.permissionhandlers; - -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import ru.tehkode.permissions.PermissionGroup; -import ru.tehkode.permissions.PermissionUser; -import ru.tehkode.permissions.bukkit.PermissionsEx; - -public class PermissionHandlerPermissionsEx extends PermissionHandler -{ - public PermissionHandlerPermissionsEx() throws IllegalStateException - { - Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx"); - - validate(plugin, "PermissionsEx", "1.21.4"); - } - - @Override - public boolean addToGroup(Player player, String groupName) - { - PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName); - PermissionUser user = getPermissionUser(player); - if (group == null || user == null) - { - return false; - } - else - { - user.addGroup(group); - return true; - } - } - - @Override - public List getGroups(Player player) - { - PermissionUser permissionUser = getPermissionUser(player); - if (permissionUser == null) - { - return new ArrayList(); - } - return new ArrayList(permissionUser.getParentIdentifiers()); - } - - @Override - public List getGroupsPure(Player player) - { - List groups = getGroups(player); - - if (groups.size() == 1 && groups.get(0).equalsIgnoreCase("default")) - { - return new ArrayList(); - } - - return groups; - } - - @Override - public String getPrimaryGroup(Player player) - { - List groups = getGroupsPure(player); - if (groups.isEmpty()) - { - return ""; - } - - return groups.get(0); - } - - @Override - public boolean isMemberOfGroup(Player player, String groupName) - { - PermissionUser permissionUser = getPermissionUser(player); - - if (permissionUser == null) - { - return false; - } - - return permissionUser.inGroup(groupName, false); - } - - @Override - public boolean isPrimaryGroup(Player player, String groupName) - { - String primaryGroup = this.getPrimaryGroup(player); - return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup); - } - - @Override - public boolean removeFromGroup(Player player, String groupName) - { - PermissionUser permissionUser = getPermissionUser(player); - if (permissionUser == null) - { - return false; - } - - permissionUser.removeGroup(groupName); - return true; - } - - @Override - public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) - { - boolean result; - if (formerGroupName == null) - { - result = true; - } - else - { - result = removeFromGroup(player, formerGroupName); - } - return result && addToGroup(player, groupName); - } - - @Override - public boolean supportsPrimaryGroups() - { - return false; - } - - private PermissionUser getPermissionUser(Player player) - { - PermissionUser user = PermissionsEx.getUser(player); - user.getName(); - return user; - } -} +package org.communitybridge.permissionhandlers; + +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import ru.tehkode.permissions.PermissionGroup; +import ru.tehkode.permissions.PermissionUser; +import ru.tehkode.permissions.bukkit.PermissionsEx; + +public class PermissionHandlerPermissionsEx extends PermissionHandler +{ + public PermissionHandlerPermissionsEx() throws IllegalStateException + { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx"); + + validate(plugin, "PermissionsEx", "1.21.4"); + } + + @Override + public boolean addToGroup(Player player, String groupName) + { + PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName); + PermissionUser user = getPermissionUser(player); + if (group == null || user == null) + { + return false; + } + else + { + user.addGroup(group); + return true; + } + } + + @Override + public List getGroups(Player player) + { + PermissionUser permissionUser = getPermissionUser(player); + if (permissionUser == null) + { + return new ArrayList(); + } + return new ArrayList(permissionUser.getParentIdentifiers()); + } + + @Override + public List getGroupsPure(Player player) + { + List groups = getGroups(player); + + if (groups.size() == 1 && groups.get(0).equalsIgnoreCase("default")) + { + return new ArrayList(); + } + + return groups; + } + + @Override + public String getPrimaryGroup(Player player) + { + List groups = getGroupsPure(player); + if (groups.isEmpty()) + { + return ""; + } + + return groups.get(0); + } + + @Override + public boolean isMemberOfGroup(Player player, String groupName) + { + PermissionUser permissionUser = getPermissionUser(player); + + if (permissionUser == null) + { + return false; + } + + return permissionUser.inGroup(groupName, false); + } + + @Override + public boolean isPrimaryGroup(Player player, String groupName) + { + String primaryGroup = this.getPrimaryGroup(player); + return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup); + } + + @Override + public boolean removeFromGroup(Player player, String groupName) + { + PermissionUser permissionUser = getPermissionUser(player); + if (permissionUser == null) + { + return false; + } + + permissionUser.removeGroup(groupName); + return true; + } + + @Override + public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) + { + boolean result; + if (formerGroupName == null) + { + result = true; + } + else + { + result = removeFromGroup(player, formerGroupName); + } + return result && addToGroup(player, groupName); + } + + @Override + public boolean supportsPrimaryGroups() + { + return false; + } + + private PermissionUser getPermissionUser(Player player) + { + PermissionUser user = PermissionsEx.getUser(player); + user.getName(); + return user; + } +} diff --git a/src/org/communitybridge/utility/Log.java b/src/org/communitybridge/utility/Log.java index 4436646..7094131 100644 --- a/src/org/communitybridge/utility/Log.java +++ b/src/org/communitybridge/utility/Log.java @@ -1,199 +1,199 @@ -package org.communitybridge.utility; - -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Presents a familiar interface to the built-in logging facility while giving - * us our own level of control over logging levels. - * - * @author Feaelin (Iain E. Davis) - */ -public class Log -{ - @SuppressWarnings("NonConstantLogger") - private static Logger log; - private static Level level; - - /** - * Constructor for only passing in reference to the logger object. - * - * @param log Logger object referencing the Bukkit Server logger. - */ - public Log(Logger log) - { - Log.log = log; - level = Level.INFO; - } - - /** - * Constructor to specify both the logger and the initial logging level. - * - * @param log Logger object referencing the Bukkit Server logger. - * @param level Level type from java.util.logging.Level - */ - public Log(Logger log, Level level) - { - Log.log = log; - Log.level = level; - } - - /** - * Returns the current logging level. - * - * @return Level Java's Level enumerated type - */ - public Level getLevel() - { - return Log.level; - } - - /** - * Set the logging level based on a string. - * - * @param level String containing the specified level. One of: all, finest, finer, fine, config, info, warning, severe - */ - public void setLevel(String level) - { - if (level.equalsIgnoreCase("info")) - { - this.setLevel(Level.INFO); - } - else if (level.equalsIgnoreCase("config")) - { - this.setLevel(Level.CONFIG); - } - else if (level.equalsIgnoreCase("fine")) - { - this.setLevel(Level.FINE); - } - else if (level.equalsIgnoreCase("finer")) - { - this.setLevel(Level.FINER); - } - else if (level.equalsIgnoreCase("finest")) - { - this.setLevel(Level.FINEST); - } - else if (level.equalsIgnoreCase("all")) - { - this.setLevel(Level.ALL); - } - else if (level.equalsIgnoreCase("warning")) - { - this.setLevel(Level.WARNING); - } - else if (level.equalsIgnoreCase("severe")) - { - this.setLevel(Level.SEVERE); - } - } - - /** - * Sets the logging level using a java.util.logging.Level type - * - * @param level Level from java.util.logging.Level - */ - public void setLevel(Level level) - { - Log.level = level; - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void finest(String message) - { - // Finest: 300 - if (level.intValue() <= Level.FINEST.intValue()) - { - log.info(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void finer(String message) - { - // Finer: 400 - if (level.intValue() <= Level.FINER.intValue()) - { - log.info(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void fine(String message) - { - // Fine: 500 - if (level.intValue() <= Level.FINE.intValue()) - { - log.info(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void config(String message) - { - // Config: 700 - if (level.intValue() <= Level.CONFIG.intValue()) - { - log.info(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void info(String message) - { - // Info: 800 - if (level.intValue() <= Level.INFO.intValue()) - { - log.info(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void warning(String message) - { - // Warning: 900 - if (level.intValue() <= Level.WARNING.intValue()) - { - log.warning(message); - } - } - - /** - * Sends 'message' to the log if the logging level is high enough. - * - * @param message String containing message to be sent. - */ - public void severe(String message) - { - // Severe: 1000 - if (level.intValue() <= Level.SEVERE.intValue()) - { - log.severe(message); - } - } -} +package org.communitybridge.utility; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Presents a familiar interface to the built-in logging facility while giving + * us our own level of control over logging levels. + * + * @author Feaelin (Iain E. Davis) + */ +public class Log +{ + @SuppressWarnings("NonConstantLogger") + private static Logger log; + private static Level level; + + /** + * Constructor for only passing in reference to the logger object. + * + * @param log Logger object referencing the Bukkit Server logger. + */ + public Log(Logger log) + { + Log.log = log; + level = Level.INFO; + } + + /** + * Constructor to specify both the logger and the initial logging level. + * + * @param log Logger object referencing the Bukkit Server logger. + * @param level Level type from java.util.logging.Level + */ + public Log(Logger log, Level level) + { + Log.log = log; + Log.level = level; + } + + /** + * Returns the current logging level. + * + * @return Level Java's Level enumerated type + */ + public Level getLevel() + { + return Log.level; + } + + /** + * Set the logging level based on a string. + * + * @param level String containing the specified level. One of: all, finest, finer, fine, config, info, warning, severe + */ + public void setLevel(String level) + { + if (level.equalsIgnoreCase("info")) + { + this.setLevel(Level.INFO); + } + else if (level.equalsIgnoreCase("config")) + { + this.setLevel(Level.CONFIG); + } + else if (level.equalsIgnoreCase("fine")) + { + this.setLevel(Level.FINE); + } + else if (level.equalsIgnoreCase("finer")) + { + this.setLevel(Level.FINER); + } + else if (level.equalsIgnoreCase("finest")) + { + this.setLevel(Level.FINEST); + } + else if (level.equalsIgnoreCase("all")) + { + this.setLevel(Level.ALL); + } + else if (level.equalsIgnoreCase("warning")) + { + this.setLevel(Level.WARNING); + } + else if (level.equalsIgnoreCase("severe")) + { + this.setLevel(Level.SEVERE); + } + } + + /** + * Sets the logging level using a java.util.logging.Level type + * + * @param level Level from java.util.logging.Level + */ + public void setLevel(Level level) + { + Log.level = level; + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void finest(String message) + { + // Finest: 300 + if (level.intValue() <= Level.FINEST.intValue()) + { + log.info(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void finer(String message) + { + // Finer: 400 + if (level.intValue() <= Level.FINER.intValue()) + { + log.info(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void fine(String message) + { + // Fine: 500 + if (level.intValue() <= Level.FINE.intValue()) + { + log.info(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void config(String message) + { + // Config: 700 + if (level.intValue() <= Level.CONFIG.intValue()) + { + log.info(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void info(String message) + { + // Info: 800 + if (level.intValue() <= Level.INFO.intValue()) + { + log.info(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void warning(String message) + { + // Warning: 900 + if (level.intValue() <= Level.WARNING.intValue()) + { + log.warning(message); + } + } + + /** + * Sends 'message' to the log if the logging level is high enough. + * + * @param message String containing message to be sent. + */ + public void severe(String message) + { + // Severe: 1000 + if (level.intValue() <= Level.SEVERE.intValue()) + { + log.severe(message); + } + } +} diff --git a/src/org/communitybridge/utility/StringUtilities.java b/src/org/communitybridge/utility/StringUtilities.java index bd4f9bf..a714653 100644 --- a/src/org/communitybridge/utility/StringUtilities.java +++ b/src/org/communitybridge/utility/StringUtilities.java @@ -1,221 +1,221 @@ -package org.communitybridge.utility; - -import java.util.List; - -public final class StringUtilities -{ - public final static int NOT_FOUND = -1; - - private StringUtilities() {} - - /** - * Returns: - * 1 -- if left is greater than right - * 0 -- if they are equal - * -1 -- if left is less than right - * @param leftVersion - * @param rightVersion - */ - public static int compareVersion(String leftVersion, String rightVersion) throws IllegalArgumentException - { - if (leftVersion == null) - { - leftVersion = ""; - } - - if (rightVersion == null) - { - rightVersion = ""; - } - - leftVersion = leftVersion.replace("-", ".").replaceAll("[^0-9\\.]", ""); - rightVersion = rightVersion.replace("-", ".").replaceAll("[^0-9\\.]", ""); - - if (leftVersion.isEmpty() && rightVersion.isEmpty()) - { - return 0; - } - else if (leftVersion.isEmpty()) - { - return -1; - } - else if (rightVersion.isEmpty()) - { - return 1; - } - - String[] leftParts = leftVersion.split("\\."); - String[] rightParts = rightVersion.split("\\."); - int leftLength = leftParts.length; - int rightLength = rightParts.length; - - // Which is shortest? - int shortest = leftLength < rightLength ? leftLength : rightLength; - - // Determine if they are equal up to the point they are the same length. - for (int i = 0; i < shortest; i++) - { - int leftPart = Integer.parseInt(leftParts[i]); - int rightPart = Integer.parseInt(rightParts[i]); - - if (leftPart > rightPart) - { - return 1; - } - else if (leftPart < rightPart) - { - return -1; - } - } - - if (shortest < leftParts.length) - { - for (int i = shortest; i < leftParts.length; i++) - { - if (Integer.parseInt(leftParts[i]) > 0) - { - return 1; - } - } - } - else if (shortest < rightParts.length) - { - for (int i = shortest; i < rightParts.length; i++) - { - if (Integer.parseInt(rightParts[i]) > 0) - { - return -1; - } - } - } - - // Same length, so equal. - return 0; - } - - /** - * Finds the first position, of any of the characters in searchCharacters, if none of the characters are found StringUtilities.NOT_FOUND (-1) is returned. - * - * @param stringToSearch string to be searched, e.g., the haystack. - * @param searchCharacters string containing the characters to search for, e.g., the needles. - * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string. - * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty. - */ - public static int find_first_of(String stringToSearch, String searchCharacters) throws IllegalArgumentException - { - return StringUtilities.find_first_of(stringToSearch, searchCharacters, 0); - } - /** - * Finds the first position after a specified starting position, of any of the characters in searchCharacters, if none of the characters are found StringUtilities.NOT_FOUND (-1) is returned. - * - * @param stringToSearch string to be searched, e.g., the haystack. - * @param searchCharacters string containing the characters to search for, e.g., the needles. - * @param startingPosition integer of where to begin the search in the string. - * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string. - * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty. - */ - public static int find_first_of(String stringToSearch, String searchCharacters, int startingPosition) throws IllegalArgumentException - { - if (stringToSearch == null) - { - throw new IllegalArgumentException("stringToSearch cannot be null."); - } - - if (searchCharacters == null) - { - throw new IllegalArgumentException("searchCharacters cannot be null."); - } - - if (searchCharacters.isEmpty()) - { - throw new IllegalArgumentException("At least one character required for search."); - } - - - for (int position = startingPosition; position < stringToSearch.length(); position++) - { - if (searchCharacters.indexOf(stringToSearch.charAt(position)) > -1) - { - return position; - } - } - - return NOT_FOUND; - } - - public static String joinStrings(List stringList, String conjunction) - { - StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; - - for (String string : stringList) - { - if (first) - { - first = false; - } - else - { - stringBuilder.append(conjunction); - } - stringBuilder.append(string); - } - - return stringBuilder.toString(); - } - - public static String timeElapsedToString(long time) - { - int count = 0; - - if (time == 0) - { - return "0 seconds"; - } - - String result = ""; - - if (time >= 86400) - { - long days = time / 86400; - time = time - days * 86400; - result = result + days + (days == 1 ? " day" : " days"); - count++; - } - - if (time >= 3600) - { - if (count >= 1) - { - result = result + ", "; - } - long hours = time / 3600; - time = time - hours * 3600; - result = result + hours + (hours == 1 ? " hour" : " hours"); - count++; - } - - if (time >= 60) - { - if (count >= 1) - { - result = result + ", "; - } - long minutes = time / 60; - time = time - minutes * 60; - result = result + minutes + (minutes == 1 ? " minute" : " minutes"); - count++; - } - - if (time > 0) - { - if (count >= 1) - { - result = result + ", "; - } - result = result + time + (time == 1 ? " second" : " seconds"); - } - - return result; - } -} +package org.communitybridge.utility; + +import java.util.List; + +public final class StringUtilities +{ + public final static int NOT_FOUND = -1; + + private StringUtilities() {} + + /** + * Returns: + * 1 -- if left is greater than right + * 0 -- if they are equal + * -1 -- if left is less than right + * @param leftVersion + * @param rightVersion + */ + public static int compareVersion(String leftVersion, String rightVersion) throws IllegalArgumentException + { + if (leftVersion == null) + { + leftVersion = ""; + } + + if (rightVersion == null) + { + rightVersion = ""; + } + + leftVersion = leftVersion.replace("-", ".").replaceAll("[^0-9\\.]", ""); + rightVersion = rightVersion.replace("-", ".").replaceAll("[^0-9\\.]", ""); + + if (leftVersion.isEmpty() && rightVersion.isEmpty()) + { + return 0; + } + else if (leftVersion.isEmpty()) + { + return -1; + } + else if (rightVersion.isEmpty()) + { + return 1; + } + + String[] leftParts = leftVersion.split("\\."); + String[] rightParts = rightVersion.split("\\."); + int leftLength = leftParts.length; + int rightLength = rightParts.length; + + // Which is shortest? + int shortest = leftLength < rightLength ? leftLength : rightLength; + + // Determine if they are equal up to the point they are the same length. + for (int i = 0; i < shortest; i++) + { + int leftPart = Integer.parseInt(leftParts[i]); + int rightPart = Integer.parseInt(rightParts[i]); + + if (leftPart > rightPart) + { + return 1; + } + else if (leftPart < rightPart) + { + return -1; + } + } + + if (shortest < leftParts.length) + { + for (int i = shortest; i < leftParts.length; i++) + { + if (Integer.parseInt(leftParts[i]) > 0) + { + return 1; + } + } + } + else if (shortest < rightParts.length) + { + for (int i = shortest; i < rightParts.length; i++) + { + if (Integer.parseInt(rightParts[i]) > 0) + { + return -1; + } + } + } + + // Same length, so equal. + return 0; + } + + /** + * Finds the first position, of any of the characters in searchCharacters, if none of the characters are found StringUtilities.NOT_FOUND (-1) is returned. + * + * @param stringToSearch string to be searched, e.g., the haystack. + * @param searchCharacters string containing the characters to search for, e.g., the needles. + * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string. + * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty. + */ + public static int find_first_of(String stringToSearch, String searchCharacters) throws IllegalArgumentException + { + return StringUtilities.find_first_of(stringToSearch, searchCharacters, 0); + } + /** + * Finds the first position after a specified starting position, of any of the characters in searchCharacters, if none of the characters are found StringUtilities.NOT_FOUND (-1) is returned. + * + * @param stringToSearch string to be searched, e.g., the haystack. + * @param searchCharacters string containing the characters to search for, e.g., the needles. + * @param startingPosition integer of where to begin the search in the string. + * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string. + * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty. + */ + public static int find_first_of(String stringToSearch, String searchCharacters, int startingPosition) throws IllegalArgumentException + { + if (stringToSearch == null) + { + throw new IllegalArgumentException("stringToSearch cannot be null."); + } + + if (searchCharacters == null) + { + throw new IllegalArgumentException("searchCharacters cannot be null."); + } + + if (searchCharacters.isEmpty()) + { + throw new IllegalArgumentException("At least one character required for search."); + } + + + for (int position = startingPosition; position < stringToSearch.length(); position++) + { + if (searchCharacters.indexOf(stringToSearch.charAt(position)) > -1) + { + return position; + } + } + + return NOT_FOUND; + } + + public static String joinStrings(List stringList, String conjunction) + { + StringBuilder stringBuilder = new StringBuilder(); + boolean first = true; + + for (String string : stringList) + { + if (first) + { + first = false; + } + else + { + stringBuilder.append(conjunction); + } + stringBuilder.append(string); + } + + return stringBuilder.toString(); + } + + public static String timeElapsedToString(long time) + { + int count = 0; + + if (time == 0) + { + return "0 seconds"; + } + + String result = ""; + + if (time >= 86400) + { + long days = time / 86400; + time = time - days * 86400; + result = result + days + (days == 1 ? " day" : " days"); + count++; + } + + if (time >= 3600) + { + if (count >= 1) + { + result = result + ", "; + } + long hours = time / 3600; + time = time - hours * 3600; + result = result + hours + (hours == 1 ? " hour" : " hours"); + count++; + } + + if (time >= 60) + { + if (count >= 1) + { + result = result + ", "; + } + long minutes = time / 60; + time = time - minutes * 60; + result = result + minutes + (minutes == 1 ? " minute" : " minutes"); + count++; + } + + if (time > 0) + { + if (count >= 1) + { + result = result + ", "; + } + result = result + time + (time == 1 ? " second" : " seconds"); + } + + return result; + } +} diff --git a/test/org/communitybridge/achievement/AchievementAvatarTest.java b/test/org/communitybridge/achievement/AchievementAvatarTest.java index c4effa0..0eee544 100644 --- a/test/org/communitybridge/achievement/AchievementAvatarTest.java +++ b/test/org/communitybridge/achievement/AchievementAvatarTest.java @@ -1,122 +1,122 @@ -package org.communitybridge.achievement; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang.RandomStringUtils; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.communitybridge.linker.UserPlayerLinker; -import org.communitybridge.main.BukkitWrapper; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.WebApplication; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import static org.mockito.Mockito.*; - -public class AchievementAvatarTest -{ - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private Player player = mock(Player.class); - private WebApplication webApplication = mock(WebApplication.class); - private UserPlayerLinker linker = mock(UserPlayerLinker.class); - private PlayerAchievementState state = new PlayerAchievementState("Player", null); - private String userID = RandomStringUtils.randomAlphabetic(2); - private PlayerInventory playerInventory = mock(PlayerInventory.class); - private PlayerInventory otherInventory = mock(PlayerInventory.class); - private Server server = mock(Server.class); - - private BukkitWrapper bukkit = mock(BukkitWrapper.class); - - private AchievementAvatar achievement = new AchievementAvatar(environment); - - @Before - public void beforeEach() { - achievement.bukkit = bukkit; - environment.setConfiguration(configuration); - environment.setUserPlayerLinker(linker); - configuration.avatarEnabled = true; - environment.setWebApplication(webApplication); - achievement.setLimit(1); - when(bukkit.getServer()).thenReturn(server); - when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); - when(player.getInventory()).thenReturn(playerInventory); - when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); - when(linker.getUserID(player)).thenReturn(userID); - when(webApplication.playerHasAvatar(userID)).thenReturn(true); - Map itemRewards = new EnumMap(Material.class); - itemRewards.put(Material.ACACIA_STAIRS, 10); - itemRewards.put(Material.ACTIVATOR_RAIL, 10); - achievement.setItemRewards(itemRewards); - } - - @Test - public void playerQualifiesReturnsTrue() - { - assertTrue(achievement.playerQualifies(player, state)); - } - - @Test - public void playerQualifiesWithAvatarDisabledReturnsFalse() - { - configuration.avatarEnabled = false; - assertFalse(achievement.playerQualifies(player, state)); - } - - @Test - public void playerQualifiesWithNoUserIDReturnsFalse() - { - when(linker.getUserID(player)).thenReturn(""); - assertFalse(achievement.playerQualifies(player, state)); - } - - @Test - public void playerQualifiesWithNoAvatarReturnsFalse() - { - when(webApplication.playerHasAvatar(userID)).thenReturn(false); - assertFalse(achievement.playerQualifies(player, state)); - } - - @Test - public void playerQualifiesOverLimitReturnsFalse() - { - achievement.setLimit(-1); - assertFalse(achievement.playerQualifies(player, state)); - } - - @Test - public void playerQualifiesWhenTooManyReturnsFalse() - { - HashMap rejected = new HashMap(); - ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64); - rejected.put(0, stack); - - when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); - when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected); - - assertFalse(achievement.playerQualifies(player, state)); - } - - @Test - public void rewardPlayerRewardsPlayer() - { - achievement.rewardPlayer(player, state); - int rewardCount = achievement.getItemRewards().size(); - verify(playerInventory, times(rewardCount)).addItem(any(ItemStack.class)); - } - - @Test - public void rewardPlayerIncrementsState() - { - int expected = state.getAvatarAchievements() + 1; - achievement.rewardPlayer(player, state); - assertEquals(expected, state.getAvatarAchievements()); - } +package org.communitybridge.achievement; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang.RandomStringUtils; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.communitybridge.linker.UserPlayerLinker; +import org.communitybridge.main.BukkitWrapper; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.WebApplication; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import static org.mockito.Mockito.*; + +public class AchievementAvatarTest +{ + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private Player player = mock(Player.class); + private WebApplication webApplication = mock(WebApplication.class); + private UserPlayerLinker linker = mock(UserPlayerLinker.class); + private PlayerAchievementState state = new PlayerAchievementState("Player", null); + private String userID = RandomStringUtils.randomAlphabetic(2); + private PlayerInventory playerInventory = mock(PlayerInventory.class); + private PlayerInventory otherInventory = mock(PlayerInventory.class); + private Server server = mock(Server.class); + + private BukkitWrapper bukkit = mock(BukkitWrapper.class); + + private AchievementAvatar achievement = new AchievementAvatar(environment); + + @Before + public void beforeEach() { + achievement.bukkit = bukkit; + environment.setConfiguration(configuration); + environment.setUserPlayerLinker(linker); + configuration.avatarEnabled = true; + environment.setWebApplication(webApplication); + achievement.setLimit(1); + when(bukkit.getServer()).thenReturn(server); + when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); + when(player.getInventory()).thenReturn(playerInventory); + when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); + when(linker.getUserID(player)).thenReturn(userID); + when(webApplication.playerHasAvatar(userID)).thenReturn(true); + Map itemRewards = new EnumMap(Material.class); + itemRewards.put(Material.ACACIA_STAIRS, 10); + itemRewards.put(Material.ACTIVATOR_RAIL, 10); + achievement.setItemRewards(itemRewards); + } + + @Test + public void playerQualifiesReturnsTrue() + { + assertTrue(achievement.playerQualifies(player, state)); + } + + @Test + public void playerQualifiesWithAvatarDisabledReturnsFalse() + { + configuration.avatarEnabled = false; + assertFalse(achievement.playerQualifies(player, state)); + } + + @Test + public void playerQualifiesWithNoUserIDReturnsFalse() + { + when(linker.getUserID(player)).thenReturn(""); + assertFalse(achievement.playerQualifies(player, state)); + } + + @Test + public void playerQualifiesWithNoAvatarReturnsFalse() + { + when(webApplication.playerHasAvatar(userID)).thenReturn(false); + assertFalse(achievement.playerQualifies(player, state)); + } + + @Test + public void playerQualifiesOverLimitReturnsFalse() + { + achievement.setLimit(-1); + assertFalse(achievement.playerQualifies(player, state)); + } + + @Test + public void playerQualifiesWhenTooManyReturnsFalse() + { + HashMap rejected = new HashMap(); + ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64); + rejected.put(0, stack); + + when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); + when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected); + + assertFalse(achievement.playerQualifies(player, state)); + } + + @Test + public void rewardPlayerRewardsPlayer() + { + achievement.rewardPlayer(player, state); + int rewardCount = achievement.getItemRewards().size(); + verify(playerInventory, times(rewardCount)).addItem(any(ItemStack.class)); + } + + @Test + public void rewardPlayerIncrementsState() + { + int expected = state.getAvatarAchievements() + 1; + achievement.rewardPlayer(player, state); + assertEquals(expected, state.getAvatarAchievements()); + } } \ No newline at end of file diff --git a/test/org/communitybridge/achievement/AchievementTest.java b/test/org/communitybridge/achievement/AchievementTest.java index 2b69879..9756a55 100644 --- a/test/org/communitybridge/achievement/AchievementTest.java +++ b/test/org/communitybridge/achievement/AchievementTest.java @@ -1,207 +1,207 @@ -package org.communitybridge.achievement; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import net.milkbowl.vault.economy.Economy; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.communitybridge.main.BukkitWrapper; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.junit.Test; -import org.junit.Before; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -public class AchievementTest -{ - private Player player = mock(Player.class); - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private PlayerInventory playerInventory = mock(PlayerInventory.class); - private PlayerInventory otherInventory = mock(PlayerInventory.class); - private BukkitWrapper bukkit = mock(BukkitWrapper.class); - private Server server = mock(Server.class); - - Achievement achievement = new TestableAchievement(environment, bukkit); - - @Before - public void beforeEach() - { - environment.setConfiguration(configuration); - } - - @Test - public void rewardPlayerPerformsCashReward() - { - Double amount = RandomUtils.nextDouble(10.0, 1000.0); - configuration.economyEnabled = true; - Economy economy = mock(Economy.class); - environment.setEconomy(economy); - when(economy.depositPlayer(player, amount)).thenReturn(null); - achievement.setCashReward(amount); - achievement.rewardPlayer(player, null); - verify(economy).depositPlayer(player, amount); - } - - @Test - public void rewardPlayerNoEconomyNoCashAward() - { - Double amount = RandomUtils.nextDouble(10.0, 1000.0); - configuration.economyEnabled = false; - Economy economy = mock(Economy.class); - environment.setEconomy(economy); - when(economy.depositPlayer(player, amount)).thenReturn(null); - achievement.setCashReward(amount); - achievement.rewardPlayer(player, null); - verifyZeroInteractions(economy); - } - - @Test - public void rewardPlayerOneItem() - { - configuration.economyEnabled = false; - Map itemRewards = new EnumMap(Material.class); - itemRewards.put(Material.ACACIA_STAIRS, 10); - achievement.setItemRewards(itemRewards); - when(player.getInventory()).thenReturn(playerInventory); - when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null); - achievement.rewardPlayer(player, null); - verify(playerInventory).addItem(any(ItemStack.class)); - verify(player).updateInventory(); - } - - @Test - public void rewardPlayerTwoItems() - { - configuration.economyEnabled = false; - setupRewards(); - when(player.getInventory()).thenReturn(playerInventory); - when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null); - achievement.rewardPlayer(player, null); - verify(playerInventory, times(2)).addItem(any(ItemStack.class)); - verify(player, times(1)).updateInventory(); - } - - @Test - public void rewardPlayerNoItemDontUpdateInventory() - { - configuration.economyEnabled = false; - achievement.rewardPlayer(player, null); - verify(player, never()).updateInventory(); - } - - @Test - public void canRewardAllItemRewardsReturnTrue() - { - setupRewards(); - - when(bukkit.getServer()).thenReturn(server); - when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); - when(player.getInventory()).thenReturn(playerInventory); - when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); - assertTrue(achievement.canRewardAllItemRewards(player)); - } - - @Test - public void canRewardAllItemRewardsReturnFalseWhenTooMany() - { - setupRewards(); - - HashMap rejected = new HashMap(); - ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64); - rejected.put(0, stack); - - when(bukkit.getServer()).thenReturn(server); - when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); - when(player.getInventory()).thenReturn(playerInventory); - when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); - when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected); - - assertFalse(achievement.canRewardAllItemRewards(player)); - } - - @Test - public void loadReadsLimit() - { - String path = RandomStringUtils.randomAlphabetic(7); - YamlConfiguration yamlConfiguration = new YamlConfiguration(); - int limit = RandomUtils.nextInt(1,10); - yamlConfiguration.set(path + ".Limit", limit); - achievement.load(yamlConfiguration, path); - assertEquals(limit, achievement.getLimit()); - } - - @Test - public void loadReadsCashReward() - { - String path = RandomStringUtils.randomAlphabetic(7); - YamlConfiguration yamlConfiguration = new YamlConfiguration(); - double cash = RandomUtils.nextDouble(1,10); - yamlConfiguration.set(path + ".Money", cash); - achievement.load(yamlConfiguration, path); - assertEquals(cash, achievement.getCashReward(), 0); - } - - @Test - public void loadReadsOneItem() - { - String path = RandomStringUtils.randomAlphabetic(7); - YamlConfiguration yamlConfiguration = new YamlConfiguration(); - ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items"); - Integer expected = RandomUtils.nextInt(1, 10); - itemsSection.set("EMERALD", expected); - achievement.load(yamlConfiguration, path); - Integer actual = achievement.getItemRewards().get(Material.EMERALD); - assertEquals(expected, actual); - } - - @Test - public void loadReadsMultipleItems() - { - String path = RandomStringUtils.randomAlphabetic(7); - YamlConfiguration yamlConfiguration = new YamlConfiguration(); - ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items"); - Integer expectedEmerald = RandomUtils.nextInt(2, 10); - Integer expectedCoal = RandomUtils.nextInt(2, 25); - itemsSection.set("EMERALD", expectedEmerald); - itemsSection.set("COAL", expectedCoal); - achievement.load(yamlConfiguration, path); - Integer actual = achievement.getItemRewards().get(Material.EMERALD); - assertEquals(expectedEmerald, actual); - actual = achievement.getItemRewards().get(Material.COAL); - assertEquals(expectedCoal, actual); - } - - private void setupRewards() - { - Map itemRewards = new EnumMap(Material.class); - itemRewards.put(Material.ACACIA_STAIRS, 10); - itemRewards.put(Material.ACTIVATOR_RAIL, 10); - achievement.setItemRewards(itemRewards); - } - - public class TestableAchievement extends Achievement - { - public TestableAchievement(Environment environment, BukkitWrapper bukkit) - { - super(environment); - this.bukkit = bukkit; - } - - @Override - public boolean playerQualifies(Player player, PlayerAchievementState state) - { - return false; - } - } +package org.communitybridge.achievement; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import net.milkbowl.vault.economy.Economy; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.communitybridge.main.BukkitWrapper; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class AchievementTest +{ + private Player player = mock(Player.class); + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private PlayerInventory playerInventory = mock(PlayerInventory.class); + private PlayerInventory otherInventory = mock(PlayerInventory.class); + private BukkitWrapper bukkit = mock(BukkitWrapper.class); + private Server server = mock(Server.class); + + Achievement achievement = new TestableAchievement(environment, bukkit); + + @Before + public void beforeEach() + { + environment.setConfiguration(configuration); + } + + @Test + public void rewardPlayerPerformsCashReward() + { + Double amount = RandomUtils.nextDouble(10.0, 1000.0); + configuration.economyEnabled = true; + Economy economy = mock(Economy.class); + environment.setEconomy(economy); + when(economy.depositPlayer(player, amount)).thenReturn(null); + achievement.setCashReward(amount); + achievement.rewardPlayer(player, null); + verify(economy).depositPlayer(player, amount); + } + + @Test + public void rewardPlayerNoEconomyNoCashAward() + { + Double amount = RandomUtils.nextDouble(10.0, 1000.0); + configuration.economyEnabled = false; + Economy economy = mock(Economy.class); + environment.setEconomy(economy); + when(economy.depositPlayer(player, amount)).thenReturn(null); + achievement.setCashReward(amount); + achievement.rewardPlayer(player, null); + verifyZeroInteractions(economy); + } + + @Test + public void rewardPlayerOneItem() + { + configuration.economyEnabled = false; + Map itemRewards = new EnumMap(Material.class); + itemRewards.put(Material.ACACIA_STAIRS, 10); + achievement.setItemRewards(itemRewards); + when(player.getInventory()).thenReturn(playerInventory); + when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null); + achievement.rewardPlayer(player, null); + verify(playerInventory).addItem(any(ItemStack.class)); + verify(player).updateInventory(); + } + + @Test + public void rewardPlayerTwoItems() + { + configuration.economyEnabled = false; + setupRewards(); + when(player.getInventory()).thenReturn(playerInventory); + when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null); + achievement.rewardPlayer(player, null); + verify(playerInventory, times(2)).addItem(any(ItemStack.class)); + verify(player, times(1)).updateInventory(); + } + + @Test + public void rewardPlayerNoItemDontUpdateInventory() + { + configuration.economyEnabled = false; + achievement.rewardPlayer(player, null); + verify(player, never()).updateInventory(); + } + + @Test + public void canRewardAllItemRewardsReturnTrue() + { + setupRewards(); + + when(bukkit.getServer()).thenReturn(server); + when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); + when(player.getInventory()).thenReturn(playerInventory); + when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); + assertTrue(achievement.canRewardAllItemRewards(player)); + } + + @Test + public void canRewardAllItemRewardsReturnFalseWhenTooMany() + { + setupRewards(); + + HashMap rejected = new HashMap(); + ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64); + rejected.put(0, stack); + + when(bukkit.getServer()).thenReturn(server); + when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory); + when(player.getInventory()).thenReturn(playerInventory); + when(playerInventory.getType()).thenReturn(InventoryType.PLAYER); + when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected); + + assertFalse(achievement.canRewardAllItemRewards(player)); + } + + @Test + public void loadReadsLimit() + { + String path = RandomStringUtils.randomAlphabetic(7); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + int limit = RandomUtils.nextInt(1,10); + yamlConfiguration.set(path + ".Limit", limit); + achievement.load(yamlConfiguration, path); + assertEquals(limit, achievement.getLimit()); + } + + @Test + public void loadReadsCashReward() + { + String path = RandomStringUtils.randomAlphabetic(7); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + double cash = RandomUtils.nextDouble(1,10); + yamlConfiguration.set(path + ".Money", cash); + achievement.load(yamlConfiguration, path); + assertEquals(cash, achievement.getCashReward(), 0); + } + + @Test + public void loadReadsOneItem() + { + String path = RandomStringUtils.randomAlphabetic(7); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items"); + Integer expected = RandomUtils.nextInt(1, 10); + itemsSection.set("EMERALD", expected); + achievement.load(yamlConfiguration, path); + Integer actual = achievement.getItemRewards().get(Material.EMERALD); + assertEquals(expected, actual); + } + + @Test + public void loadReadsMultipleItems() + { + String path = RandomStringUtils.randomAlphabetic(7); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items"); + Integer expectedEmerald = RandomUtils.nextInt(2, 10); + Integer expectedCoal = RandomUtils.nextInt(2, 25); + itemsSection.set("EMERALD", expectedEmerald); + itemsSection.set("COAL", expectedCoal); + achievement.load(yamlConfiguration, path); + Integer actual = achievement.getItemRewards().get(Material.EMERALD); + assertEquals(expectedEmerald, actual); + actual = achievement.getItemRewards().get(Material.COAL); + assertEquals(expectedCoal, actual); + } + + private void setupRewards() + { + Map itemRewards = new EnumMap(Material.class); + itemRewards.put(Material.ACACIA_STAIRS, 10); + itemRewards.put(Material.ACTIVATOR_RAIL, 10); + achievement.setItemRewards(itemRewards); + } + + public class TestableAchievement extends Achievement + { + public TestableAchievement(Environment environment, BukkitWrapper bukkit) + { + super(environment); + this.bukkit = bukkit; + } + + @Override + public boolean playerQualifies(Player player, PlayerAchievementState state) + { + return false; + } + } } \ No newline at end of file diff --git a/test/org/communitybridge/linker/UserIDDaoTest.java b/test/org/communitybridge/linker/UserIDDaoTest.java index 9005456..3bec94a 100644 --- a/test/org/communitybridge/linker/UserIDDaoTest.java +++ b/test/org/communitybridge/linker/UserIDDaoTest.java @@ -1,239 +1,239 @@ -package org.communitybridge.linker; - -import java.net.MalformedURLException; -import java.sql.ResultSet; -import java.sql.SQLException; -import org.apache.commons.lang.RandomStringUtils; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.SQL; -import org.communitybridge.utility.Log; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import static org.mockito.Mockito.*; - -public class UserIDDaoTest -{ - private static final String EXCEPTION_MESSAGE = "test message"; - private static final String IDENTIFIER = RandomStringUtils.randomAlphabetic(7); - private static final String USER_ID = RandomStringUtils.randomNumeric(2); - private static final String UUID = RandomStringUtils.randomAlphabetic(36); - - private Environment environment = new Environment(); - private UserIDDao userIDDao; - private Configuration configuration = mock(Configuration.class); - private Log log = mock(Log.class); - private SQL sql = mock(SQL.class); - private ResultSet result = mock(ResultSet.class); - - @Before - public void setup() - { - environment.setConfiguration(configuration); - environment.setLog(log); - environment.setSql(sql); - userIDDao = new UserIDDao(environment); - configuration.linkingTableName = RandomStringUtils.randomAlphabetic(6); - configuration.linkingUserIDColumn = RandomStringUtils.randomAlphabetic(9); - configuration.linkingIdentifierColumn = RandomStringUtils.randomAlphabetic(4); - configuration.linkingKeyColumn = RandomStringUtils.randomAlphabetic(7); - configuration.linkingValueColumn = RandomStringUtils.randomAlphabetic(5); - configuration.linkingKeyName = RandomStringUtils.randomAlphabetic(8); - } - - @Test - public void getUserIDNeverReturnsNull() - { - assertNotNull(userIDDao.getUserID(null)); - } - - @Test - public void getUserIDUsesCorrectKeyedQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = true; - - String query = "SELECT `" + configuration.linkingTableName + "`.`" + configuration.linkingUserIDColumn + "` " - + "FROM `" + configuration.linkingTableName + "` " - + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' " - + "AND `" + configuration.linkingValueColumn + "` = '" + IDENTIFIER + "' " - + "ORDER BY `" + configuration.linkingUserIDColumn + "` DESC"; - userIDDao.getUserID(IDENTIFIER); - verify(sql).sqlQuery(query); - } - - @Test - public void getUserIDUsesCorrectKeylessQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = false; - - String query = "SELECT `" + configuration.linkingTableName + "`.`" + configuration.linkingUserIDColumn + "` " - + "FROM `" + configuration.linkingTableName + "` " - + "WHERE LOWER(`" + configuration.linkingIdentifierColumn + "`) = LOWER('" + IDENTIFIER + "') " - + "ORDER BY `" + configuration.linkingUserIDColumn + "` DESC"; - userIDDao.getUserID(IDENTIFIER); - verify(sql).sqlQuery(query); - } - - @Test - public void getUserIDWithNullResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(sql.sqlQuery(anyString())).thenReturn(null); - String userID = userIDDao.getUserID(IDENTIFIER); - assertEquals("", userID); - } - - @Test - public void getUserIDWithEmptyResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.next()).thenReturn(false); - String userID = userIDDao.getUserID(IDENTIFIER); - assertEquals("", userID); - } - - @Test - public void getUserIDReturnsUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.getString(configuration.linkingUserIDColumn)).thenReturn(USER_ID); - when(result.next()).thenReturn(true); - assertEquals(USER_ID, userIDDao.getUserID(IDENTIFIER)); - } - - @Test - public void getUserIDHandlesSQLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - SQLException exception = new SQLException(EXCEPTION_MESSAGE); - testGetUserIDFromDatabaseException(exception); - } - - @Test - public void getUserIDHandlesMalformedURLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - MalformedURLException exception = new MalformedURLException(EXCEPTION_MESSAGE); - testGetUserIDFromDatabaseException(exception); - } - - @Test - public void getUserIDHandlesInstantiationException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - InstantiationException exception = new InstantiationException(EXCEPTION_MESSAGE); - testGetUserIDFromDatabaseException(exception); - } - - @Test - public void getUserIDHandlesIllegalAccessException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - IllegalAccessException exception = new IllegalAccessException(EXCEPTION_MESSAGE); - testGetUserIDFromDatabaseException(exception); - } - - private void testGetUserIDFromDatabaseException(Exception exception) throws SQLException, InstantiationException, IllegalAccessException, MalformedURLException - { - when(sql.sqlQuery(anyString())).thenThrow(exception); - assertEquals("", userIDDao.getUserID(IDENTIFIER)); - verify(log).severe(UserIDDao.EXCEPTION_MESSAGE_GETUSERID + exception.getMessage()); - } - - @Test - public void getUUIDNeverReturnsNull() - { - assertNotNull(userIDDao.getUUID(null)); - } - - @Test - public void getUUIDUsesCorrectKeyedQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = true; - - String query = "SELECT `" + configuration.linkingValueColumn + "` " - + "FROM `" + configuration.linkingTableName + "` " - + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' " - + "AND `" + configuration.linkingUserIDColumn + "` = '" + USER_ID + "'"; - userIDDao.getUUID(USER_ID); - verify(sql).sqlQuery(query); - } - - @Test - public void getUUIDUsesCorrectKeylessQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = false; - - String query = "SELECT `" + configuration.linkingIdentifierColumn + "` " - + "FROM `" + configuration.linkingTableName + "` " - + "WHERE `" + configuration.linkingUserIDColumn + "` = '" + USER_ID + "'"; - userIDDao.getUUID(USER_ID); - verify(sql).sqlQuery(query); - } - - @Test - public void getUUIDWithNullResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(sql.sqlQuery(anyString())).thenReturn(null); - assertEquals("", userIDDao.getUUID(USER_ID)); - } - - @Test - public void getUUIDWithEmptyResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.next()).thenReturn(false); - assertEquals("", userIDDao.getUUID(USER_ID)); - } - - @Test - public void getUUIDKeylessReturnsUUID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = false; - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.getString(configuration.linkingIdentifierColumn)).thenReturn(UUID); - when(result.next()).thenReturn(true); - assertEquals(UUID, userIDDao.getUUID(USER_ID)); - } - - @Test - public void getUUIDKeyedReturnsUUID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.linkingUsesKey = true; - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.getString(configuration.linkingValueColumn)).thenReturn(UUID); - when(result.next()).thenReturn(true); - assertEquals(UUID, userIDDao.getUUID(USER_ID)); - } - - @Test - public void getUUIDHandlesSQLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - SQLException exception = new SQLException(EXCEPTION_MESSAGE); - testGetUUIDFromDatabaseException(exception); - } - - @Test - public void getUUIDHandlesMalformedURLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - MalformedURLException exception = new MalformedURLException(EXCEPTION_MESSAGE); - testGetUUIDFromDatabaseException(exception); - } - - @Test - public void getUUIDHandlesInstantiationException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - InstantiationException exception = new InstantiationException(EXCEPTION_MESSAGE); - testGetUUIDFromDatabaseException(exception); - } - - @Test - public void getUUIDHandlesIllegalAccessException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - IllegalAccessException exception = new IllegalAccessException(EXCEPTION_MESSAGE); - testGetUUIDFromDatabaseException(exception); - } - - private void testGetUUIDFromDatabaseException(Exception exception) throws SQLException, InstantiationException, IllegalAccessException, MalformedURLException - { - when(sql.sqlQuery(anyString())).thenThrow(exception); - assertEquals("", userIDDao.getUUID(IDENTIFIER)); - verify(log).severe(UserIDDao.EXCEPTION_MESSAGE_GETUUID + exception.getMessage()); - } +package org.communitybridge.linker; + +import java.net.MalformedURLException; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.apache.commons.lang.RandomStringUtils; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.SQL; +import org.communitybridge.utility.Log; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import static org.mockito.Mockito.*; + +public class UserIDDaoTest +{ + private static final String EXCEPTION_MESSAGE = "test message"; + private static final String IDENTIFIER = RandomStringUtils.randomAlphabetic(7); + private static final String USER_ID = RandomStringUtils.randomNumeric(2); + private static final String UUID = RandomStringUtils.randomAlphabetic(36); + + private Environment environment = new Environment(); + private UserIDDao userIDDao; + private Configuration configuration = mock(Configuration.class); + private Log log = mock(Log.class); + private SQL sql = mock(SQL.class); + private ResultSet result = mock(ResultSet.class); + + @Before + public void setup() + { + environment.setConfiguration(configuration); + environment.setLog(log); + environment.setSql(sql); + userIDDao = new UserIDDao(environment); + configuration.linkingTableName = RandomStringUtils.randomAlphabetic(6); + configuration.linkingUserIDColumn = RandomStringUtils.randomAlphabetic(9); + configuration.linkingIdentifierColumn = RandomStringUtils.randomAlphabetic(4); + configuration.linkingKeyColumn = RandomStringUtils.randomAlphabetic(7); + configuration.linkingValueColumn = RandomStringUtils.randomAlphabetic(5); + configuration.linkingKeyName = RandomStringUtils.randomAlphabetic(8); + } + + @Test + public void getUserIDNeverReturnsNull() + { + assertNotNull(userIDDao.getUserID(null)); + } + + @Test + public void getUserIDUsesCorrectKeyedQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = true; + + String query = "SELECT `" + configuration.linkingTableName + "`.`" + configuration.linkingUserIDColumn + "` " + + "FROM `" + configuration.linkingTableName + "` " + + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' " + + "AND `" + configuration.linkingValueColumn + "` = '" + IDENTIFIER + "' " + + "ORDER BY `" + configuration.linkingUserIDColumn + "` DESC"; + userIDDao.getUserID(IDENTIFIER); + verify(sql).sqlQuery(query); + } + + @Test + public void getUserIDUsesCorrectKeylessQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = false; + + String query = "SELECT `" + configuration.linkingTableName + "`.`" + configuration.linkingUserIDColumn + "` " + + "FROM `" + configuration.linkingTableName + "` " + + "WHERE LOWER(`" + configuration.linkingIdentifierColumn + "`) = LOWER('" + IDENTIFIER + "') " + + "ORDER BY `" + configuration.linkingUserIDColumn + "` DESC"; + userIDDao.getUserID(IDENTIFIER); + verify(sql).sqlQuery(query); + } + + @Test + public void getUserIDWithNullResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(sql.sqlQuery(anyString())).thenReturn(null); + String userID = userIDDao.getUserID(IDENTIFIER); + assertEquals("", userID); + } + + @Test + public void getUserIDWithEmptyResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.next()).thenReturn(false); + String userID = userIDDao.getUserID(IDENTIFIER); + assertEquals("", userID); + } + + @Test + public void getUserIDReturnsUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.getString(configuration.linkingUserIDColumn)).thenReturn(USER_ID); + when(result.next()).thenReturn(true); + assertEquals(USER_ID, userIDDao.getUserID(IDENTIFIER)); + } + + @Test + public void getUserIDHandlesSQLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + SQLException exception = new SQLException(EXCEPTION_MESSAGE); + testGetUserIDFromDatabaseException(exception); + } + + @Test + public void getUserIDHandlesMalformedURLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + MalformedURLException exception = new MalformedURLException(EXCEPTION_MESSAGE); + testGetUserIDFromDatabaseException(exception); + } + + @Test + public void getUserIDHandlesInstantiationException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + InstantiationException exception = new InstantiationException(EXCEPTION_MESSAGE); + testGetUserIDFromDatabaseException(exception); + } + + @Test + public void getUserIDHandlesIllegalAccessException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + IllegalAccessException exception = new IllegalAccessException(EXCEPTION_MESSAGE); + testGetUserIDFromDatabaseException(exception); + } + + private void testGetUserIDFromDatabaseException(Exception exception) throws SQLException, InstantiationException, IllegalAccessException, MalformedURLException + { + when(sql.sqlQuery(anyString())).thenThrow(exception); + assertEquals("", userIDDao.getUserID(IDENTIFIER)); + verify(log).severe(UserIDDao.EXCEPTION_MESSAGE_GETUSERID + exception.getMessage()); + } + + @Test + public void getUUIDNeverReturnsNull() + { + assertNotNull(userIDDao.getUUID(null)); + } + + @Test + public void getUUIDUsesCorrectKeyedQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = true; + + String query = "SELECT `" + configuration.linkingValueColumn + "` " + + "FROM `" + configuration.linkingTableName + "` " + + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' " + + "AND `" + configuration.linkingUserIDColumn + "` = '" + USER_ID + "'"; + userIDDao.getUUID(USER_ID); + verify(sql).sqlQuery(query); + } + + @Test + public void getUUIDUsesCorrectKeylessQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = false; + + String query = "SELECT `" + configuration.linkingIdentifierColumn + "` " + + "FROM `" + configuration.linkingTableName + "` " + + "WHERE `" + configuration.linkingUserIDColumn + "` = '" + USER_ID + "'"; + userIDDao.getUUID(USER_ID); + verify(sql).sqlQuery(query); + } + + @Test + public void getUUIDWithNullResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(sql.sqlQuery(anyString())).thenReturn(null); + assertEquals("", userIDDao.getUUID(USER_ID)); + } + + @Test + public void getUUIDWithEmptyResultReturnsEmptyString() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.next()).thenReturn(false); + assertEquals("", userIDDao.getUUID(USER_ID)); + } + + @Test + public void getUUIDKeylessReturnsUUID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = false; + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.getString(configuration.linkingIdentifierColumn)).thenReturn(UUID); + when(result.next()).thenReturn(true); + assertEquals(UUID, userIDDao.getUUID(USER_ID)); + } + + @Test + public void getUUIDKeyedReturnsUUID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.linkingUsesKey = true; + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.getString(configuration.linkingValueColumn)).thenReturn(UUID); + when(result.next()).thenReturn(true); + assertEquals(UUID, userIDDao.getUUID(USER_ID)); + } + + @Test + public void getUUIDHandlesSQLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + SQLException exception = new SQLException(EXCEPTION_MESSAGE); + testGetUUIDFromDatabaseException(exception); + } + + @Test + public void getUUIDHandlesMalformedURLException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + MalformedURLException exception = new MalformedURLException(EXCEPTION_MESSAGE); + testGetUUIDFromDatabaseException(exception); + } + + @Test + public void getUUIDHandlesInstantiationException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + InstantiationException exception = new InstantiationException(EXCEPTION_MESSAGE); + testGetUUIDFromDatabaseException(exception); + } + + @Test + public void getUUIDHandlesIllegalAccessException() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + IllegalAccessException exception = new IllegalAccessException(EXCEPTION_MESSAGE); + testGetUUIDFromDatabaseException(exception); + } + + private void testGetUUIDFromDatabaseException(Exception exception) throws SQLException, InstantiationException, IllegalAccessException, MalformedURLException + { + when(sql.sqlQuery(anyString())).thenThrow(exception); + assertEquals("", userIDDao.getUUID(IDENTIFIER)); + verify(log).severe(UserIDDao.EXCEPTION_MESSAGE_GETUUID + exception.getMessage()); + } } \ No newline at end of file diff --git a/test/org/communitybridge/linker/UserPlayerLinkerTest.java b/test/org/communitybridge/linker/UserPlayerLinkerTest.java index 4c07892..b35f70d 100644 --- a/test/org/communitybridge/linker/UserPlayerLinkerTest.java +++ b/test/org/communitybridge/linker/UserPlayerLinkerTest.java @@ -1,283 +1,283 @@ -package org.communitybridge.linker; - -import org.communitybridge.main.BukkitWrapper; -import java.util.UUID; -import org.apache.commons.lang.RandomStringUtils; -import org.bukkit.entity.Player; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import org.mockito.runners.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class UserPlayerLinkerTest -{ - private static final String NAME_USER_ID = RandomStringUtils.randomNumeric(2); - private static final String PLAYER_NAME = RandomStringUtils.randomAlphabetic(8); - private static final String UUID_USER_ID = RandomStringUtils.randomNumeric(2); - - private Player player = mock(Player.class); - private UUID uuid = new UUID(System.currentTimeMillis(), System.currentTimeMillis()); - private UserIDDao userIDDao = mock(UserIDDao.class); - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private BukkitWrapper bukkit = mock(BukkitWrapper.class); - - @InjectMocks - UserPlayerLinker userPlayerLinker = new UserPlayerLinker(environment, 1); - - @Before - public void setup() - { - environment.setConfiguration(configuration); - } - - @Test - public void getUserIDByUUIDNeverReturnsNull() - { - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - assertNotNull(userPlayerLinker.getUserID(uuid.toString())); - } - - @Test - public void getUserIDByUUIDWithUUIDReturnsUserID() - { - configuration.linkingMethod = "both"; - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - assertEquals(UUID_USER_ID, userPlayerLinker.getUserID(uuid.toString())); - } - - @Test - public void getUserIDByUUIDWithoutUUIDReturnsBlank() - { - configuration.linkingMethod = "uuid"; - when(userIDDao.getUserID(uuid.toString())).thenReturn(""); - assertEquals("", userPlayerLinker.getUserID(uuid.toString())); - } - - @Test - public void getUserIDByPlayerNeverReturnsNull() - { - configuration.linkingMethod = "both"; - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(anyString())).thenReturn(NAME_USER_ID); - assertNotNull(userPlayerLinker.getUserID(player)); - } - - @Test - public void getUserIDbyPlayerWithoutUUIDWithPlayernameReturnsPlayernameUserID() - { - configuration.linkingMethod = "both"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(uuid.toString())).thenReturn(""); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - assertEquals(NAME_USER_ID, userPlayerLinker.getUserID(player)); - } - - @Test - public void getUserIDByPlayerWithUUIDandWithPlayernameReturnsUUIDUserID() - { - configuration.linkingMethod = "both"; - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - assertEquals(UUID_USER_ID, userPlayerLinker.getUserID(player)); - } - - @Test - public void getUserIDWithUUIDandWithPlayernameUUIDOffReturnsPlayernameUserID() - { - configuration.linkingMethod = "name"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - assertEquals(NAME_USER_ID, userPlayerLinker.getUserID(player)); - } - - @Test - public void getUserIDWithoutUUIDandWithPlayernameUUIDOnReturnsBlank() - { - configuration.linkingMethod = "uuid"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(""); - assertEquals("", userPlayerLinker.getUserID(player)); - } - - @Test - public void getUserIDAddsUUIDEntryToCache() - { - configuration.linkingMethod = "uuid"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - assertEquals(UUID_USER_ID, userPlayerLinker.getUserIDCache().get(uuid.toString())); - } - - @Test - public void getUserIDAddsNameEntryToCache() - { - configuration.linkingMethod = "name"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - assertEquals(NAME_USER_ID, userPlayerLinker.getUserIDCache().get(PLAYER_NAME)); - } - - @Test - public void removeUserIDFromCacheRemovesUUIDEntry() - { - configuration.linkingMethod = "uuid"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - userPlayerLinker.removeUserIDFromCache(uuid.toString(), PLAYER_NAME); - assertNull(userPlayerLinker.getUserIDCache().get(uuid.toString())); - } - - @Test - public void removeUserIDFromCacheRemovesNameEntry() - { - configuration.linkingMethod = "name"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - userPlayerLinker.removeUserIDFromCache(uuid.toString(), PLAYER_NAME); - assertNull(userPlayerLinker.getUserIDCache().get(PLAYER_NAME)); - } - - @Test - public void secondLookupOnTinyCacheForcesFlush() - { - String someOtherName = RandomStringUtils.randomNumeric(6); - String someOtherID = RandomStringUtils.randomNumeric(2); - configuration.linkingMethod = "name"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME, someOtherName); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(someOtherName)).thenReturn(someOtherID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - userPlayerLinker.getUserID(player); - assertEquals(1, userPlayerLinker.getUserIDCache().size()); - assertEquals(someOtherID, userPlayerLinker.getUserIDCache().get(someOtherName)); - assertFalse(userPlayerLinker.getUserIDCache().containsKey(PLAYER_NAME)); - } - - @Test - public void getUUIDNeverReturnsNull() - { - configuration.linkingMethod = "both"; - when(userIDDao.getUUID(anyString())).thenReturn(uuid.toString()); - assertNotNull(userPlayerLinker.getUUID("")); - } - - @Test - public void getUUIDSuccessfullyRetrievesCachedEntry() - { - configuration.linkingMethod = "uuid"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - userPlayerLinker.getUserID(player); - assertEquals(uuid.toString(), userPlayerLinker.getUUID(UUID_USER_ID)); - } - - @Test - public void getUUIDRetrievesUUIDFromDatabase() - { - configuration.linkingMethod = "uuid"; - when(player.getUniqueId()).thenReturn(uuid); - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUUID(UUID_USER_ID)).thenReturn(uuid.toString()); - assertEquals(uuid.toString(), userPlayerLinker.getUUID(UUID_USER_ID)); - } - - @Test - public void getPlayerNameNeverReturnsNull() - { - configuration.linkingMethod = "both"; - when(userIDDao.getUUID(anyString())).thenReturn(uuid.toString()); - when(bukkit.getPlayer(uuid)).thenReturn(player); - when(player.getName()).thenReturn(PLAYER_NAME); - assertNotNull(userPlayerLinker.getPlayerName(UUID_USER_ID)); - } - - @Test - public void getPlayerNameInNameModeReturnsPreviouslyCachedName() - { - configuration.linkingMethod = "name"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(player.getUniqueId()).thenReturn(uuid); - userPlayerLinker.getUserID(player); - assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(NAME_USER_ID)); - } - - @Test - public void getPlayerNameInUUIDModeReturnsNameByPreviouslyCachedUUID() - { - configuration.linkingMethod = "uuid"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - when(bukkit.getPlayer(uuid)).thenReturn(player); - userPlayerLinker.getUserID(player); - assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); - } - - @Test - public void getPlayerNameInBothModeReturnsNameByPreviouslyCachedUUID() - { - configuration.linkingMethod = "both"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - when(bukkit.getPlayer(uuid)).thenReturn(player); - userPlayerLinker.getUserID(player); - assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); - } - - @Test - public void getPlayerNameInBothModeReturnsPreviouslyCachedName() - { - configuration.linkingMethod = "both"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); - when(userIDDao.getUserID(uuid.toString())).thenReturn(""); - when(player.getUniqueId()).thenReturn(uuid); - userPlayerLinker.getUserID(player); - assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(NAME_USER_ID)); - } - - @Test - public void getPlayerNameInBothModeReturnsNormalName() - { - configuration.linkingMethod = "both"; - when(player.getName()).thenReturn(PLAYER_NAME); - when(player.getUniqueId()).thenReturn(uuid); - when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); - when(userIDDao.getUUID(UUID_USER_ID)).thenReturn(uuid.toString()); - when(bukkit.getPlayer(uuid)).thenReturn(player); - assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); - } +package org.communitybridge.linker; + +import org.communitybridge.main.BukkitWrapper; +import java.util.UUID; +import org.apache.commons.lang.RandomStringUtils; +import org.bukkit.entity.Player; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class UserPlayerLinkerTest +{ + private static final String NAME_USER_ID = RandomStringUtils.randomNumeric(2); + private static final String PLAYER_NAME = RandomStringUtils.randomAlphabetic(8); + private static final String UUID_USER_ID = RandomStringUtils.randomNumeric(2); + + private Player player = mock(Player.class); + private UUID uuid = new UUID(System.currentTimeMillis(), System.currentTimeMillis()); + private UserIDDao userIDDao = mock(UserIDDao.class); + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private BukkitWrapper bukkit = mock(BukkitWrapper.class); + + @InjectMocks + UserPlayerLinker userPlayerLinker = new UserPlayerLinker(environment, 1); + + @Before + public void setup() + { + environment.setConfiguration(configuration); + } + + @Test + public void getUserIDByUUIDNeverReturnsNull() + { + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + assertNotNull(userPlayerLinker.getUserID(uuid.toString())); + } + + @Test + public void getUserIDByUUIDWithUUIDReturnsUserID() + { + configuration.linkingMethod = "both"; + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + assertEquals(UUID_USER_ID, userPlayerLinker.getUserID(uuid.toString())); + } + + @Test + public void getUserIDByUUIDWithoutUUIDReturnsBlank() + { + configuration.linkingMethod = "uuid"; + when(userIDDao.getUserID(uuid.toString())).thenReturn(""); + assertEquals("", userPlayerLinker.getUserID(uuid.toString())); + } + + @Test + public void getUserIDByPlayerNeverReturnsNull() + { + configuration.linkingMethod = "both"; + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(anyString())).thenReturn(NAME_USER_ID); + assertNotNull(userPlayerLinker.getUserID(player)); + } + + @Test + public void getUserIDbyPlayerWithoutUUIDWithPlayernameReturnsPlayernameUserID() + { + configuration.linkingMethod = "both"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(uuid.toString())).thenReturn(""); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + assertEquals(NAME_USER_ID, userPlayerLinker.getUserID(player)); + } + + @Test + public void getUserIDByPlayerWithUUIDandWithPlayernameReturnsUUIDUserID() + { + configuration.linkingMethod = "both"; + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + assertEquals(UUID_USER_ID, userPlayerLinker.getUserID(player)); + } + + @Test + public void getUserIDWithUUIDandWithPlayernameUUIDOffReturnsPlayernameUserID() + { + configuration.linkingMethod = "name"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + assertEquals(NAME_USER_ID, userPlayerLinker.getUserID(player)); + } + + @Test + public void getUserIDWithoutUUIDandWithPlayernameUUIDOnReturnsBlank() + { + configuration.linkingMethod = "uuid"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(""); + assertEquals("", userPlayerLinker.getUserID(player)); + } + + @Test + public void getUserIDAddsUUIDEntryToCache() + { + configuration.linkingMethod = "uuid"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + assertEquals(UUID_USER_ID, userPlayerLinker.getUserIDCache().get(uuid.toString())); + } + + @Test + public void getUserIDAddsNameEntryToCache() + { + configuration.linkingMethod = "name"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + assertEquals(NAME_USER_ID, userPlayerLinker.getUserIDCache().get(PLAYER_NAME)); + } + + @Test + public void removeUserIDFromCacheRemovesUUIDEntry() + { + configuration.linkingMethod = "uuid"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + userPlayerLinker.removeUserIDFromCache(uuid.toString(), PLAYER_NAME); + assertNull(userPlayerLinker.getUserIDCache().get(uuid.toString())); + } + + @Test + public void removeUserIDFromCacheRemovesNameEntry() + { + configuration.linkingMethod = "name"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + userPlayerLinker.removeUserIDFromCache(uuid.toString(), PLAYER_NAME); + assertNull(userPlayerLinker.getUserIDCache().get(PLAYER_NAME)); + } + + @Test + public void secondLookupOnTinyCacheForcesFlush() + { + String someOtherName = RandomStringUtils.randomNumeric(6); + String someOtherID = RandomStringUtils.randomNumeric(2); + configuration.linkingMethod = "name"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME, someOtherName); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(someOtherName)).thenReturn(someOtherID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + userPlayerLinker.getUserID(player); + assertEquals(1, userPlayerLinker.getUserIDCache().size()); + assertEquals(someOtherID, userPlayerLinker.getUserIDCache().get(someOtherName)); + assertFalse(userPlayerLinker.getUserIDCache().containsKey(PLAYER_NAME)); + } + + @Test + public void getUUIDNeverReturnsNull() + { + configuration.linkingMethod = "both"; + when(userIDDao.getUUID(anyString())).thenReturn(uuid.toString()); + assertNotNull(userPlayerLinker.getUUID("")); + } + + @Test + public void getUUIDSuccessfullyRetrievesCachedEntry() + { + configuration.linkingMethod = "uuid"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + userPlayerLinker.getUserID(player); + assertEquals(uuid.toString(), userPlayerLinker.getUUID(UUID_USER_ID)); + } + + @Test + public void getUUIDRetrievesUUIDFromDatabase() + { + configuration.linkingMethod = "uuid"; + when(player.getUniqueId()).thenReturn(uuid); + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUUID(UUID_USER_ID)).thenReturn(uuid.toString()); + assertEquals(uuid.toString(), userPlayerLinker.getUUID(UUID_USER_ID)); + } + + @Test + public void getPlayerNameNeverReturnsNull() + { + configuration.linkingMethod = "both"; + when(userIDDao.getUUID(anyString())).thenReturn(uuid.toString()); + when(bukkit.getPlayer(uuid)).thenReturn(player); + when(player.getName()).thenReturn(PLAYER_NAME); + assertNotNull(userPlayerLinker.getPlayerName(UUID_USER_ID)); + } + + @Test + public void getPlayerNameInNameModeReturnsPreviouslyCachedName() + { + configuration.linkingMethod = "name"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(player.getUniqueId()).thenReturn(uuid); + userPlayerLinker.getUserID(player); + assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(NAME_USER_ID)); + } + + @Test + public void getPlayerNameInUUIDModeReturnsNameByPreviouslyCachedUUID() + { + configuration.linkingMethod = "uuid"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + when(bukkit.getPlayer(uuid)).thenReturn(player); + userPlayerLinker.getUserID(player); + assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); + } + + @Test + public void getPlayerNameInBothModeReturnsNameByPreviouslyCachedUUID() + { + configuration.linkingMethod = "both"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + when(bukkit.getPlayer(uuid)).thenReturn(player); + userPlayerLinker.getUserID(player); + assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); + } + + @Test + public void getPlayerNameInBothModeReturnsPreviouslyCachedName() + { + configuration.linkingMethod = "both"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(userIDDao.getUserID(PLAYER_NAME)).thenReturn(NAME_USER_ID); + when(userIDDao.getUserID(uuid.toString())).thenReturn(""); + when(player.getUniqueId()).thenReturn(uuid); + userPlayerLinker.getUserID(player); + assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(NAME_USER_ID)); + } + + @Test + public void getPlayerNameInBothModeReturnsNormalName() + { + configuration.linkingMethod = "both"; + when(player.getName()).thenReturn(PLAYER_NAME); + when(player.getUniqueId()).thenReturn(uuid); + when(userIDDao.getUserID(uuid.toString())).thenReturn(UUID_USER_ID); + when(userIDDao.getUUID(UUID_USER_ID)).thenReturn(uuid.toString()); + when(bukkit.getPlayer(uuid)).thenReturn(player); + assertEquals(PLAYER_NAME, userPlayerLinker.getPlayerName(UUID_USER_ID)); + } } \ No newline at end of file diff --git a/test/org/communitybridge/main/PlayerStatisticsTest.java b/test/org/communitybridge/main/PlayerStatisticsTest.java index 37259a7..cbc490b 100644 --- a/test/org/communitybridge/main/PlayerStatisticsTest.java +++ b/test/org/communitybridge/main/PlayerStatisticsTest.java @@ -1,55 +1,55 @@ -package org.communitybridge.main; - -import java.text.SimpleDateFormat; -import java.util.TimeZone; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; - -public class PlayerStatisticsTest -{ - private SimpleDateFormat dateFormat; - private PlayerStatistics playerStatistics; - - @Before - public void setup() - { - dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - playerStatistics = new PlayerStatistics(dateFormat); - } - - @Test - public void testGetGameTimeFormatted() - { - playerStatistics.setGameTime(0); - assertEquals("0 seconds", playerStatistics.getGameTimeFormatted()); - } - - @Test - public void testGetCurrentXPFormatted() - { - playerStatistics.setCurrentXP(0); - assertEquals("0%", playerStatistics.getCurrentXPFormatted()); - } - - @Test - public void testGetLastOnlineTimeFormatted() - { - playerStatistics.setLastOnlineTime(1406378311373L); - assertEquals("2014-07-26 12:38:31 PM", playerStatistics.getLastOnlineTimeFormatted()); - } - - @Test - public void testGetLifeTicksFormatted() - { - playerStatistics.setLifeTicks(0); - assertEquals("0 seconds", playerStatistics.getLifeTicksFormatted()); - } - - @Test - public void testGetLastOnlineTimeInSeconds() { - playerStatistics.setLastOnlineTime(1406378311373L); - assertEquals(1406378311, playerStatistics.getLastOnlineTimeInSeconds()); - } +package org.communitybridge.main; + +import java.text.SimpleDateFormat; +import java.util.TimeZone; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; + +public class PlayerStatisticsTest +{ + private SimpleDateFormat dateFormat; + private PlayerStatistics playerStatistics; + + @Before + public void setup() + { + dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + playerStatistics = new PlayerStatistics(dateFormat); + } + + @Test + public void testGetGameTimeFormatted() + { + playerStatistics.setGameTime(0); + assertEquals("0 seconds", playerStatistics.getGameTimeFormatted()); + } + + @Test + public void testGetCurrentXPFormatted() + { + playerStatistics.setCurrentXP(0); + assertEquals("0%", playerStatistics.getCurrentXPFormatted()); + } + + @Test + public void testGetLastOnlineTimeFormatted() + { + playerStatistics.setLastOnlineTime(1406378311373L); + assertEquals("2014-07-26 12:38:31 PM", playerStatistics.getLastOnlineTimeFormatted()); + } + + @Test + public void testGetLifeTicksFormatted() + { + playerStatistics.setLifeTicks(0); + assertEquals("0 seconds", playerStatistics.getLifeTicksFormatted()); + } + + @Test + public void testGetLastOnlineTimeInSeconds() { + playerStatistics.setLastOnlineTime(1406378311373L); + assertEquals(1406378311, playerStatistics.getLastOnlineTimeInSeconds()); + } } \ No newline at end of file diff --git a/test/org/communitybridge/permissionhandlers/PermissionHandlerTest.java b/test/org/communitybridge/permissionhandlers/PermissionHandlerTest.java index f855d15..f7f8ab5 100644 --- a/test/org/communitybridge/permissionhandlers/PermissionHandlerTest.java +++ b/test/org/communitybridge/permissionhandlers/PermissionHandlerTest.java @@ -1,242 +1,242 @@ -package org.communitybridge.permissionhandlers; - -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.communitybridge.main.BukkitWrapper; -import org.junit.Test; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class PermissionHandlerTest -{ - private String name = "someplugin"; - private String pluginVersion = "1.1"; - private Player player = mock(Player.class); - private Plugin plugin = mock(Plugin.class); - private PluginDescriptionFile description = new PluginDescriptionFile(name, pluginVersion, null); - private final String playerName = "somePlayer"; - private final String groupOne = "groupOne"; - private final String groupTwo = "groupTwo"; - - private BukkitWrapper bukkit = mock(BukkitWrapper.class); - private TestablePermissionHandler permissionHandler = new TestablePermissionHandler(bukkit); - - @Test - public void determineWorldFetchesPlayersWorld() - { - World world = mock(World.class); - - when(player.getWorld()).thenReturn(world); - String worldName = "worldName"; - when(world.getName()).thenReturn(worldName); - assertEquals(worldName, permissionHandler.determineWorld(player)); - } - - @Test - public void determineWorldUsesDefaultWorld() - { - String worldName = "worldName"; - Server server = mock(Server.class); - World world = mock(World.class); - List worlds = new ArrayList(); - worlds.add(world); - - when(bukkit.getServer()).thenReturn(server); - when(server.getWorlds()).thenReturn(worlds); - when(world.getName()).thenReturn(worldName); - assertEquals(worldName, permissionHandler.determineWorld(null)); - } - - @Test - public void switchGroupCallsRemoveGroup() - { - permissionHandler.switchGroup(player, groupOne, groupTwo); - assertEquals(playerName, permissionHandler.removePlayer); - assertEquals(groupOne, permissionHandler.removeGroup); - } - - @Test - public void switchGroupCallsDoesNotCallRemoveGroupOnNull() - { - permissionHandler.switchGroup(player, null, groupTwo); - assertEquals("", permissionHandler.removePlayer); - assertEquals("", permissionHandler.removeGroup); - } - - @Test - public void switchGroupCallsAddGroup() - { - permissionHandler.switchGroup(player, groupOne, groupTwo); - assertEquals(playerName, permissionHandler.addPlayer); - assertEquals(groupTwo, permissionHandler.addGroup); - } - - @Test - public void validateHandlerDoesNotThrowErrorWithValidPlugin() - { - when(plugin.isEnabled()).thenReturn(true); - when(plugin.getDescription()).thenReturn(description); - - try - { - permissionHandler.validate(plugin, name, pluginVersion); - } - catch (Exception exception) - { - fail("Caught an exception with valid plugin: " + exception.getMessage()); - } - } - - @Test - public void validateHandlerDoesNotThrowErrorWithValidPluginNewerVersion() - { - when(plugin.isEnabled()).thenReturn(true); - when(plugin.getDescription()).thenReturn(description); - - try - { - permissionHandler.validate(plugin, name, "1.0"); - } - catch (Exception exception) - { - fail("Caught an exception with valid plugin: " + exception.getMessage()); - } - } - - @Test - public void validateHandlerDoesThrowErrorWithValidPluginOlderVersion() - { - when(plugin.isEnabled()).thenReturn(true); - when(plugin.getDescription()).thenReturn(description); - String version = "1.2"; - - try - { - permissionHandler.validate(plugin, name, version); - fail("Failed to throw an exception."); - } - catch (IllegalStateException exception) - { - assertEquals(name + permissionHandler.WRONG_VERSION + version, exception.getMessage()); - } - catch (Exception exception) - { - fail("Threw incorrect exception: " + exception.getMessage()); - } - } - - @Test - public void validateHandlerDoesThrowErrorWithNullPlugin() - { - try - { - permissionHandler.validate(null, name, pluginVersion); - fail("Failed to throw an exception."); - } - catch (IllegalStateException exception) - { - assertEquals(name + permissionHandler.NOT_FOUND, exception.getMessage()); - } - catch (Exception exception) - { - fail("Threw incorrect exception: " + exception.getMessage()); - } - } - - @Test - public void validateHandlerDoesThrowErrorWithDisabledPlugin() - { - when(plugin.isEnabled()).thenReturn(false); - - try - { - permissionHandler.validate(plugin, name, pluginVersion); - fail("Failed to throw an exception."); - } - catch (IllegalStateException exception) - { - assertEquals(name + permissionHandler.NOT_ENABLED, exception.getMessage()); - } - catch (Exception exception) - { - fail("Threw incorrect exception." + exception.getMessage()); - } - } - - public class TestablePermissionHandler extends PermissionHandler - { - public String addPlayer = ""; - public String addGroup = ""; - public String removePlayer = ""; - public String removeGroup = ""; - - public TestablePermissionHandler(BukkitWrapper bukkit) - { - this.bukkit = bukkit; - } - - @Override - public boolean addToGroup(Player player, String groupName) - { - addPlayer = playerName; - addGroup = groupName; - return true; - } - - @Override - public boolean removeFromGroup(Player player, String groupName) - { - removePlayer = playerName; - removeGroup = groupName; - return true; - } - - @Override - public List getGroups(Player player) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public List getGroupsPure(Player player) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public String getPrimaryGroup(Player player) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public boolean isMemberOfGroup(Player player, String groupName) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public boolean isPrimaryGroup(Player player, String groupName) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - - @Override - public boolean supportsPrimaryGroups() - { - throw new UnsupportedOperationException("No implementation needed for tests."); - } - } +package org.communitybridge.permissionhandlers; + +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.communitybridge.main.BukkitWrapper; +import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PermissionHandlerTest +{ + private String name = "someplugin"; + private String pluginVersion = "1.1"; + private Player player = mock(Player.class); + private Plugin plugin = mock(Plugin.class); + private PluginDescriptionFile description = new PluginDescriptionFile(name, pluginVersion, null); + private final String playerName = "somePlayer"; + private final String groupOne = "groupOne"; + private final String groupTwo = "groupTwo"; + + private BukkitWrapper bukkit = mock(BukkitWrapper.class); + private TestablePermissionHandler permissionHandler = new TestablePermissionHandler(bukkit); + + @Test + public void determineWorldFetchesPlayersWorld() + { + World world = mock(World.class); + + when(player.getWorld()).thenReturn(world); + String worldName = "worldName"; + when(world.getName()).thenReturn(worldName); + assertEquals(worldName, permissionHandler.determineWorld(player)); + } + + @Test + public void determineWorldUsesDefaultWorld() + { + String worldName = "worldName"; + Server server = mock(Server.class); + World world = mock(World.class); + List worlds = new ArrayList(); + worlds.add(world); + + when(bukkit.getServer()).thenReturn(server); + when(server.getWorlds()).thenReturn(worlds); + when(world.getName()).thenReturn(worldName); + assertEquals(worldName, permissionHandler.determineWorld(null)); + } + + @Test + public void switchGroupCallsRemoveGroup() + { + permissionHandler.switchGroup(player, groupOne, groupTwo); + assertEquals(playerName, permissionHandler.removePlayer); + assertEquals(groupOne, permissionHandler.removeGroup); + } + + @Test + public void switchGroupCallsDoesNotCallRemoveGroupOnNull() + { + permissionHandler.switchGroup(player, null, groupTwo); + assertEquals("", permissionHandler.removePlayer); + assertEquals("", permissionHandler.removeGroup); + } + + @Test + public void switchGroupCallsAddGroup() + { + permissionHandler.switchGroup(player, groupOne, groupTwo); + assertEquals(playerName, permissionHandler.addPlayer); + assertEquals(groupTwo, permissionHandler.addGroup); + } + + @Test + public void validateHandlerDoesNotThrowErrorWithValidPlugin() + { + when(plugin.isEnabled()).thenReturn(true); + when(plugin.getDescription()).thenReturn(description); + + try + { + permissionHandler.validate(plugin, name, pluginVersion); + } + catch (Exception exception) + { + fail("Caught an exception with valid plugin: " + exception.getMessage()); + } + } + + @Test + public void validateHandlerDoesNotThrowErrorWithValidPluginNewerVersion() + { + when(plugin.isEnabled()).thenReturn(true); + when(plugin.getDescription()).thenReturn(description); + + try + { + permissionHandler.validate(plugin, name, "1.0"); + } + catch (Exception exception) + { + fail("Caught an exception with valid plugin: " + exception.getMessage()); + } + } + + @Test + public void validateHandlerDoesThrowErrorWithValidPluginOlderVersion() + { + when(plugin.isEnabled()).thenReturn(true); + when(plugin.getDescription()).thenReturn(description); + String version = "1.2"; + + try + { + permissionHandler.validate(plugin, name, version); + fail("Failed to throw an exception."); + } + catch (IllegalStateException exception) + { + assertEquals(name + permissionHandler.WRONG_VERSION + version, exception.getMessage()); + } + catch (Exception exception) + { + fail("Threw incorrect exception: " + exception.getMessage()); + } + } + + @Test + public void validateHandlerDoesThrowErrorWithNullPlugin() + { + try + { + permissionHandler.validate(null, name, pluginVersion); + fail("Failed to throw an exception."); + } + catch (IllegalStateException exception) + { + assertEquals(name + permissionHandler.NOT_FOUND, exception.getMessage()); + } + catch (Exception exception) + { + fail("Threw incorrect exception: " + exception.getMessage()); + } + } + + @Test + public void validateHandlerDoesThrowErrorWithDisabledPlugin() + { + when(plugin.isEnabled()).thenReturn(false); + + try + { + permissionHandler.validate(plugin, name, pluginVersion); + fail("Failed to throw an exception."); + } + catch (IllegalStateException exception) + { + assertEquals(name + permissionHandler.NOT_ENABLED, exception.getMessage()); + } + catch (Exception exception) + { + fail("Threw incorrect exception." + exception.getMessage()); + } + } + + public class TestablePermissionHandler extends PermissionHandler + { + public String addPlayer = ""; + public String addGroup = ""; + public String removePlayer = ""; + public String removeGroup = ""; + + public TestablePermissionHandler(BukkitWrapper bukkit) + { + this.bukkit = bukkit; + } + + @Override + public boolean addToGroup(Player player, String groupName) + { + addPlayer = playerName; + addGroup = groupName; + return true; + } + + @Override + public boolean removeFromGroup(Player player, String groupName) + { + removePlayer = playerName; + removeGroup = groupName; + return true; + } + + @Override + public List getGroups(Player player) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public List getGroupsPure(Player player) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public String getPrimaryGroup(Player player) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public boolean isMemberOfGroup(Player player, String groupName) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public boolean isPrimaryGroup(Player player, String groupName) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName) + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + + @Override + public boolean supportsPrimaryGroups() + { + throw new UnsupportedOperationException("No implementation needed for tests."); + } + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/MoneySynchronizerTest.java b/test/org/communitybridge/synchronization/MoneySynchronizerTest.java index 0744632..d310c68 100644 --- a/test/org/communitybridge/synchronization/MoneySynchronizerTest.java +++ b/test/org/communitybridge/synchronization/MoneySynchronizerTest.java @@ -1,222 +1,222 @@ -package org.communitybridge.synchronization; - -import java.net.MalformedURLException; -import net.milkbowl.vault.economy.Economy; -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.math.RandomUtils; -import org.bukkit.entity.Player; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.WebApplication; -import org.communitybridge.synchronization.dao.MoneyDao; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.AdditionalMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class MoneySynchronizerTest -{ - private String USER_ID = RandomStringUtils.randomAlphabetic(13); - private static final double DOUBLE_DELTA = 0.001; - private Configuration configuration = Mockito.mock(Configuration.class); - private Economy economy = Mockito.mock(Economy.class); - private WebApplication webApplication = Mockito.mock(WebApplication.class); - - private Environment environment = new Environment(); - - private Player player = Mockito.mock(Player.class); - private PlayerState previous = Mockito.mock(PlayerState.class); - private PlayerState current = Mockito.mock(PlayerState.class); - private PlayerState result = Mockito.mock(PlayerState.class); - private MoneyDao money = Mockito.mock(MoneyDao.class); - - @InjectMocks - private MoneySynchronizer synchronizer = new MoneySynchronizer(environment); - - @Before - public void beforeEach() - { - environment.setConfiguration(configuration); - environment.setEconomy(economy); - environment.setWebApplication(webApplication); - } - - @Test - public void isActiveReturnsTrue() - { - configuration.walletEnabled = true; - Assert.assertTrue(synchronizer.isActive(environment)); - } - - @Test - public void isActiveReturnsFalse() - { - configuration.walletEnabled = false; - Assert.assertFalse(synchronizer.isActive(environment)); - } - - @Test - public void synchronizeShouldNeverReturnNull() - { - PlayerState newState = synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - Assert.assertNotNull(newState); - } - - @Test - public void synchronizeWithNoChangeShouldReturnSameState() - { - PlayerState newState = synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - Assert.assertEquals(result, newState); - } - - @Test - public void synchronizeWithPositiveWebChangeShouldDeposit() - { - double webPrevious = RandomUtils.nextDouble(); - double webCurrent = webPrevious * 2; - double expected = webCurrent - webPrevious; - - Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(economy).depositPlayer(player, expected); - } - - @Test - public void synchronizeWithNegativeWebChangeShouldWithdraw() - { - double webCurrent = RandomUtils.nextDouble(); - double webPrevious = webCurrent * 2; - double expected = Math.abs(webCurrent - webPrevious); - - Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(economy).withdrawPlayer(player, expected); - } - - @Test - public void synchronizeWithPositiveWebChangeShouldUpdateResult() - { - double mcCurrent = RandomUtils.nextDouble(); - double webPrevious = RandomUtils.nextDouble(); - double webCurrent = webPrevious * 2; - double expected = mcCurrent + webCurrent - webPrevious; - - Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(result).setMinecraftWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); - } - - @Test - public void synchronizeWithNegativeWebChangeShouldUpdateResult() - { - double mcCurrent = RandomUtils.nextDouble(); - double webCurrent = RandomUtils.nextDouble(); - double webPrevious = webCurrent * 2; - double expected = mcCurrent + webCurrent - webPrevious; - - Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(result).setMinecraftWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); - } - - @Test - public void synchronizeWithNoChangeShouldNotChangePlayersBalance() - { - double webCurrent = RandomUtils.nextDouble(); - - Mockito.when(previous.getWebApplicationWallet()).thenReturn(webCurrent); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(economy, Mockito.never()).depositPlayer(Mockito.eq(player), Mockito.anyDouble()); - Mockito.verify(economy, Mockito.never()).withdrawPlayer(Mockito.eq(player), Mockito.anyDouble()); - } - - @Test - public void synchronizeWithPositiveGameChangeShouldUpdateWeb() throws IllegalAccessException, InstantiationException, MalformedURLException - { - double mcPrevious = RandomUtils.nextDouble(); - double mcCurrent = mcPrevious * 2; - double webCurrent = RandomUtils.nextDouble(); - double expected = webCurrent + mcCurrent - mcPrevious; - - Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(money).setBalance(Mockito.eq(environment), Mockito.eq(USER_ID), - AdditionalMatchers.eq(expected, DOUBLE_DELTA)); - } - - @Test - public void synchronizeWithNegativeGameChangeShouldUpdateWeb() throws IllegalAccessException, InstantiationException, MalformedURLException - { - double mcCurrent = RandomUtils.nextDouble(); - double mcPrevious = mcCurrent * 2; - double webCurrent = RandomUtils.nextDouble(); - double expected = webCurrent + mcCurrent - mcPrevious; - - Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(money).setBalance(Mockito.eq(environment), Mockito.eq(USER_ID), - AdditionalMatchers.eq(expected, DOUBLE_DELTA)); - } - - @Test - public void synchronizeWithGameChangeShouldUpdateResult() - { - double mcPrevious = RandomUtils.nextDouble(); - double mcCurrent = mcPrevious * 2; - double webCurrent = RandomUtils.nextDouble(); - double expected = webCurrent + mcCurrent - mcPrevious; - - Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(result).setWebApplicationWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); - } - - @Test - public void synchronizeWithNoGameChangeShouldNotUpdateWeb() - { - double mcCurrent = RandomUtils.nextDouble(); - double webCurrent = RandomUtils.nextDouble(); - - Mockito.when(previous.getMinecraftWallet()).thenReturn(mcCurrent); - Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); - Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); - - synchronizer.synchronize(environment, player, USER_ID, previous, current, result); - - Mockito.verify(webApplication, Mockito.never()).setBalance(Mockito.eq(USER_ID), Mockito.anyDouble()); - } +package org.communitybridge.synchronization; + +import java.net.MalformedURLException; +import net.milkbowl.vault.economy.Economy; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.math.RandomUtils; +import org.bukkit.entity.Player; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.WebApplication; +import org.communitybridge.synchronization.dao.MoneyDao; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.AdditionalMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MoneySynchronizerTest +{ + private String USER_ID = RandomStringUtils.randomAlphabetic(13); + private static final double DOUBLE_DELTA = 0.001; + private Configuration configuration = Mockito.mock(Configuration.class); + private Economy economy = Mockito.mock(Economy.class); + private WebApplication webApplication = Mockito.mock(WebApplication.class); + + private Environment environment = new Environment(); + + private Player player = Mockito.mock(Player.class); + private PlayerState previous = Mockito.mock(PlayerState.class); + private PlayerState current = Mockito.mock(PlayerState.class); + private PlayerState result = Mockito.mock(PlayerState.class); + private MoneyDao money = Mockito.mock(MoneyDao.class); + + @InjectMocks + private MoneySynchronizer synchronizer = new MoneySynchronizer(environment); + + @Before + public void beforeEach() + { + environment.setConfiguration(configuration); + environment.setEconomy(economy); + environment.setWebApplication(webApplication); + } + + @Test + public void isActiveReturnsTrue() + { + configuration.walletEnabled = true; + Assert.assertTrue(synchronizer.isActive(environment)); + } + + @Test + public void isActiveReturnsFalse() + { + configuration.walletEnabled = false; + Assert.assertFalse(synchronizer.isActive(environment)); + } + + @Test + public void synchronizeShouldNeverReturnNull() + { + PlayerState newState = synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + Assert.assertNotNull(newState); + } + + @Test + public void synchronizeWithNoChangeShouldReturnSameState() + { + PlayerState newState = synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + Assert.assertEquals(result, newState); + } + + @Test + public void synchronizeWithPositiveWebChangeShouldDeposit() + { + double webPrevious = RandomUtils.nextDouble(); + double webCurrent = webPrevious * 2; + double expected = webCurrent - webPrevious; + + Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(economy).depositPlayer(player, expected); + } + + @Test + public void synchronizeWithNegativeWebChangeShouldWithdraw() + { + double webCurrent = RandomUtils.nextDouble(); + double webPrevious = webCurrent * 2; + double expected = Math.abs(webCurrent - webPrevious); + + Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(economy).withdrawPlayer(player, expected); + } + + @Test + public void synchronizeWithPositiveWebChangeShouldUpdateResult() + { + double mcCurrent = RandomUtils.nextDouble(); + double webPrevious = RandomUtils.nextDouble(); + double webCurrent = webPrevious * 2; + double expected = mcCurrent + webCurrent - webPrevious; + + Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(result).setMinecraftWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); + } + + @Test + public void synchronizeWithNegativeWebChangeShouldUpdateResult() + { + double mcCurrent = RandomUtils.nextDouble(); + double webCurrent = RandomUtils.nextDouble(); + double webPrevious = webCurrent * 2; + double expected = mcCurrent + webCurrent - webPrevious; + + Mockito.when(previous.getWebApplicationWallet()).thenReturn(webPrevious); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(result).setMinecraftWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); + } + + @Test + public void synchronizeWithNoChangeShouldNotChangePlayersBalance() + { + double webCurrent = RandomUtils.nextDouble(); + + Mockito.when(previous.getWebApplicationWallet()).thenReturn(webCurrent); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(economy, Mockito.never()).depositPlayer(Mockito.eq(player), Mockito.anyDouble()); + Mockito.verify(economy, Mockito.never()).withdrawPlayer(Mockito.eq(player), Mockito.anyDouble()); + } + + @Test + public void synchronizeWithPositiveGameChangeShouldUpdateWeb() throws IllegalAccessException, InstantiationException, MalformedURLException + { + double mcPrevious = RandomUtils.nextDouble(); + double mcCurrent = mcPrevious * 2; + double webCurrent = RandomUtils.nextDouble(); + double expected = webCurrent + mcCurrent - mcPrevious; + + Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(money).setBalance(Mockito.eq(environment), Mockito.eq(USER_ID), + AdditionalMatchers.eq(expected, DOUBLE_DELTA)); + } + + @Test + public void synchronizeWithNegativeGameChangeShouldUpdateWeb() throws IllegalAccessException, InstantiationException, MalformedURLException + { + double mcCurrent = RandomUtils.nextDouble(); + double mcPrevious = mcCurrent * 2; + double webCurrent = RandomUtils.nextDouble(); + double expected = webCurrent + mcCurrent - mcPrevious; + + Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(money).setBalance(Mockito.eq(environment), Mockito.eq(USER_ID), + AdditionalMatchers.eq(expected, DOUBLE_DELTA)); + } + + @Test + public void synchronizeWithGameChangeShouldUpdateResult() + { + double mcPrevious = RandomUtils.nextDouble(); + double mcCurrent = mcPrevious * 2; + double webCurrent = RandomUtils.nextDouble(); + double expected = webCurrent + mcCurrent - mcPrevious; + + Mockito.when(previous.getMinecraftWallet()).thenReturn(mcPrevious); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(result).setWebApplicationWallet(AdditionalMatchers.eq(expected, DOUBLE_DELTA)); + } + + @Test + public void synchronizeWithNoGameChangeShouldNotUpdateWeb() + { + double mcCurrent = RandomUtils.nextDouble(); + double webCurrent = RandomUtils.nextDouble(); + + Mockito.when(previous.getMinecraftWallet()).thenReturn(mcCurrent); + Mockito.when(current.getMinecraftWallet()).thenReturn(mcCurrent); + Mockito.when(current.getWebApplicationWallet()).thenReturn(webCurrent); + + synchronizer.synchronize(environment, player, USER_ID, previous, current, result); + + Mockito.verify(webApplication, Mockito.never()).setBalance(Mockito.eq(USER_ID), Mockito.anyDouble()); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/PlayerFileFetcherTest.java b/test/org/communitybridge/synchronization/PlayerFileFetcherTest.java index 17774d0..0ccc4f7 100644 --- a/test/org/communitybridge/synchronization/PlayerFileFetcherTest.java +++ b/test/org/communitybridge/synchronization/PlayerFileFetcherTest.java @@ -1,94 +1,94 @@ -package org.communitybridge.synchronization; - -import java.io.File; -import java.io.IOException; -import java.util.UUID; -import org.apache.commons.lang.math.RandomUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.bukkit.entity.Player; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import static org.mockito.Mockito.*; - -public class PlayerFileFetcherTest -{ - private PlayerFileFetcher fetcher = new PlayerFileFetcher(); - private Player player = mock(Player.class); - private UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); - private String PLAYER_NAME = RandomStringUtils.randomAlphabetic(10); - @Mock private File folder; - private File mockPlayerFile = mock(File.class); - private File file = new File("/"); - - private PlayerFileFetcher fetcher2 = spy(new PlayerFileFetcher()); - @Before - public void beforeEach() - { - when(player.getUniqueId()).thenReturn(UUID); - when(player.getName()).thenReturn(PLAYER_NAME); - } - - @Test - public void getPlayerShouldNeverReturnNull() - { - Assert.assertNotNull(fetcher.getPlayerFile(file, player, false)); - Assert.assertNotNull(fetcher.getPlayerFile(file, player, true)); - } - - @Test - public void getPlayerShouldUsePlayersFolder() throws IOException - { - File playerFile = fetcher.getPlayerFile(file, player, false); - Assert.assertEquals("Players", playerFile.getParent().substring(1)); - } - - @Test - public void getPlayerShouldUseUUID() - { - File playerFile = fetcher.getPlayerFile(file, player, false); - Assert.assertEquals(player.getUniqueId().toString() + ".yml", playerFile.getName()); - } - - @Test - public void getPlayerWhenTypicalDoesNotExistAndAllowedShouldReturnOldPlayerFile() - { - doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); - doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); - when(mockPlayerFile.exists()).thenReturn(false); - File playerFile = fetcher2.getPlayerFile(file, player, true); - Assert.assertEquals(player.getName() + ".yml", playerFile.getName()); - } - - @Test - public void getPlayerWhenTypicalDoesNotExistAndNotAllowedShouldReturnTypicalPlayerFile() - { - doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); - doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); - when(mockPlayerFile.exists()).thenReturn(false); - File playerFile = fetcher2.getPlayerFile(file, player, false); - Assert.assertSame(mockPlayerFile, playerFile); - } - - @Test - public void getPlayerWhenTypicalDoesExistAndAllowedShouldReturnTypicalPlayerFile() - { - doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); - doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); - when(mockPlayerFile.exists()).thenReturn(true); - File playerFile = fetcher2.getPlayerFile(file, player, true); - Assert.assertSame(mockPlayerFile, playerFile); - } - - @Test - public void getPlayerWhenTypicalDoesExistAndNotAllowedShouldReturnTypicalPlayerFile() - { - doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); - doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); - when(mockPlayerFile.exists()).thenReturn(true); - File playerFile = fetcher2.getPlayerFile(file, player, false); - Assert.assertSame(mockPlayerFile, playerFile); - } -} - +package org.communitybridge.synchronization; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; +import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.bukkit.entity.Player; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import static org.mockito.Mockito.*; + +public class PlayerFileFetcherTest +{ + private PlayerFileFetcher fetcher = new PlayerFileFetcher(); + private Player player = mock(Player.class); + private UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); + private String PLAYER_NAME = RandomStringUtils.randomAlphabetic(10); + @Mock private File folder; + private File mockPlayerFile = mock(File.class); + private File file = new File("/"); + + private PlayerFileFetcher fetcher2 = spy(new PlayerFileFetcher()); + @Before + public void beforeEach() + { + when(player.getUniqueId()).thenReturn(UUID); + when(player.getName()).thenReturn(PLAYER_NAME); + } + + @Test + public void getPlayerShouldNeverReturnNull() + { + Assert.assertNotNull(fetcher.getPlayerFile(file, player, false)); + Assert.assertNotNull(fetcher.getPlayerFile(file, player, true)); + } + + @Test + public void getPlayerShouldUsePlayersFolder() throws IOException + { + File playerFile = fetcher.getPlayerFile(file, player, false); + Assert.assertEquals("Players", playerFile.getParent().substring(1)); + } + + @Test + public void getPlayerShouldUseUUID() + { + File playerFile = fetcher.getPlayerFile(file, player, false); + Assert.assertEquals(player.getUniqueId().toString() + ".yml", playerFile.getName()); + } + + @Test + public void getPlayerWhenTypicalDoesNotExistAndAllowedShouldReturnOldPlayerFile() + { + doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); + doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); + when(mockPlayerFile.exists()).thenReturn(false); + File playerFile = fetcher2.getPlayerFile(file, player, true); + Assert.assertEquals(player.getName() + ".yml", playerFile.getName()); + } + + @Test + public void getPlayerWhenTypicalDoesNotExistAndNotAllowedShouldReturnTypicalPlayerFile() + { + doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); + doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); + when(mockPlayerFile.exists()).thenReturn(false); + File playerFile = fetcher2.getPlayerFile(file, player, false); + Assert.assertSame(mockPlayerFile, playerFile); + } + + @Test + public void getPlayerWhenTypicalDoesExistAndAllowedShouldReturnTypicalPlayerFile() + { + doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); + doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); + when(mockPlayerFile.exists()).thenReturn(true); + File playerFile = fetcher2.getPlayerFile(file, player, true); + Assert.assertSame(mockPlayerFile, playerFile); + } + + @Test + public void getPlayerWhenTypicalDoesExistAndNotAllowedShouldReturnTypicalPlayerFile() + { + doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString()); + doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString()); + when(mockPlayerFile.exists()).thenReturn(true); + File playerFile = fetcher2.getPlayerFile(file, player, false); + Assert.assertSame(mockPlayerFile, playerFile); + } +} + diff --git a/test/org/communitybridge/synchronization/PlayerStateTest.java b/test/org/communitybridge/synchronization/PlayerStateTest.java index ff07df4..9c3864a 100644 --- a/test/org/communitybridge/synchronization/PlayerStateTest.java +++ b/test/org/communitybridge/synchronization/PlayerStateTest.java @@ -1,387 +1,387 @@ -package org.communitybridge.synchronization; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import net.milkbowl.vault.economy.Economy; -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.math.RandomUtils; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.communitybridge.main.CommunityBridge; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.WebApplication; -import org.communitybridge.permissionhandlers.PermissionHandler; -import org.communitybridge.synchronization.dao.MoneyDao; -import org.communitybridge.utility.Log; -import org.junit.Test; -import org.junit.Before; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import static org.mockito.Mockito.*; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(YamlConfiguration.class) -public class PlayerStateTest -{ - private static final String PLAYER_NAME = RandomStringUtils.randomAlphabetic(9); - private static final String PRIMARY_GROUP_NAME = RandomStringUtils.randomAlphabetic(7); - private static final String USER_ID = RandomStringUtils.randomNumeric(3); - private static final String PRIMARY_GROUP_ID = RandomStringUtils.randomNumeric(2); - private static final List GROUP_NAMES = new ArrayList(Arrays.asList(new String[] {RandomStringUtils.randomAlphabetic(7), RandomStringUtils.randomAlphabetic(7), RandomStringUtils.randomAlphabetic(7)})); - private static final List GROUP_IDS = new ArrayList(Arrays.asList(new String[] {RandomStringUtils.randomNumeric(2), RandomStringUtils.randomNumeric(2), RandomStringUtils.randomNumeric(2)})); - - private static final UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); - - private Environment environment = new Environment(); - private Economy economy = mock(Economy.class); - private PermissionHandler permissionHandler = mock(PermissionHandler.class); - private Configuration configuration = mock(Configuration.class); - private CommunityBridge plugin = mock(CommunityBridge.class); - private Log log = mock(Log.class); - private Player player = mock(Player.class); - private MoneyDao money = mock(MoneyDao.class); - private WebApplication webApplication = mock(WebApplication.class); - - private YamlConfiguration playerData = mock(YamlConfiguration.class); - private File playerFile = mock(File.class); - private File oldPlayerFile = mock(File.class); - - @InjectMocks - private PlayerState state = new PlayerState(); - - @Before - public void beforeEach() { - environment.setConfiguration(configuration); - environment.setEconomy(economy); - environment.setLog(log); - environment.setPermissionHandler(permissionHandler); - environment.setPlugin(plugin); - environment.setWebApplication(webApplication); - configuration.simpleSynchronizationGroupsTreatedAsPrimary = new ArrayList(); - configuration.simpleSynchronizationGroupsTreatedAsPrimary.add(PRIMARY_GROUP_NAME); - configuration.groupSynchronizationActive = true; - configuration.webappPrimaryGroupEnabled = true; - configuration.webappSecondaryGroupEnabled = true; - when(player.getUniqueId()).thenReturn(UUID); - when(player.getName()).thenReturn(PLAYER_NAME); - when(webApplication.getUserPrimaryGroupID(USER_ID)).thenReturn(PRIMARY_GROUP_ID); - when(webApplication.getUserSecondaryGroupIDs(USER_ID)).thenReturn(GROUP_IDS); - when(permissionHandler.supportsPrimaryGroups()).thenReturn(true); - when(permissionHandler.getPrimaryGroup(player)).thenReturn(PRIMARY_GROUP_NAME); - when(permissionHandler.getGroups(player)).thenReturn(GROUP_NAMES); - } - - @Test - public void generateSetsPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - - assertEquals(PRIMARY_GROUP_ID, state.getWebappPrimaryGroupID()); - } - - @Test - public void generateWhenGroupSynchronizationInactiveDoesNotSetPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = false; - state.generate(environment, player, USER_ID); - - assertEquals("", state.getWebappPrimaryGroupID()); - } - - @Test - public void generateWhenPrimaryGroupInactiveDoesNotSetPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = true; - configuration.webappPrimaryGroupEnabled = false; - state.generate(environment, player, USER_ID); - - assertEquals("", state.getWebappPrimaryGroupID()); - } - - @Test - public void generateSetsGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - for (String id : GROUP_IDS) - { - assertTrue(id + "missing", state.getWebappGroupIDs().contains(id)); - } - } - - @Test - public void generateWhenGroupSynchronizationInactiveDoesNotSetGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = false; - state.generate(environment, player, USER_ID); - - assertTrue(state.getWebappGroupIDs().isEmpty()); - } - - @Test - public void generateWhenSecondaryGroupInactiveDoesNotSetGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = true; - configuration.webappSecondaryGroupEnabled = false; - state.generate(environment, player, USER_ID); - - assertTrue(state.getWebappGroupIDs().isEmpty()); - } - - @Test - public void generateSetsPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void generateWhenPrimaryGroupNotSupportedSetsPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - when(permissionHandler.supportsPrimaryGroups()).thenReturn(false); - GROUP_NAMES.add(PRIMARY_GROUP_NAME); - state.generate(environment, player, USER_ID); - assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void generateWhenPrimaryGroupNotSupportedSetsBlankOnNotFound() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - when(permissionHandler.supportsPrimaryGroups()).thenReturn(false); - state.generate(environment, player, USER_ID); - assertEquals("", state.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void generateWhenGroupSynchronizationInactiveDoesNotSetPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = false; - state.generate(environment, player, USER_ID); - - assertEquals("", state.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void generateSetsGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - - for (String group : GROUP_NAMES) - { - assertTrue(group + "missing", state.getPermissionsSystemGroupNames().contains(group)); - } - } - - @Test - public void generateWhenGroupSynchronizationInactiveDoesNotSetGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.groupSynchronizationActive = false; - state.generate(environment, player, USER_ID); - - assertTrue(state.getPermissionsSystemGroupNames().isEmpty()); - } - - @Test - public void generateSetsMinecraftWallet() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double wallet = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - - when(economy.getBalance(player)).thenReturn(wallet); - - state.generate(environment, player, USER_ID); - - assertEquals(wallet, state.getMinecraftWallet(), 0); - } - - @Test - public void generateSetsWebApplicationWallet() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double wallet = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - when(money.getBalance(environment, USER_ID)).thenReturn(wallet); - state.generate(environment, player, USER_ID); - - assertEquals(wallet, state.getWebApplicationWallet(), 0); - } - - @Test - public void copyNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - assertNotNull(copy); - } - - @Test - public void copyCopiesPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - assertEquals(state.getWebappPrimaryGroupID(), copy.getWebappPrimaryGroupID()); - } - - @Test - public void copyCopiesGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - assertEquals(state.getWebappGroupIDs(), copy.getWebappGroupIDs()); - } - - @Test - public void copyCopiesPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - - assertEquals(state.getPermissionsSystemPrimaryGroupName(), copy.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void copyCopiesGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - - assertEquals(state.getPermissionsSystemGroupNames(), copy.getPermissionsSystemGroupNames()); - } - - @Test - public void copyCopiesMinecraftMoney() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double wallet = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - - when(economy.getBalance(player)).thenReturn(wallet); - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - - assertEquals(wallet, copy.getMinecraftWallet(), 0); - } - - @Test - public void copyCopiesWebApplicationMoney() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double wallet = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - - when(money.getBalance(environment, USER_ID)).thenReturn(wallet); - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - - assertEquals(wallet, copy.getWebApplicationWallet(), 0); - } - - @Test - public void copyCopiesNewFile() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - state.generate(environment, player, USER_ID); - PlayerState copy = state.copy(); - - assertEquals(state.isIsNewFile(), copy.isIsNewFile()); - } - - @Test - public void saveSavesData() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double mcWallet = RandomUtils.nextDouble() + 1; - double wbWallet = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - - when(economy.getBalance(player)).thenReturn(mcWallet); - when(money.getBalance(environment, USER_ID)).thenReturn(wbWallet); - - state.generate(environment, player, USER_ID); - state.save(player, playerFile, environment.getLog()); - - verify(playerData).set("last-known-name", PLAYER_NAME); - verify(playerData).set("minecraft-money", mcWallet); - verify(playerData).set("web-application-money", wbWallet); - verify(playerData).set("permissions-system.primary-group-name", PRIMARY_GROUP_NAME); - verify(playerData).set("permissions-system.group-names", GROUP_NAMES); - verify(playerData).set("webapp.primary-group-id", PRIMARY_GROUP_ID); - verify(playerData).set("webapp.group-ids", GROUP_IDS); - verify(playerData).save(any(File.class)); - } - - @Test - public void saveHandlesIOException() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double money = RandomUtils.nextDouble() + 1; - configuration.economyEnabled = true; - configuration.walletEnabled = true; - - when(economy.getBalance(player)).thenReturn(money); - doNothing().when(playerData).set(anyString(), anyString()); - String exceptionMessage = RandomStringUtils.randomAlphabetic(18); - doThrow(new IOException(exceptionMessage)).when(playerData).save(any(File.class)); - - state.generate(environment, player, USER_ID); - state.save(player, playerFile, environment.getLog()); - verify(log).severe("Exception while saving player state for " + player.getName() + ": " + exceptionMessage); - } - - @Test - public void loadHandlesNewFile() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - when(playerFile.exists()).thenReturn(false); - when(oldPlayerFile.exists()).thenReturn(false); - state.load(playerFile); - assertEquals(true, state.isIsNewFile()); - assertEquals("", state.getWebappPrimaryGroupID()); - assertTrue("Group name list should be empty", state.getPermissionsSystemGroupNames().isEmpty()); - assertTrue("Group id list should be empty", state.getWebappGroupIDs().isEmpty()); - assertEquals("", state.getPermissionsSystemPrimaryGroupName()); - } - - @Test - public void loadLoadsData() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - double mcWallet = RandomUtils.nextDouble() + 1; - double waWallet = RandomUtils.nextDouble() + 1; - - when(playerFile.exists()).thenReturn(true); - when(oldPlayerFile.exists()).thenReturn(true); - PowerMockito.mockStatic(YamlConfiguration.class); - when(YamlConfiguration.loadConfiguration(playerFile)).thenReturn(playerData); - when(playerData.getDouble("minecraft-money", 0)).thenReturn(mcWallet); - when(playerData.getDouble("web-application-money", 0)).thenReturn(waWallet); - when(playerData.getStringList("permissions-system.group-names")).thenReturn(GROUP_NAMES); - when(playerData.getString("permissions-system.primary-group-name", "")).thenReturn(PRIMARY_GROUP_NAME); - when(playerData.getStringList("webapp.group-ids")).thenReturn(GROUP_IDS); - when(playerData.getString("webapp.primary-group-id", "")).thenReturn(PRIMARY_GROUP_ID); - state.load(playerFile); - - assertEquals(false, state.isIsNewFile()); - assertEquals(mcWallet, state.getMinecraftWallet(), 0); - assertEquals(waWallet, state.getWebApplicationWallet(), 0); - assertEquals(PRIMARY_GROUP_ID, state.getWebappPrimaryGroupID()); - assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); - - for (String group : GROUP_NAMES) - { - assertTrue(group + " missing.", state.getPermissionsSystemGroupNames().contains(group)); - } - - for (String id : GROUP_IDS) - { - assertTrue(id + " missing.", state.getWebappGroupIDs().contains(id)); - } - } +package org.communitybridge.synchronization; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.milkbowl.vault.economy.Economy; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.math.RandomUtils; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.communitybridge.main.CommunityBridge; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.WebApplication; +import org.communitybridge.permissionhandlers.PermissionHandler; +import org.communitybridge.synchronization.dao.MoneyDao; +import org.communitybridge.utility.Log; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import static org.mockito.Mockito.*; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(YamlConfiguration.class) +public class PlayerStateTest +{ + private static final String PLAYER_NAME = RandomStringUtils.randomAlphabetic(9); + private static final String PRIMARY_GROUP_NAME = RandomStringUtils.randomAlphabetic(7); + private static final String USER_ID = RandomStringUtils.randomNumeric(3); + private static final String PRIMARY_GROUP_ID = RandomStringUtils.randomNumeric(2); + private static final List GROUP_NAMES = new ArrayList(Arrays.asList(new String[] {RandomStringUtils.randomAlphabetic(7), RandomStringUtils.randomAlphabetic(7), RandomStringUtils.randomAlphabetic(7)})); + private static final List GROUP_IDS = new ArrayList(Arrays.asList(new String[] {RandomStringUtils.randomNumeric(2), RandomStringUtils.randomNumeric(2), RandomStringUtils.randomNumeric(2)})); + + private static final UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); + + private Environment environment = new Environment(); + private Economy economy = mock(Economy.class); + private PermissionHandler permissionHandler = mock(PermissionHandler.class); + private Configuration configuration = mock(Configuration.class); + private CommunityBridge plugin = mock(CommunityBridge.class); + private Log log = mock(Log.class); + private Player player = mock(Player.class); + private MoneyDao money = mock(MoneyDao.class); + private WebApplication webApplication = mock(WebApplication.class); + + private YamlConfiguration playerData = mock(YamlConfiguration.class); + private File playerFile = mock(File.class); + private File oldPlayerFile = mock(File.class); + + @InjectMocks + private PlayerState state = new PlayerState(); + + @Before + public void beforeEach() { + environment.setConfiguration(configuration); + environment.setEconomy(economy); + environment.setLog(log); + environment.setPermissionHandler(permissionHandler); + environment.setPlugin(plugin); + environment.setWebApplication(webApplication); + configuration.simpleSynchronizationGroupsTreatedAsPrimary = new ArrayList(); + configuration.simpleSynchronizationGroupsTreatedAsPrimary.add(PRIMARY_GROUP_NAME); + configuration.groupSynchronizationActive = true; + configuration.webappPrimaryGroupEnabled = true; + configuration.webappSecondaryGroupEnabled = true; + when(player.getUniqueId()).thenReturn(UUID); + when(player.getName()).thenReturn(PLAYER_NAME); + when(webApplication.getUserPrimaryGroupID(USER_ID)).thenReturn(PRIMARY_GROUP_ID); + when(webApplication.getUserSecondaryGroupIDs(USER_ID)).thenReturn(GROUP_IDS); + when(permissionHandler.supportsPrimaryGroups()).thenReturn(true); + when(permissionHandler.getPrimaryGroup(player)).thenReturn(PRIMARY_GROUP_NAME); + when(permissionHandler.getGroups(player)).thenReturn(GROUP_NAMES); + } + + @Test + public void generateSetsPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + + assertEquals(PRIMARY_GROUP_ID, state.getWebappPrimaryGroupID()); + } + + @Test + public void generateWhenGroupSynchronizationInactiveDoesNotSetPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = false; + state.generate(environment, player, USER_ID); + + assertEquals("", state.getWebappPrimaryGroupID()); + } + + @Test + public void generateWhenPrimaryGroupInactiveDoesNotSetPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = true; + configuration.webappPrimaryGroupEnabled = false; + state.generate(environment, player, USER_ID); + + assertEquals("", state.getWebappPrimaryGroupID()); + } + + @Test + public void generateSetsGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + for (String id : GROUP_IDS) + { + assertTrue(id + "missing", state.getWebappGroupIDs().contains(id)); + } + } + + @Test + public void generateWhenGroupSynchronizationInactiveDoesNotSetGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = false; + state.generate(environment, player, USER_ID); + + assertTrue(state.getWebappGroupIDs().isEmpty()); + } + + @Test + public void generateWhenSecondaryGroupInactiveDoesNotSetGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = true; + configuration.webappSecondaryGroupEnabled = false; + state.generate(environment, player, USER_ID); + + assertTrue(state.getWebappGroupIDs().isEmpty()); + } + + @Test + public void generateSetsPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void generateWhenPrimaryGroupNotSupportedSetsPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + when(permissionHandler.supportsPrimaryGroups()).thenReturn(false); + GROUP_NAMES.add(PRIMARY_GROUP_NAME); + state.generate(environment, player, USER_ID); + assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void generateWhenPrimaryGroupNotSupportedSetsBlankOnNotFound() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + when(permissionHandler.supportsPrimaryGroups()).thenReturn(false); + state.generate(environment, player, USER_ID); + assertEquals("", state.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void generateWhenGroupSynchronizationInactiveDoesNotSetPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = false; + state.generate(environment, player, USER_ID); + + assertEquals("", state.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void generateSetsGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + + for (String group : GROUP_NAMES) + { + assertTrue(group + "missing", state.getPermissionsSystemGroupNames().contains(group)); + } + } + + @Test + public void generateWhenGroupSynchronizationInactiveDoesNotSetGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.groupSynchronizationActive = false; + state.generate(environment, player, USER_ID); + + assertTrue(state.getPermissionsSystemGroupNames().isEmpty()); + } + + @Test + public void generateSetsMinecraftWallet() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double wallet = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + + when(economy.getBalance(player)).thenReturn(wallet); + + state.generate(environment, player, USER_ID); + + assertEquals(wallet, state.getMinecraftWallet(), 0); + } + + @Test + public void generateSetsWebApplicationWallet() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double wallet = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + when(money.getBalance(environment, USER_ID)).thenReturn(wallet); + state.generate(environment, player, USER_ID); + + assertEquals(wallet, state.getWebApplicationWallet(), 0); + } + + @Test + public void copyNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + assertNotNull(copy); + } + + @Test + public void copyCopiesPrimaryGroupId() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + assertEquals(state.getWebappPrimaryGroupID(), copy.getWebappPrimaryGroupID()); + } + + @Test + public void copyCopiesGroupIds() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + assertEquals(state.getWebappGroupIDs(), copy.getWebappGroupIDs()); + } + + @Test + public void copyCopiesPrimaryGroupName() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + + assertEquals(state.getPermissionsSystemPrimaryGroupName(), copy.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void copyCopiesGroupNames() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + + assertEquals(state.getPermissionsSystemGroupNames(), copy.getPermissionsSystemGroupNames()); + } + + @Test + public void copyCopiesMinecraftMoney() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double wallet = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + + when(economy.getBalance(player)).thenReturn(wallet); + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + + assertEquals(wallet, copy.getMinecraftWallet(), 0); + } + + @Test + public void copyCopiesWebApplicationMoney() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double wallet = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + + when(money.getBalance(environment, USER_ID)).thenReturn(wallet); + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + + assertEquals(wallet, copy.getWebApplicationWallet(), 0); + } + + @Test + public void copyCopiesNewFile() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + state.generate(environment, player, USER_ID); + PlayerState copy = state.copy(); + + assertEquals(state.isIsNewFile(), copy.isIsNewFile()); + } + + @Test + public void saveSavesData() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double mcWallet = RandomUtils.nextDouble() + 1; + double wbWallet = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + + when(economy.getBalance(player)).thenReturn(mcWallet); + when(money.getBalance(environment, USER_ID)).thenReturn(wbWallet); + + state.generate(environment, player, USER_ID); + state.save(player, playerFile, environment.getLog()); + + verify(playerData).set("last-known-name", PLAYER_NAME); + verify(playerData).set("minecraft-money", mcWallet); + verify(playerData).set("web-application-money", wbWallet); + verify(playerData).set("permissions-system.primary-group-name", PRIMARY_GROUP_NAME); + verify(playerData).set("permissions-system.group-names", GROUP_NAMES); + verify(playerData).set("webapp.primary-group-id", PRIMARY_GROUP_ID); + verify(playerData).set("webapp.group-ids", GROUP_IDS); + verify(playerData).save(any(File.class)); + } + + @Test + public void saveHandlesIOException() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double money = RandomUtils.nextDouble() + 1; + configuration.economyEnabled = true; + configuration.walletEnabled = true; + + when(economy.getBalance(player)).thenReturn(money); + doNothing().when(playerData).set(anyString(), anyString()); + String exceptionMessage = RandomStringUtils.randomAlphabetic(18); + doThrow(new IOException(exceptionMessage)).when(playerData).save(any(File.class)); + + state.generate(environment, player, USER_ID); + state.save(player, playerFile, environment.getLog()); + verify(log).severe("Exception while saving player state for " + player.getName() + ": " + exceptionMessage); + } + + @Test + public void loadHandlesNewFile() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + when(playerFile.exists()).thenReturn(false); + when(oldPlayerFile.exists()).thenReturn(false); + state.load(playerFile); + assertEquals(true, state.isIsNewFile()); + assertEquals("", state.getWebappPrimaryGroupID()); + assertTrue("Group name list should be empty", state.getPermissionsSystemGroupNames().isEmpty()); + assertTrue("Group id list should be empty", state.getWebappGroupIDs().isEmpty()); + assertEquals("", state.getPermissionsSystemPrimaryGroupName()); + } + + @Test + public void loadLoadsData() throws IOException, IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + double mcWallet = RandomUtils.nextDouble() + 1; + double waWallet = RandomUtils.nextDouble() + 1; + + when(playerFile.exists()).thenReturn(true); + when(oldPlayerFile.exists()).thenReturn(true); + PowerMockito.mockStatic(YamlConfiguration.class); + when(YamlConfiguration.loadConfiguration(playerFile)).thenReturn(playerData); + when(playerData.getDouble("minecraft-money", 0)).thenReturn(mcWallet); + when(playerData.getDouble("web-application-money", 0)).thenReturn(waWallet); + when(playerData.getStringList("permissions-system.group-names")).thenReturn(GROUP_NAMES); + when(playerData.getString("permissions-system.primary-group-name", "")).thenReturn(PRIMARY_GROUP_NAME); + when(playerData.getStringList("webapp.group-ids")).thenReturn(GROUP_IDS); + when(playerData.getString("webapp.primary-group-id", "")).thenReturn(PRIMARY_GROUP_ID); + state.load(playerFile); + + assertEquals(false, state.isIsNewFile()); + assertEquals(mcWallet, state.getMinecraftWallet(), 0); + assertEquals(waWallet, state.getWebApplicationWallet(), 0); + assertEquals(PRIMARY_GROUP_ID, state.getWebappPrimaryGroupID()); + assertEquals(PRIMARY_GROUP_NAME, state.getPermissionsSystemPrimaryGroupName()); + + for (String group : GROUP_NAMES) + { + assertTrue(group + " missing.", state.getPermissionsSystemGroupNames().contains(group)); + } + + for (String id : GROUP_IDS) + { + assertTrue(id + " missing.", state.getWebappGroupIDs().contains(id)); + } + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/PlayerSynchronizationDispatcherTest.java b/test/org/communitybridge/synchronization/PlayerSynchronizationDispatcherTest.java index 8978650..f4f7bd4 100644 --- a/test/org/communitybridge/synchronization/PlayerSynchronizationDispatcherTest.java +++ b/test/org/communitybridge/synchronization/PlayerSynchronizationDispatcherTest.java @@ -1,216 +1,216 @@ -package org.communitybridge.synchronization; - -import java.io.File; -import java.util.ArrayList; -import java.util.UUID; -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.math.RandomUtils; -import org.bukkit.entity.Player; -import org.communitybridge.linker.UserPlayerLinker; -import org.communitybridge.main.BukkitWrapper; -import org.communitybridge.main.CommunityBridge; -import org.communitybridge.main.Configuration; -import org.communitybridge.utility.Log; -import org.communitybridge.main.Environment; -import org.communitybridge.main.WebApplication; -import org.junit.Test; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.mockito.InOrder; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import static org.mockito.Mockito.*; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.MockGateway; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(CommunityBridge.class) -public class PlayerSynchronizationDispatcherTest -{ - private Environment environment = new Environment(); - private BukkitWrapper bukkit = mock(BukkitWrapper.class); - private CommunityBridge plugin = PowerMockito.mock(CommunityBridge.class); - private Configuration configuration = mock(Configuration.class); - private Log log = mock(Log.class); - private UserPlayerLinker userPlayerLinker = mock(UserPlayerLinker.class); - private WebApplication webApplication = mock(WebApplication.class); - - private PlayerState result = mock(PlayerState.class); - - private Player player = mock(Player.class); - private Player[] players = new Player[2]; - private static final String USER_ID = RandomStringUtils.randomAlphabetic(8); - private static final UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); - private File dataFolder = new File("/"); - - @Mock private File dataFile; - @Mock private ArrayList playerLocks; - @Mock private MoneySynchronizer moneySynchronizer; - - @InjectMocks - private PlayerSynchronizationDispatcher dispatcher = new PlayerSynchronizationDispatcher(); - - @Before - public void beforeEach() throws Exception - { - MockGateway.MOCK_STANDARD_METHODS = false; - environment.setBukkit(bukkit); - environment.setConfiguration(configuration); - environment.setLog(log); - environment.setPlugin(plugin); - environment.setUserPlayerLinker(userPlayerLinker); - environment.setWebApplication(webApplication); - - configuration.groupSynchronizationActive = true; - configuration.simpleSynchronizationGroupsTreatedAsPrimary = new ArrayList(); - configuration.statisticsEnabled = true; - configuration.useAchievements = true; - when(moneySynchronizer.isActive(environment)).thenReturn(true); - - players[0] = player; - when(bukkit.getOnlinePlayers()).thenReturn(players); - PowerMockito.when(plugin.getDataFolder()).thenReturn(dataFolder); - when(dataFile.exists()).thenReturn(true); - when(userPlayerLinker.getUserID(player)).thenReturn(USER_ID); - when(player.getUniqueId()).thenReturn(UUID); - when(webApplication.synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result); - when(moneySynchronizer.synchronize(eq(environment), any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result); - } - - @Test - public void synchronizeShouldLogStart() - { - dispatcher.synchronize(environment); - verify(log).finest("Running player synchronization."); - } - - @Test - public void synchronizeShouldLogEnd() - { - dispatcher.synchronize(environment); - verify(log).finest("Player synchronization complete."); - } - - @Test - public void synchronizeShouldSynchronizeGroups() - { - dispatcher.synchronize(environment); - verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeShouldSynchronizeForMultiplePlayers() - { - Player player2 = mock(Player.class); - players[1] = player2; - when(userPlayerLinker.getUserID(player2)).thenReturn(USER_ID); - when(player2.getUniqueId()).thenReturn(UUID); - dispatcher.synchronize(environment); - - verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - verify(webApplication).synchronizeGroups(eq(player2), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeWhenGroupSynchronizationInactiveShouldNotSynchronizeGroups() - { - configuration.groupSynchronizationActive = false; - dispatcher.synchronize(environment); - verify(webApplication, never()).synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeWhenUserIDIsNullShouldNotSynchronize() - { - configuration.groupSynchronizationActive = true; - when(userPlayerLinker.getUserID(player)).thenReturn(null); - dispatcher.synchronize(environment); - verify(webApplication, never()).synchronizeGroups(any(Player.class), isNull(String.class), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeWhenUserIDIsNullShouldNotAddPlayerLock() - { - configuration.groupSynchronizationActive = true; - when(userPlayerLinker.getUserID(player)).thenReturn(null); - dispatcher.synchronize(environment); - verify(playerLocks, never()).add(player); - } - - @Test - public void synchronizeShouldOnlySynchronizePlayerOnce() - { - when(playerLocks.contains(player)).thenReturn(true); - - dispatcher.synchronize(environment); - - verify(webApplication, never()).synchronizeGroups(eq(player), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeShouldAddPlayerToLock() - { - dispatcher.synchronize(environment); - InOrder inOrder = inOrder(playerLocks, webApplication); - inOrder.verify(playerLocks).add(player); - inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeShouldRemovePlayerFromLock() - { - dispatcher.synchronize(environment); - - InOrder inOrder = inOrder(webApplication, playerLocks); - inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - inOrder.verify(playerLocks).remove(player); - } - - - @Test - public void synchronizeShouldUpdateStatistics() - { - dispatcher.synchronize(environment); - verify(webApplication).updateStatistics(player, true); - } - - @Test - public void synchronizeWhenStatisticsInactiveShouldNotUpdateStatistics() - { - configuration.statisticsEnabled = false; - dispatcher.synchronize(environment); - verify(webApplication, never()).updateStatistics(player, true); - } - - @Test - public void synchronizeShouldRewardAchievements() - { - dispatcher.synchronize(environment); - verify(webApplication).rewardAchievements(player); - } - - @Test - public void synchronizeWhenAchievementsInactiveShouldNotRewardAchievements() - { - configuration.useAchievements = false; - dispatcher.synchronize(environment); - verify(webApplication, never()).rewardAchievements(player); - } - - @Test - public void synchronizeShouldSynchronizeMoney() - { - dispatcher.synchronize(environment); - verify(moneySynchronizer).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } - - @Test - public void synchronizeShouldNotSynchronizeMoney() - { - when(moneySynchronizer.isActive(environment)).thenReturn(false); - dispatcher.synchronize(environment); - verify(moneySynchronizer, never()).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); - } +package org.communitybridge.synchronization; + +import java.io.File; +import java.util.ArrayList; +import java.util.UUID; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.math.RandomUtils; +import org.bukkit.entity.Player; +import org.communitybridge.linker.UserPlayerLinker; +import org.communitybridge.main.BukkitWrapper; +import org.communitybridge.main.CommunityBridge; +import org.communitybridge.main.Configuration; +import org.communitybridge.utility.Log; +import org.communitybridge.main.Environment; +import org.communitybridge.main.WebApplication; +import org.junit.Test; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import static org.mockito.Mockito.*; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.MockGateway; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CommunityBridge.class) +public class PlayerSynchronizationDispatcherTest +{ + private Environment environment = new Environment(); + private BukkitWrapper bukkit = mock(BukkitWrapper.class); + private CommunityBridge plugin = PowerMockito.mock(CommunityBridge.class); + private Configuration configuration = mock(Configuration.class); + private Log log = mock(Log.class); + private UserPlayerLinker userPlayerLinker = mock(UserPlayerLinker.class); + private WebApplication webApplication = mock(WebApplication.class); + + private PlayerState result = mock(PlayerState.class); + + private Player player = mock(Player.class); + private Player[] players = new Player[2]; + private static final String USER_ID = RandomStringUtils.randomAlphabetic(8); + private static final UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()); + private File dataFolder = new File("/"); + + @Mock private File dataFile; + @Mock private ArrayList playerLocks; + @Mock private MoneySynchronizer moneySynchronizer; + + @InjectMocks + private PlayerSynchronizationDispatcher dispatcher = new PlayerSynchronizationDispatcher(); + + @Before + public void beforeEach() throws Exception + { + MockGateway.MOCK_STANDARD_METHODS = false; + environment.setBukkit(bukkit); + environment.setConfiguration(configuration); + environment.setLog(log); + environment.setPlugin(plugin); + environment.setUserPlayerLinker(userPlayerLinker); + environment.setWebApplication(webApplication); + + configuration.groupSynchronizationActive = true; + configuration.simpleSynchronizationGroupsTreatedAsPrimary = new ArrayList(); + configuration.statisticsEnabled = true; + configuration.useAchievements = true; + when(moneySynchronizer.isActive(environment)).thenReturn(true); + + players[0] = player; + when(bukkit.getOnlinePlayers()).thenReturn(players); + PowerMockito.when(plugin.getDataFolder()).thenReturn(dataFolder); + when(dataFile.exists()).thenReturn(true); + when(userPlayerLinker.getUserID(player)).thenReturn(USER_ID); + when(player.getUniqueId()).thenReturn(UUID); + when(webApplication.synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result); + when(moneySynchronizer.synchronize(eq(environment), any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result); + } + + @Test + public void synchronizeShouldLogStart() + { + dispatcher.synchronize(environment); + verify(log).finest("Running player synchronization."); + } + + @Test + public void synchronizeShouldLogEnd() + { + dispatcher.synchronize(environment); + verify(log).finest("Player synchronization complete."); + } + + @Test + public void synchronizeShouldSynchronizeGroups() + { + dispatcher.synchronize(environment); + verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeShouldSynchronizeForMultiplePlayers() + { + Player player2 = mock(Player.class); + players[1] = player2; + when(userPlayerLinker.getUserID(player2)).thenReturn(USER_ID); + when(player2.getUniqueId()).thenReturn(UUID); + dispatcher.synchronize(environment); + + verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + verify(webApplication).synchronizeGroups(eq(player2), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeWhenGroupSynchronizationInactiveShouldNotSynchronizeGroups() + { + configuration.groupSynchronizationActive = false; + dispatcher.synchronize(environment); + verify(webApplication, never()).synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeWhenUserIDIsNullShouldNotSynchronize() + { + configuration.groupSynchronizationActive = true; + when(userPlayerLinker.getUserID(player)).thenReturn(null); + dispatcher.synchronize(environment); + verify(webApplication, never()).synchronizeGroups(any(Player.class), isNull(String.class), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeWhenUserIDIsNullShouldNotAddPlayerLock() + { + configuration.groupSynchronizationActive = true; + when(userPlayerLinker.getUserID(player)).thenReturn(null); + dispatcher.synchronize(environment); + verify(playerLocks, never()).add(player); + } + + @Test + public void synchronizeShouldOnlySynchronizePlayerOnce() + { + when(playerLocks.contains(player)).thenReturn(true); + + dispatcher.synchronize(environment); + + verify(webApplication, never()).synchronizeGroups(eq(player), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeShouldAddPlayerToLock() + { + dispatcher.synchronize(environment); + InOrder inOrder = inOrder(playerLocks, webApplication); + inOrder.verify(playerLocks).add(player); + inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeShouldRemovePlayerFromLock() + { + dispatcher.synchronize(environment); + + InOrder inOrder = inOrder(webApplication, playerLocks); + inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + inOrder.verify(playerLocks).remove(player); + } + + + @Test + public void synchronizeShouldUpdateStatistics() + { + dispatcher.synchronize(environment); + verify(webApplication).updateStatistics(player, true); + } + + @Test + public void synchronizeWhenStatisticsInactiveShouldNotUpdateStatistics() + { + configuration.statisticsEnabled = false; + dispatcher.synchronize(environment); + verify(webApplication, never()).updateStatistics(player, true); + } + + @Test + public void synchronizeShouldRewardAchievements() + { + dispatcher.synchronize(environment); + verify(webApplication).rewardAchievements(player); + } + + @Test + public void synchronizeWhenAchievementsInactiveShouldNotRewardAchievements() + { + configuration.useAchievements = false; + dispatcher.synchronize(environment); + verify(webApplication, never()).rewardAchievements(player); + } + + @Test + public void synchronizeShouldSynchronizeMoney() + { + dispatcher.synchronize(environment); + verify(moneySynchronizer).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } + + @Test + public void synchronizeShouldNotSynchronizeMoney() + { + when(moneySynchronizer.isActive(environment)).thenReturn(false); + dispatcher.synchronize(environment); + verify(moneySynchronizer, never()).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class)); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/SynchronizerTest.java b/test/org/communitybridge/synchronization/SynchronizerTest.java index 56e9905..04106e1 100644 --- a/test/org/communitybridge/synchronization/SynchronizerTest.java +++ b/test/org/communitybridge/synchronization/SynchronizerTest.java @@ -1,41 +1,41 @@ -package org.communitybridge.synchronization; - -import org.apache.commons.lang.RandomStringUtils; -import org.communitybridge.main.Environment; -import org.junit.Test; -import static org.junit.Assert.*; - -public class SynchronizerTest -{ - Synchronizer synchronizer = new Synchronizer(new Environment()); - - @Test - public void isValidDirectionReturnsTrueForTwo() - { - assertTrue(synchronizer.isValidDirection("two", "aaa")); - } - - @Test - public void isValidDirectionReturnsTrueForWebWhenWeb() - { - assertTrue(synchronizer.isValidDirection("web", "web")); - } - - @Test - public void isValidDirectionReturnsTrueForMinWhenMin() - { - assertTrue(synchronizer.isValidDirection("min", "min")); - } - - @Test - public void isValidDirectionReturnsFalseForSomethingElseAgainstMin() - { - assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "min")); - } - - @Test - public void isValidDirectionReturnsFalseForSomethingElseAgainstWeb() - { - assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "web")); - } +package org.communitybridge.synchronization; + +import org.apache.commons.lang.RandomStringUtils; +import org.communitybridge.main.Environment; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SynchronizerTest +{ + Synchronizer synchronizer = new Synchronizer(new Environment()); + + @Test + public void isValidDirectionReturnsTrueForTwo() + { + assertTrue(synchronizer.isValidDirection("two", "aaa")); + } + + @Test + public void isValidDirectionReturnsTrueForWebWhenWeb() + { + assertTrue(synchronizer.isValidDirection("web", "web")); + } + + @Test + public void isValidDirectionReturnsTrueForMinWhenMin() + { + assertTrue(synchronizer.isValidDirection("min", "min")); + } + + @Test + public void isValidDirectionReturnsFalseForSomethingElseAgainstMin() + { + assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "min")); + } + + @Test + public void isValidDirectionReturnsFalseForSomethingElseAgainstWeb() + { + assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "web")); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/dao/JunctionWebGroupDaoTest.java b/test/org/communitybridge/synchronization/dao/JunctionWebGroupDaoTest.java index d7d0c4c..02ca8f4 100644 --- a/test/org/communitybridge/synchronization/dao/JunctionWebGroupDaoTest.java +++ b/test/org/communitybridge/synchronization/dao/JunctionWebGroupDaoTest.java @@ -1,247 +1,247 @@ -package org.communitybridge.synchronization.dao; - -import java.net.MalformedURLException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import org.apache.commons.lang.RandomStringUtils; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.SQL; -import org.communitybridge.utility.Log; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import static org.mockito.Mockito.*; - -public class JunctionWebGroupDaoTest -{ - private final String USER_ID = RandomStringUtils.randomNumeric(2); - private String group1 = RandomStringUtils.randomNumeric(2); - private String group2 = RandomStringUtils.randomNumeric(2); - private String groups; - private WebGroupDao webGroupDao; - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private Log log = mock(Log.class); - private SQL sql = mock(SQL.class); - private ResultSet result = mock(ResultSet.class); - - @Before - public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - environment.setConfiguration(configuration); - environment.setLog(log); - environment.setSql(sql); - DaoTestsHelper.setupConfiguration(configuration); - webGroupDao = new JunctionWebGroupDao(environment); - - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.next()).thenReturn(true, false); - when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); - } - - @Test - public void addGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " - + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`) " - + "VALUES ('" + USER_ID + "', '" + group1 +"')"; - doNothing().when(sql).insertQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).insertQuery(query); - } - - @Test - public void addGroupUsesCorrectQueryWithOneAdditionalColumn() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String additionalColumn = RandomStringUtils.randomAlphabetic(7); - String additionalValue = RandomStringUtils.randomAlphanumeric(7); - configuration.webappSecondaryAdditionalColumns.put(additionalColumn, additionalValue); - String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " - + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`, `" + additionalColumn + "`) " - + "VALUES ('" + USER_ID + "', '" + group1 + "', '" + additionalValue + "')"; - doNothing().when(sql).insertQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).insertQuery(query); - } - - @Test - public void addGroupUsesCorrectQueryWithTwoAdditionalColumns() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String additionalColumn = RandomStringUtils.randomAlphabetic(3); - String additionalValue = RandomStringUtils.randomAlphanumeric(7); - String additionalColumn2 = RandomStringUtils.randomAlphabetic(4); - String additionalValue2 = RandomStringUtils.randomAlphanumeric(9); - configuration.webappSecondaryAdditionalColumns.put(additionalColumn, additionalValue); - configuration.webappSecondaryAdditionalColumns.put(additionalColumn2, additionalValue2); - String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " - + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`, `" + additionalColumn + "`, `" + additionalColumn2 + "`) " - + "VALUES ('" + USER_ID + "', '" + group1 + "', '" + additionalValue + "', '" + additionalValue2 + "')"; - doNothing().when(sql).insertQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).insertQuery(query); - } - - @Test - public void removeGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` " - + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + USER_ID + "' " - + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + group1 + "' "; - - doNothing().when(sql).deleteQuery(query); - webGroupDao.removeUserFromGroup(USER_ID, group1); - verify(sql).deleteQuery(query); - } - - @Test - public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(false); - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); - } - - @Test - public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - group1 = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - group1 = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - } - - @Test - public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1, group2); - when(result.next()).thenReturn(true, true, false); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1 + " ", group2); - when(result.next()).thenReturn(true, true, false); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" ", group2); - when(result.next()).thenReturn(true, true, false); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); - } - - @Test - public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(result.next()).thenReturn(false); - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = RandomStringUtils.randomNumeric(2); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); - assertEquals(1, secondaryGroups.size()); - assertEquals(USER_ID, secondaryGroups.get(0)); - } - - @Test - public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String userID2 = RandomStringUtils.randomNumeric(2); - groups = group1 + "," + group2; - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(USER_ID)); - assertTrue(secondaryGroups.contains(userID2)); - } +package org.communitybridge.synchronization.dao; + +import java.net.MalformedURLException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import org.apache.commons.lang.RandomStringUtils; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.SQL; +import org.communitybridge.utility.Log; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import static org.mockito.Mockito.*; + +public class JunctionWebGroupDaoTest +{ + private final String USER_ID = RandomStringUtils.randomNumeric(2); + private String group1 = RandomStringUtils.randomNumeric(2); + private String group2 = RandomStringUtils.randomNumeric(2); + private String groups; + private WebGroupDao webGroupDao; + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private Log log = mock(Log.class); + private SQL sql = mock(SQL.class); + private ResultSet result = mock(ResultSet.class); + + @Before + public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + environment.setConfiguration(configuration); + environment.setLog(log); + environment.setSql(sql); + DaoTestsHelper.setupConfiguration(configuration); + webGroupDao = new JunctionWebGroupDao(environment); + + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.next()).thenReturn(true, false); + when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); + } + + @Test + public void addGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " + + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`) " + + "VALUES ('" + USER_ID + "', '" + group1 +"')"; + doNothing().when(sql).insertQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).insertQuery(query); + } + + @Test + public void addGroupUsesCorrectQueryWithOneAdditionalColumn() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String additionalColumn = RandomStringUtils.randomAlphabetic(7); + String additionalValue = RandomStringUtils.randomAlphanumeric(7); + configuration.webappSecondaryAdditionalColumns.put(additionalColumn, additionalValue); + String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " + + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`, `" + additionalColumn + "`) " + + "VALUES ('" + USER_ID + "', '" + group1 + "', '" + additionalValue + "')"; + doNothing().when(sql).insertQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).insertQuery(query); + } + + @Test + public void addGroupUsesCorrectQueryWithTwoAdditionalColumns() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String additionalColumn = RandomStringUtils.randomAlphabetic(3); + String additionalValue = RandomStringUtils.randomAlphanumeric(7); + String additionalColumn2 = RandomStringUtils.randomAlphabetic(4); + String additionalValue2 = RandomStringUtils.randomAlphanumeric(9); + configuration.webappSecondaryAdditionalColumns.put(additionalColumn, additionalValue); + configuration.webappSecondaryAdditionalColumns.put(additionalColumn2, additionalValue2); + String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " + + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`, `" + additionalColumn + "`, `" + additionalColumn2 + "`) " + + "VALUES ('" + USER_ID + "', '" + group1 + "', '" + additionalValue + "', '" + additionalValue2 + "')"; + doNothing().when(sql).insertQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).insertQuery(query); + } + + @Test + public void removeGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` " + + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + USER_ID + "' " + + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + group1 + "' "; + + doNothing().when(sql).deleteQuery(query); + webGroupDao.removeUserFromGroup(USER_ID, group1); + verify(sql).deleteQuery(query); + } + + @Test + public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(false); + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); + } + + @Test + public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + group1 = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + group1 = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + } + + @Test + public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1, group2); + when(result.next()).thenReturn(true, true, false); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1 + " ", group2); + when(result.next()).thenReturn(true, true, false); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" ", group2); + when(result.next()).thenReturn(true, true, false); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); + } + + @Test + public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(result.next()).thenReturn(false); + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = RandomStringUtils.randomNumeric(2); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); + assertEquals(1, secondaryGroups.size()); + assertEquals(USER_ID, secondaryGroups.get(0)); + } + + @Test + public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String userID2 = RandomStringUtils.randomNumeric(2); + groups = group1 + "," + group2; + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(USER_ID)); + assertTrue(secondaryGroups.contains(userID2)); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/dao/KeyValueWebGroupDaoTest.java b/test/org/communitybridge/synchronization/dao/KeyValueWebGroupDaoTest.java index 3fd711e..fb0e937 100644 --- a/test/org/communitybridge/synchronization/dao/KeyValueWebGroupDaoTest.java +++ b/test/org/communitybridge/synchronization/dao/KeyValueWebGroupDaoTest.java @@ -1,349 +1,349 @@ -package org.communitybridge.synchronization.dao; - -import java.net.MalformedURLException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang.RandomStringUtils; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.SQL; -import org.communitybridge.utility.Log; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import static org.mockito.Mockito.*; - -public class KeyValueWebGroupDaoTest -{ - private final String USER_ID = RandomStringUtils.randomNumeric(2); - private String group1 = RandomStringUtils.randomNumeric(2); - private String group2 = RandomStringUtils.randomNumeric(2); - private String group3 = RandomStringUtils.randomNumeric(2); - private String groups; - private KeyValueWebGroupDao webGroupDao; - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private Log log = mock(Log.class); - private SQL sql = mock(SQL.class); - private ResultSet result = mock(ResultSet.class); - - @Before - public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - environment.setConfiguration(configuration); - environment.setLog(log); - environment.setSql(sql); - DaoTestsHelper.setupConfiguration(configuration); - webGroupDao = new KeyValueWebGroupDao(environment); - - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.next()).thenReturn(true, false); - when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); - } - - @Test - public void addGroupUsesCorrectReadQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(false); - doNothing().when(sql).updateQuery(webGroupDao.getGroupIDInsertQuery(USER_ID, group1)); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).sqlQuery(query); - } - - @Test - public void addGroupUsesCorrectUpdateQueryWhenRowDoesNotExist() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(false); - query = webGroupDao.getGroupIDInsertQuery(USER_ID, group1); - doNothing().when(sql).insertQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).insertQuery(query); - } - - @Test - public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = group1; - List groupsAsList = new ArrayList(); - groupsAsList.add(group1); - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); - query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); - doNothing().when(sql).updateQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).updateQuery(query); - } - - @Test - public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsEmpty() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = group1; - List groupsAsList = new ArrayList(); - groupsAsList.add(group1); - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(""); - query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); - doNothing().when(sql).updateQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).updateQuery(query); - } - - @Test - public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsWhitespace() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = group1; - List groupsAsList = new ArrayList(); - groupsAsList.add(group1); - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" "); - query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); - doNothing().when(sql).updateQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).updateQuery(query); - } - - @Test - public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsOccupied() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = group1; - List groupsAsList = new ArrayList(); - groupsAsList.add(group2); - groupsAsList.add(group1); - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group2); - query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); - doNothing().when(sql).updateQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).updateQuery(query); - } - - @Test - public void removeGroupUsesCorrectReadQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(false); - webGroupDao.removeUserFromGroup(USER_ID, group1); - verify(sql).sqlQuery(query); - } - - @Test - public void removeGroupHandlesNoResultOnRead() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); - when(sql.sqlQuery(query)).thenReturn(result); - when(result.next()).thenReturn(false); - webGroupDao.removeUserFromGroup(USER_ID, group1); - verify(sql).sqlQuery(query); - verifyNoMoreInteractions(sql); - } - - @Test - public void removeGroupUsesCorrectUpdateCallRemovingOneOfNone() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - testRemoveGroupUpdateQuery("", ""); - } - - @Test - public void removeGroupUsesCorrectUpdateCallRemovingOneOfOne() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - testRemoveGroupUpdateQuery(group1, ""); - } - - @Test - public void removeGroupUsesCorrectUpdateCallRemovingOneOfPair() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - testRemoveGroupUpdateQuery(group1 + "," + group2, group2); - } - - @Test - public void removeGroupUsesCorrectUpdateCallRemovingOneOfThree() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - testRemoveGroupUpdateQuery(group1 + "," + group2 + "," + group3, group2 + "," + group3); - } - - private void testRemoveGroupUpdateQuery(String before, String after) throws SQLException, IllegalAccessException, MalformedURLException, InstantiationException - { - when(sql.sqlQuery(webGroupDao.getSecondaryGroupReadQuery(USER_ID))).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(before); - String query = getRemoveGroupUpdateQuery(after); - doNothing().when(sql).updateQuery(query); - webGroupDao.removeUserFromGroup(USER_ID, group1); - verify(sql).updateQuery(query); - } - - private String getRemoveGroupUpdateQuery(String after) - { - return "UPDATE `" + configuration.webappSecondaryGroupTable + "` " - + "SET `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + after + "' " - + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + USER_ID + "' " - + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "'"; - } - - @Test - public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(false); - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); - } - - @Test - public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = RandomStringUtils.randomNumeric(2); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertEquals(groups, secondaryGroups.get(0)); - } - - @Test - public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = group1 + "," + group2; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = group1 + " , " + group2; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = " , " + group2; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); - } - - @Test - public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(result.next()).thenReturn(false); - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = RandomStringUtils.randomNumeric(2); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); - assertEquals(1, secondaryGroups.size()); - assertEquals(USER_ID, secondaryGroups.get(0)); - } - - @Test - public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String userID2 = RandomStringUtils.randomNumeric(2); - groups = group1 + "," + group2; - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(USER_ID)); - assertTrue(secondaryGroups.contains(userID2)); - } +package org.communitybridge.synchronization.dao; + +import java.net.MalformedURLException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.RandomStringUtils; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.SQL; +import org.communitybridge.utility.Log; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import static org.mockito.Mockito.*; + +public class KeyValueWebGroupDaoTest +{ + private final String USER_ID = RandomStringUtils.randomNumeric(2); + private String group1 = RandomStringUtils.randomNumeric(2); + private String group2 = RandomStringUtils.randomNumeric(2); + private String group3 = RandomStringUtils.randomNumeric(2); + private String groups; + private KeyValueWebGroupDao webGroupDao; + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private Log log = mock(Log.class); + private SQL sql = mock(SQL.class); + private ResultSet result = mock(ResultSet.class); + + @Before + public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + environment.setConfiguration(configuration); + environment.setLog(log); + environment.setSql(sql); + DaoTestsHelper.setupConfiguration(configuration); + webGroupDao = new KeyValueWebGroupDao(environment); + + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.next()).thenReturn(true, false); + when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); + } + + @Test + public void addGroupUsesCorrectReadQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(false); + doNothing().when(sql).updateQuery(webGroupDao.getGroupIDInsertQuery(USER_ID, group1)); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).sqlQuery(query); + } + + @Test + public void addGroupUsesCorrectUpdateQueryWhenRowDoesNotExist() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(false); + query = webGroupDao.getGroupIDInsertQuery(USER_ID, group1); + doNothing().when(sql).insertQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).insertQuery(query); + } + + @Test + public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = group1; + List groupsAsList = new ArrayList(); + groupsAsList.add(group1); + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); + query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); + doNothing().when(sql).updateQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).updateQuery(query); + } + + @Test + public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsEmpty() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = group1; + List groupsAsList = new ArrayList(); + groupsAsList.add(group1); + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(""); + query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); + doNothing().when(sql).updateQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).updateQuery(query); + } + + @Test + public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsWhitespace() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = group1; + List groupsAsList = new ArrayList(); + groupsAsList.add(group1); + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" "); + query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); + doNothing().when(sql).updateQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).updateQuery(query); + } + + @Test + public void addGroupUsesCorrectUpdateQueryWhenRowExistsButIsOccupied() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = group1; + List groupsAsList = new ArrayList(); + groupsAsList.add(group2); + groupsAsList.add(group1); + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group2); + query = webGroupDao.getGroupIDsUpdateQuery(groupsAsList, USER_ID); + doNothing().when(sql).updateQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).updateQuery(query); + } + + @Test + public void removeGroupUsesCorrectReadQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(false); + webGroupDao.removeUserFromGroup(USER_ID, group1); + verify(sql).sqlQuery(query); + } + + @Test + public void removeGroupHandlesNoResultOnRead() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = webGroupDao.getSecondaryGroupReadQuery(USER_ID); + when(sql.sqlQuery(query)).thenReturn(result); + when(result.next()).thenReturn(false); + webGroupDao.removeUserFromGroup(USER_ID, group1); + verify(sql).sqlQuery(query); + verifyNoMoreInteractions(sql); + } + + @Test + public void removeGroupUsesCorrectUpdateCallRemovingOneOfNone() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + testRemoveGroupUpdateQuery("", ""); + } + + @Test + public void removeGroupUsesCorrectUpdateCallRemovingOneOfOne() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + testRemoveGroupUpdateQuery(group1, ""); + } + + @Test + public void removeGroupUsesCorrectUpdateCallRemovingOneOfPair() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + testRemoveGroupUpdateQuery(group1 + "," + group2, group2); + } + + @Test + public void removeGroupUsesCorrectUpdateCallRemovingOneOfThree() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + testRemoveGroupUpdateQuery(group1 + "," + group2 + "," + group3, group2 + "," + group3); + } + + private void testRemoveGroupUpdateQuery(String before, String after) throws SQLException, IllegalAccessException, MalformedURLException, InstantiationException + { + when(sql.sqlQuery(webGroupDao.getSecondaryGroupReadQuery(USER_ID))).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(before); + String query = getRemoveGroupUpdateQuery(after); + doNothing().when(sql).updateQuery(query); + webGroupDao.removeUserFromGroup(USER_ID, group1); + verify(sql).updateQuery(query); + } + + private String getRemoveGroupUpdateQuery(String after) + { + return "UPDATE `" + configuration.webappSecondaryGroupTable + "` " + + "SET `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + after + "' " + + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + USER_ID + "' " + + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "'"; + } + + @Test + public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(false); + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); + } + + @Test + public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = RandomStringUtils.randomNumeric(2); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertEquals(groups, secondaryGroups.get(0)); + } + + @Test + public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = group1 + "," + group2; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = group1 + " , " + group2; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = " , " + group2; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); + } + + @Test + public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(result.next()).thenReturn(false); + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = RandomStringUtils.randomNumeric(2); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); + assertEquals(1, secondaryGroups.size()); + assertEquals(USER_ID, secondaryGroups.get(0)); + } + + @Test + public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String userID2 = RandomStringUtils.randomNumeric(2); + groups = group1 + "," + group2; + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(USER_ID)); + assertTrue(secondaryGroups.contains(userID2)); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/dao/MoneyDaoTest.java b/test/org/communitybridge/synchronization/dao/MoneyDaoTest.java index 2b538cf..04f0be1 100644 --- a/test/org/communitybridge/synchronization/dao/MoneyDaoTest.java +++ b/test/org/communitybridge/synchronization/dao/MoneyDaoTest.java @@ -1,124 +1,124 @@ -package org.communitybridge.synchronization.dao; - -import java.net.MalformedURLException; -import java.sql.ResultSet; -import java.sql.SQLException; -import org.apache.commons.lang.math.RandomUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.SQL; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MoneyDaoTest -{ - MoneyDao dao = new MoneyDao(); - private final Environment environment = new Environment(); - private final Configuration configuration = mock(Configuration.class); - private final SQL sql = mock(SQL.class); - private final ResultSet result = mock(ResultSet.class); - private String KEYED_QUERY; - private String KEYLESS_QUERY; - private final String USER_ID = RandomStringUtils.randomAlphabetic(2); - private final double KEYLESS_BALANCE = RandomUtils.nextDouble(); - private final double KEYED_BALANCE = RandomUtils.nextDouble(); - - @Before - public void beforeEach() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletValueColumn = RandomStringUtils.randomAlphabetic(13); - configuration.walletTableName = RandomStringUtils.randomAlphabetic(10); - configuration.walletKeyColumn = RandomStringUtils.randomAlphabetic(9); - configuration.walletUserIDColumn = RandomStringUtils.randomAlphabetic(8); - configuration.walletColumnOrKey = RandomStringUtils.randomAlphabetic(7); - - environment.setConfiguration(configuration); - environment.setSql(sql); - KEYED_QUERY = "SELECT `" + configuration.walletValueColumn + "` " - + "FROM `" + configuration.walletTableName + "` " - + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "' " - + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'"; - KEYLESS_QUERY = "SELECT `" + configuration.walletColumnOrKey + "` " - + "FROM `" + configuration.walletTableName + "` " - + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'"; - - when(sql.sqlQuery(KEYED_QUERY)).thenReturn(result); - when(sql.sqlQuery(KEYLESS_QUERY)).thenReturn(result); - when(result.next()).thenReturn(true); - when(result.getDouble(configuration.walletValueColumn)).thenReturn(KEYED_BALANCE); - when(result.getDouble(configuration.walletColumnOrKey)).thenReturn(KEYLESS_BALANCE); - } - - @Test - public void getBalanceNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - Assert.assertNotNull(dao.getBalance(environment, USER_ID)); - } - - @Test - public void getBalanceKeylessWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletUsesKey = false; - when(result.next()).thenReturn(false); - Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0); - } - - @Test - public void getBalanceKeylessReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletUsesKey = false; - Assert.assertEquals(KEYLESS_BALANCE, dao.getBalance(environment, USER_ID), 0.0); - } - - @Test - public void getBalanceUsesKeyNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletUsesKey = true; - Assert.assertNotNull(dao.getBalance(environment, USER_ID)); - } - - @Test - public void getBalanceKeyedWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletUsesKey = true; - when(result.next()).thenReturn(false); - Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0); - } - - @Test - public void getBalanceUsesKeyReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - configuration.walletUsesKey = true; - Assert.assertEquals(KEYED_BALANCE, dao.getBalance(environment, USER_ID), 0.0); - } - - @Test - public void setBalanceKeylessSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - Double balance = RandomUtils.nextDouble(); - String query = "UPDATE `" + configuration.walletTableName + "` " - + "SET `" + configuration.walletColumnOrKey + "` = '" + balance.toString() + "' " - + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'"; - configuration.walletUsesKey = false; - dao.setBalance(environment, USER_ID, balance); - Mockito.verify(sql).updateQuery(query); - } - - @Test - public void setBalanceKeyedSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException - { - Double balance = RandomUtils.nextDouble(); - String query = "UPDATE `" + configuration.walletTableName + "` " - + "SET `" + configuration.walletValueColumn + "` = '" + balance.toString() + "' " - + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'" - + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'"; - configuration.walletUsesKey = true; - dao.setBalance(environment, USER_ID, balance); - Mockito.verify(sql).updateQuery(query); - } +package org.communitybridge.synchronization.dao; + +import java.net.MalformedURLException; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.SQL; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MoneyDaoTest +{ + MoneyDao dao = new MoneyDao(); + private final Environment environment = new Environment(); + private final Configuration configuration = mock(Configuration.class); + private final SQL sql = mock(SQL.class); + private final ResultSet result = mock(ResultSet.class); + private String KEYED_QUERY; + private String KEYLESS_QUERY; + private final String USER_ID = RandomStringUtils.randomAlphabetic(2); + private final double KEYLESS_BALANCE = RandomUtils.nextDouble(); + private final double KEYED_BALANCE = RandomUtils.nextDouble(); + + @Before + public void beforeEach() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletValueColumn = RandomStringUtils.randomAlphabetic(13); + configuration.walletTableName = RandomStringUtils.randomAlphabetic(10); + configuration.walletKeyColumn = RandomStringUtils.randomAlphabetic(9); + configuration.walletUserIDColumn = RandomStringUtils.randomAlphabetic(8); + configuration.walletColumnOrKey = RandomStringUtils.randomAlphabetic(7); + + environment.setConfiguration(configuration); + environment.setSql(sql); + KEYED_QUERY = "SELECT `" + configuration.walletValueColumn + "` " + + "FROM `" + configuration.walletTableName + "` " + + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "' " + + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'"; + KEYLESS_QUERY = "SELECT `" + configuration.walletColumnOrKey + "` " + + "FROM `" + configuration.walletTableName + "` " + + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'"; + + when(sql.sqlQuery(KEYED_QUERY)).thenReturn(result); + when(sql.sqlQuery(KEYLESS_QUERY)).thenReturn(result); + when(result.next()).thenReturn(true); + when(result.getDouble(configuration.walletValueColumn)).thenReturn(KEYED_BALANCE); + when(result.getDouble(configuration.walletColumnOrKey)).thenReturn(KEYLESS_BALANCE); + } + + @Test + public void getBalanceNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + Assert.assertNotNull(dao.getBalance(environment, USER_ID)); + } + + @Test + public void getBalanceKeylessWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletUsesKey = false; + when(result.next()).thenReturn(false); + Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0); + } + + @Test + public void getBalanceKeylessReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletUsesKey = false; + Assert.assertEquals(KEYLESS_BALANCE, dao.getBalance(environment, USER_ID), 0.0); + } + + @Test + public void getBalanceUsesKeyNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletUsesKey = true; + Assert.assertNotNull(dao.getBalance(environment, USER_ID)); + } + + @Test + public void getBalanceKeyedWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletUsesKey = true; + when(result.next()).thenReturn(false); + Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0); + } + + @Test + public void getBalanceUsesKeyReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + configuration.walletUsesKey = true; + Assert.assertEquals(KEYED_BALANCE, dao.getBalance(environment, USER_ID), 0.0); + } + + @Test + public void setBalanceKeylessSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + Double balance = RandomUtils.nextDouble(); + String query = "UPDATE `" + configuration.walletTableName + "` " + + "SET `" + configuration.walletColumnOrKey + "` = '" + balance.toString() + "' " + + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'"; + configuration.walletUsesKey = false; + dao.setBalance(environment, USER_ID, balance); + Mockito.verify(sql).updateQuery(query); + } + + @Test + public void setBalanceKeyedSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException + { + Double balance = RandomUtils.nextDouble(); + String query = "UPDATE `" + configuration.walletTableName + "` " + + "SET `" + configuration.walletValueColumn + "` = '" + balance.toString() + "' " + + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'" + + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'"; + configuration.walletUsesKey = true; + dao.setBalance(environment, USER_ID, balance); + Mockito.verify(sql).updateQuery(query); + } } \ No newline at end of file diff --git a/test/org/communitybridge/synchronization/dao/MultipleKeyValueWebGroupDaoTest.java b/test/org/communitybridge/synchronization/dao/MultipleKeyValueWebGroupDaoTest.java index 6c4d618..fa7317b 100644 --- a/test/org/communitybridge/synchronization/dao/MultipleKeyValueWebGroupDaoTest.java +++ b/test/org/communitybridge/synchronization/dao/MultipleKeyValueWebGroupDaoTest.java @@ -1,218 +1,218 @@ -package org.communitybridge.synchronization.dao; - -import java.net.MalformedURLException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import org.apache.commons.lang.RandomStringUtils; -import org.communitybridge.main.Configuration; -import org.communitybridge.main.Environment; -import org.communitybridge.main.SQL; -import org.communitybridge.utility.Log; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import static org.mockito.Mockito.*; - -public class MultipleKeyValueWebGroupDaoTest -{ - private final String USER_ID = RandomStringUtils.randomNumeric(2); - private String group1 = RandomStringUtils.randomNumeric(2); - private String group2 = RandomStringUtils.randomNumeric(2); - private String groups; - private WebGroupDao webGroupDao; - private Environment environment = new Environment(); - private Configuration configuration = mock(Configuration.class); - private Log log = mock(Log.class); - private SQL sql = mock(SQL.class); - private ResultSet result = mock(ResultSet.class); - - @Before - public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - environment.setConfiguration(configuration); - environment.setLog(log); - environment.setSql(sql); - DaoTestsHelper.setupConfiguration(configuration); - webGroupDao = new MultipleKeyValueWebGroupDao(environment); - - when(sql.sqlQuery(anyString())).thenReturn(result); - when(result.next()).thenReturn(true, false); - when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); - } - - @Test - public void addGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " - + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupKeyColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`) " - + "VALUES ('" + USER_ID + "', '" + configuration.webappSecondaryGroupKeyName + "', '" + group1 + "')"; - doNothing().when(sql).insertQuery(query); - webGroupDao.addUserToGroup(USER_ID, group1, 0); - verify(sql).insertQuery(query); - } - - @Test - public void removeGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` " - + "WHERE `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' " - + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + group1 + "' "; - - doNothing().when(sql).deleteQuery(query); - webGroupDao.removeUserFromGroup(USER_ID, group1); - verify(sql).deleteQuery(query); - } - - @Test - public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(false); - assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); - } - - @Test - public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); - } - - @Test - public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - groups = RandomStringUtils.randomNumeric(2); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertEquals(groups, secondaryGroups.get(0)); - } - - @Test - public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1, group2); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1 + " ", group2 + " "); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group1)); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException - { - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" ", group2); - List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); - assertEquals(1, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(group2)); - } - - @Test - public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); - } - - @Test - public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - configuration.webappSecondaryGroupEnabled = false; - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - when(result.next()).thenReturn(false); - assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = ""; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = " "; - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(0, secondaryGroups.size()); - } - - @Test - public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - groups = RandomStringUtils.randomNumeric(2); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); - assertEquals(1, secondaryGroups.size()); - assertEquals(USER_ID, secondaryGroups.get(0)); - } - - @Test - public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException - { - String userID2 = RandomStringUtils.randomNumeric(2); - groups = group1 + "," + group2; - when(result.next()).thenReturn(true, true, false); - when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); - when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); - List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); - assertEquals(2, secondaryGroups.size()); - assertTrue(secondaryGroups.contains(USER_ID)); - assertTrue(secondaryGroups.contains(userID2)); - } +package org.communitybridge.synchronization.dao; + +import java.net.MalformedURLException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import org.apache.commons.lang.RandomStringUtils; +import org.communitybridge.main.Configuration; +import org.communitybridge.main.Environment; +import org.communitybridge.main.SQL; +import org.communitybridge.utility.Log; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Before; +import static org.mockito.Mockito.*; + +public class MultipleKeyValueWebGroupDaoTest +{ + private final String USER_ID = RandomStringUtils.randomNumeric(2); + private String group1 = RandomStringUtils.randomNumeric(2); + private String group2 = RandomStringUtils.randomNumeric(2); + private String groups; + private WebGroupDao webGroupDao; + private Environment environment = new Environment(); + private Configuration configuration = mock(Configuration.class); + private Log log = mock(Log.class); + private SQL sql = mock(SQL.class); + private ResultSet result = mock(ResultSet.class); + + @Before + public void setup() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + environment.setConfiguration(configuration); + environment.setLog(log); + environment.setSql(sql); + DaoTestsHelper.setupConfiguration(configuration); + webGroupDao = new MultipleKeyValueWebGroupDao(environment); + + when(sql.sqlQuery(anyString())).thenReturn(result); + when(result.next()).thenReturn(true, false); + when(result.getString(configuration.webappPrimaryGroupUserIDColumn)).thenReturn(USER_ID); + } + + @Test + public void addGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " + + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupKeyColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`) " + + "VALUES ('" + USER_ID + "', '" + configuration.webappSecondaryGroupKeyName + "', '" + group1 + "')"; + doNothing().when(sql).insertQuery(query); + webGroupDao.addUserToGroup(USER_ID, group1, 0); + verify(sql).insertQuery(query); + } + + @Test + public void removeGroupUsesCorrectQuery() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` " + + "WHERE `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' " + + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + group1 + "' "; + + doNothing().when(sql).deleteQuery(query); + webGroupDao.removeUserFromGroup(USER_ID, group1); + verify(sql).deleteQuery(query); + } + + @Test + public void getSecondaryGroupsShouldNeverReturnNull() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsShouldHandleNoResult() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(false); + assertNotNull(webGroupDao.getSecondaryGroupIDs(USER_ID)); + } + + @Test + public void getSecondaryGroupsWhenSecondaryDisableReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupIDs("").size()); + } + + @Test + public void getSecondaryGroupsWithEmptyStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithWhitespaceStringReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsWithNullReturnsEmptyList() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(null); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupsReturnsOneGroupID() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + groups = RandomStringUtils.randomNumeric(2); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertEquals(groups, secondaryGroups.get(0)); + } + + @Test + public void getSecondaryGroupsReturnsTwoGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1, group2); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsTwoCleanGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(group1 + " ", group2 + " "); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group1)); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupsReturnsOnlyGroupIDs() throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException + { + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(" ", group2); + List secondaryGroups = webGroupDao.getSecondaryGroupIDs(USER_ID); + assertEquals(1, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(group2)); + } + + @Test + public void getSecondaryGroupUserIDsNeverReturnNull() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + assertNotNull(webGroupDao.getSecondaryGroupUserIDs(group1)); + } + + @Test + public void getSecondaryGroupUserIDsWhenSecondaryDisabledReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + configuration.webappSecondaryGroupEnabled = false; + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoQueryResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + when(result.next()).thenReturn(false); + assertEquals(0, webGroupDao.getSecondaryGroupUserIDs(group1).size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenNoGroupsResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = ""; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsWhenWhitespaceResultsReturnsEmptyList() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = " "; + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(0, secondaryGroups.size()); + } + + @Test + public void getSecondaryGroupUserIDsReturnsOneUserID() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + groups = RandomStringUtils.randomNumeric(2); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(groups); + assertEquals(1, secondaryGroups.size()); + assertEquals(USER_ID, secondaryGroups.get(0)); + } + + @Test + public void getSecondaryGroupsReturnsTwoUserIDs() throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException + { + String userID2 = RandomStringUtils.randomNumeric(2); + groups = group1 + "," + group2; + when(result.next()).thenReturn(true, true, false); + when(result.getString(configuration.webappSecondaryGroupGroupIDColumn)).thenReturn(groups); + when(result.getString(configuration.webappSecondaryGroupUserIDColumn)).thenReturn(USER_ID, userID2); + List secondaryGroups = webGroupDao.getSecondaryGroupUserIDs(group1); + assertEquals(2, secondaryGroups.size()); + assertTrue(secondaryGroups.contains(USER_ID)); + assertTrue(secondaryGroups.contains(userID2)); + } } \ No newline at end of file diff --git a/test/org/communitybridge/utility/StringUtilitiesTest.java b/test/org/communitybridge/utility/StringUtilitiesTest.java index 18fd221..fdad7c9 100644 --- a/test/org/communitybridge/utility/StringUtilitiesTest.java +++ b/test/org/communitybridge/utility/StringUtilitiesTest.java @@ -1,377 +1,377 @@ -package org.communitybridge.utility; - -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; - -public class StringUtilitiesTest -{ - @Test - public void findFirstOfShouldThrowErrorOnEmptySearchCharacters() - { - try - { - StringUtilities.find_first_of("alphabet", ""); - fail("Should not search for an empty character list."); - } - catch (IllegalArgumentException exception) - { - assertNotNull(exception); - } - } - - @Test - public void findFirstOfShouldThrowErrorOnNullSearchCharacters() - { - try - { - StringUtilities.find_first_of("a", null); - fail("Should not search for an empty character list."); - } - catch (IllegalArgumentException exception) - { - assertNotNull(exception); - } - } - - @Test - public void findFirstOfShouldThrowErrorForNullSearchString() - { - try - { - StringUtilities.find_first_of(null, "s"); - fail("Should not search a null string."); - } - catch (IllegalArgumentException exception) - { - assertNotNull(exception); - } - } - - @Test - public void findFirstOfShouldReturnNotFoundForEmptySearchStringStartingAtFirstPosition() - { - assertEquals(StringUtilities.NOT_FOUND, StringUtilities.find_first_of("","a")); - } - - @Test - public void findFirstOfShouldReturnPositionForOneCharcterStartingAtFirstPosition() - { - // 0 indexed, so first position is 0. - assertEquals(0, StringUtilities.find_first_of("alphabet","a")); - } - - @Test - public void findFirstOfShouldReturnPositionEitherOfTwoCharactersStartingAtFirstPosition() - { - // 0 indexed, expected value is: 2 - assertEquals(2, StringUtilities.find_first_of("alphabet","ph")); - } - - @Test - public void findFirstOfShouldReturnPositionForOneCharacterStartingAtSecondPosition() - { - assertEquals(2,StringUtilities.find_first_of("abab", "pa", 1)); - } - - /** compareVersion section **/ - @Test - public void compareVersionWithEmptyArgumentsShouldReturnZero() - { - assertEquals(0, StringUtilities.compareVersion("", "")); - assertEquals(0, StringUtilities.compareVersion(null, "")); - assertEquals(0, StringUtilities.compareVersion("", null)); - assertEquals(0, StringUtilities.compareVersion(null, null)); - } - - @Test - public void compareVersionWithEmptyLeftArgumentShouldReturnNegativeOne() - { - assertEquals(-1, StringUtilities.compareVersion(null, "1-1.0")); - assertEquals(-1, StringUtilities.compareVersion("", "1-1.0")); - } - - @Test - public void compareVersionWithEmptyRightArgumentShouldReturnOne() - { - assertEquals(1, StringUtilities.compareVersion("1.0", null)); - assertEquals(1, StringUtilities.compareVersion("1.0", "")); - } - - @Test - public void compareVersionWithEqualSameLengthVersionsShouldReturnZero() - { - assertEquals(0, StringUtilities.compareVersion("1.2.3", "1.2.3")); - } - - @Test - public void compareVersionWithLeftLongerVersionsEqualShouldReturnZero() - { - assertEquals(0, StringUtilities.compareVersion("1.2.0", "1.2")); - } - - @Test - public void compareVersionWithRightLongerVersionsEqualShouldReturnZero() - { - assertEquals(0, StringUtilities.compareVersion("1.2", "1.2.0")); - } - - @Test - public void compareVersionWithLeftLongerLeftGreaterShouldReturnOne() - { - assertEquals(1, StringUtilities.compareVersion("1.2.3", "1.2")); - } - - @Test - public void compareVersionWithRightLongerRightGreaterShouldReturnNegativeOne() - { - assertEquals(-1, StringUtilities.compareVersion("1.2", "1.2.3")); - } - - @Test - public void compareVersionWithFirstPartLeftGreaterThanRightShouldReturnOne() - { - assertEquals(1, StringUtilities.compareVersion("2.1", "1.1")); - } - - @Test - public void compareVersionWithFirstPartRightGreaterThanRightShouldReturnNegativeOne() - { - assertEquals(-1, StringUtilities.compareVersion("1.1", "2.1")); - } - - @Test - public void compareVersionWithLastPartLeftGreaterThanRightShouldReturnOne() - { - assertEquals(1, StringUtilities.compareVersion("1.1", "1.0")); - } - - @Test - public void compareVersionWithLastPartRightGreaterThanLeftShouldReturnNegativeOne() - { - assertEquals(-1, StringUtilities.compareVersion("1.0", "1.1")); - } - - @Test - public void compareVersionWithMiddlePartLeftGreaterThanRightShouldReturnOne() - { - assertEquals(1, StringUtilities.compareVersion("1.2.0", "1.1.10")); - } - - @Test - public void compareVersionWithMiddlePartRightGreaterThanLeftShouldReturnNegativeOne() - { - assertEquals(-1, StringUtilities.compareVersion("1.0.15", "1.1.15")); - } - - @Test - public void compareVersionShouldSupportPeriodSeparators() - { - assertEquals(0, StringUtilities.compareVersion("1.0", "1.0")); - assertEquals(1, StringUtilities.compareVersion("1.1", "1.0")); - assertEquals(-1, StringUtilities.compareVersion("1.0", "1.1")); - } - - @Test - public void compareVersionShouldSupportUnseparatedVersions() - { - assertEquals(0, StringUtilities.compareVersion("1", "1")); - assertEquals(1, StringUtilities.compareVersion("11", "10")); - assertEquals(-1, StringUtilities.compareVersion("10", "11")); - } - - @Test - public void compareVersionShouldSupportHyphenSeparators() - { - assertEquals(0, StringUtilities.compareVersion("1-0", "1-0")); - assertEquals(1, StringUtilities.compareVersion("1-1", "1-0")); - assertEquals(-1, StringUtilities.compareVersion("1-0", "1-1")); - } - - @Test - public void compareVersionShouldSupportMixedSeparators() - { - assertEquals(0, StringUtilities.compareVersion("1-0.1", "1-0.1")); - assertEquals(0, StringUtilities.compareVersion("1.0.1", "1-0-1")); - assertEquals(1, StringUtilities.compareVersion("1-1.0", "1-0.0")); - assertEquals(-1, StringUtilities.compareVersion("1-0.0", "1-1.0")); - } - - @Test - public void compareVersionShouldStripOtherStuff() - { - assertEquals(0, StringUtilities.compareVersion("1-a0.b1", "1-g0.h1")); - assertEquals(0, StringUtilities.compareVersion("1.b0.a1", "1-e0-f1")); - assertEquals(1, StringUtilities.compareVersion("1-a1.b0", "1-c0.d0")); - assertEquals(-1, StringUtilities.compareVersion("1-c0.d0", "1-b1.a0")); - } - - /* - * joinStrings section. - */ - @Test - public void joinStringsShouldReturnEmptyStringWithEmptyInput() - { - List emptyList = new ArrayList(); - - String result = StringUtilities.joinStrings(emptyList, ""); - - assertTrue(result.equals("")); - } - - @Test - public void joinStringsShouldJoinTwoStrings() - { - String one = "oneString"; - String two = "oneString"; - List twoStrings = new ArrayList(); - twoStrings.add(one); - twoStrings.add(two); - - String result = StringUtilities.joinStrings(twoStrings, ""); - - assertTrue(result.equals(one + two)); - } - - @Test - public void joinStringsShouldJoinTwoStringsWithConjunction() - { - String one = "oneString"; - String two = "twoString"; - - List twoStrings = new ArrayList(); - twoStrings.add(one); - twoStrings.add(two); - - String result = StringUtilities.joinStrings(twoStrings, ", "); - - assertTrue(result.equals(one + ", " + two)); - } - - @Test - public void timeElapsedToStringShouldReturnZeroSecondsForZero() - { - String result = StringUtilities.timeElapsedToString(0); - - assertEquals("0 seconds", result); - } - - @Test - public void timeElapsedToStringShouldReturn1SecondFor1() - { - String result = StringUtilities.timeElapsedToString(1); - assertTrue(result.equals("1 second")); - } - - @Test - public void timeElapsedToStringShouldHandleMultipleSeconds() - { - String result = StringUtilities.timeElapsedToString(2); - - assertTrue(result.equals("2 seconds")); - } - - @Test - public void timeElapsedToStringShouldHandleOneMinuteNoSeconds() - { - String result = StringUtilities.timeElapsedToString(60); - - assertTrue(result.equals("1 minute")); - } - - @Test - public void timeElapsedToStringShouldHandleMultipleMinutesNoSeconds() - { - String result = StringUtilities.timeElapsedToString(120); - - assertTrue(result.equals("2 minutes")); - } - - @Test - public void timeElapsedToStringShouldHandleMinuteAndSecond() - { - String result = StringUtilities.timeElapsedToString(61); - - assertTrue(result.equals("1 minute, 1 second")); - } - - @Test - public void timeElapsedToStringShouldHandleMinuteAndSeconds() - { - String result = StringUtilities.timeElapsedToString(75); - - assertTrue(result.equals("1 minute, 15 seconds")); - } - - @Test - public void timeElapsedToStringShouldHandleMinutesAndSeconds() - { - String result = StringUtilities.timeElapsedToString(135); - - assertTrue(result.equals("2 minutes, 15 seconds")); - } - - @Test - public void timeElapsedToStringShouldHandle1Hour() - { - // 1 hour = 60m, 60 * 60 = 3600 seconds - String result = StringUtilities.timeElapsedToString(3600); - - assertTrue(result.equals("1 hour")); - } - - @Test - public void timeElapsedToStringShouldHandleHours() - { - // 2 hour = 120m, 120 * 60 = 7200 seconds - String result = StringUtilities.timeElapsedToString(7200); - - assertTrue(result.equals("2 hours")); - } - - @Test - public void timeElapsedToStringShouldHandleHourAndMinute() - { - // 1 hour = 60m, 60 * 60 = 3600 seconds, add 1 minute (60 seconds) - String result = StringUtilities.timeElapsedToString(3660); - - assertTrue(result.equals("1 hour, 1 minute")); - } - - @Test - public void timeElapsedToStringShouldHandle1Day() - { - // 60 seconds, 60 minutes, 24 hours = 86,400 - String result = StringUtilities.timeElapsedToString(86400); - - assertTrue(result.equals("1 day")); - } - - @Test - public void timeElapsedToStringShouldHandleDays() - { - // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days - String result = StringUtilities.timeElapsedToString(172800); - - assertTrue(result.equals("2 days")); - } - - @Test - public void timeElapsedToStringShouldHandleDaysAndSecond() - { - // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days - String result = StringUtilities.timeElapsedToString(172801); - - assertTrue(result.equals("2 days, 1 second")); - } - - @Test - public void timeElapsedToStringShouldHandleDaysAndHour() - { - // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days - String result = StringUtilities.timeElapsedToString(176400); - - assertTrue(result.equals("2 days, 1 hour")); - } +package org.communitybridge.utility; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class StringUtilitiesTest +{ + @Test + public void findFirstOfShouldThrowErrorOnEmptySearchCharacters() + { + try + { + StringUtilities.find_first_of("alphabet", ""); + fail("Should not search for an empty character list."); + } + catch (IllegalArgumentException exception) + { + assertNotNull(exception); + } + } + + @Test + public void findFirstOfShouldThrowErrorOnNullSearchCharacters() + { + try + { + StringUtilities.find_first_of("a", null); + fail("Should not search for an empty character list."); + } + catch (IllegalArgumentException exception) + { + assertNotNull(exception); + } + } + + @Test + public void findFirstOfShouldThrowErrorForNullSearchString() + { + try + { + StringUtilities.find_first_of(null, "s"); + fail("Should not search a null string."); + } + catch (IllegalArgumentException exception) + { + assertNotNull(exception); + } + } + + @Test + public void findFirstOfShouldReturnNotFoundForEmptySearchStringStartingAtFirstPosition() + { + assertEquals(StringUtilities.NOT_FOUND, StringUtilities.find_first_of("","a")); + } + + @Test + public void findFirstOfShouldReturnPositionForOneCharcterStartingAtFirstPosition() + { + // 0 indexed, so first position is 0. + assertEquals(0, StringUtilities.find_first_of("alphabet","a")); + } + + @Test + public void findFirstOfShouldReturnPositionEitherOfTwoCharactersStartingAtFirstPosition() + { + // 0 indexed, expected value is: 2 + assertEquals(2, StringUtilities.find_first_of("alphabet","ph")); + } + + @Test + public void findFirstOfShouldReturnPositionForOneCharacterStartingAtSecondPosition() + { + assertEquals(2,StringUtilities.find_first_of("abab", "pa", 1)); + } + + /** compareVersion section **/ + @Test + public void compareVersionWithEmptyArgumentsShouldReturnZero() + { + assertEquals(0, StringUtilities.compareVersion("", "")); + assertEquals(0, StringUtilities.compareVersion(null, "")); + assertEquals(0, StringUtilities.compareVersion("", null)); + assertEquals(0, StringUtilities.compareVersion(null, null)); + } + + @Test + public void compareVersionWithEmptyLeftArgumentShouldReturnNegativeOne() + { + assertEquals(-1, StringUtilities.compareVersion(null, "1-1.0")); + assertEquals(-1, StringUtilities.compareVersion("", "1-1.0")); + } + + @Test + public void compareVersionWithEmptyRightArgumentShouldReturnOne() + { + assertEquals(1, StringUtilities.compareVersion("1.0", null)); + assertEquals(1, StringUtilities.compareVersion("1.0", "")); + } + + @Test + public void compareVersionWithEqualSameLengthVersionsShouldReturnZero() + { + assertEquals(0, StringUtilities.compareVersion("1.2.3", "1.2.3")); + } + + @Test + public void compareVersionWithLeftLongerVersionsEqualShouldReturnZero() + { + assertEquals(0, StringUtilities.compareVersion("1.2.0", "1.2")); + } + + @Test + public void compareVersionWithRightLongerVersionsEqualShouldReturnZero() + { + assertEquals(0, StringUtilities.compareVersion("1.2", "1.2.0")); + } + + @Test + public void compareVersionWithLeftLongerLeftGreaterShouldReturnOne() + { + assertEquals(1, StringUtilities.compareVersion("1.2.3", "1.2")); + } + + @Test + public void compareVersionWithRightLongerRightGreaterShouldReturnNegativeOne() + { + assertEquals(-1, StringUtilities.compareVersion("1.2", "1.2.3")); + } + + @Test + public void compareVersionWithFirstPartLeftGreaterThanRightShouldReturnOne() + { + assertEquals(1, StringUtilities.compareVersion("2.1", "1.1")); + } + + @Test + public void compareVersionWithFirstPartRightGreaterThanRightShouldReturnNegativeOne() + { + assertEquals(-1, StringUtilities.compareVersion("1.1", "2.1")); + } + + @Test + public void compareVersionWithLastPartLeftGreaterThanRightShouldReturnOne() + { + assertEquals(1, StringUtilities.compareVersion("1.1", "1.0")); + } + + @Test + public void compareVersionWithLastPartRightGreaterThanLeftShouldReturnNegativeOne() + { + assertEquals(-1, StringUtilities.compareVersion("1.0", "1.1")); + } + + @Test + public void compareVersionWithMiddlePartLeftGreaterThanRightShouldReturnOne() + { + assertEquals(1, StringUtilities.compareVersion("1.2.0", "1.1.10")); + } + + @Test + public void compareVersionWithMiddlePartRightGreaterThanLeftShouldReturnNegativeOne() + { + assertEquals(-1, StringUtilities.compareVersion("1.0.15", "1.1.15")); + } + + @Test + public void compareVersionShouldSupportPeriodSeparators() + { + assertEquals(0, StringUtilities.compareVersion("1.0", "1.0")); + assertEquals(1, StringUtilities.compareVersion("1.1", "1.0")); + assertEquals(-1, StringUtilities.compareVersion("1.0", "1.1")); + } + + @Test + public void compareVersionShouldSupportUnseparatedVersions() + { + assertEquals(0, StringUtilities.compareVersion("1", "1")); + assertEquals(1, StringUtilities.compareVersion("11", "10")); + assertEquals(-1, StringUtilities.compareVersion("10", "11")); + } + + @Test + public void compareVersionShouldSupportHyphenSeparators() + { + assertEquals(0, StringUtilities.compareVersion("1-0", "1-0")); + assertEquals(1, StringUtilities.compareVersion("1-1", "1-0")); + assertEquals(-1, StringUtilities.compareVersion("1-0", "1-1")); + } + + @Test + public void compareVersionShouldSupportMixedSeparators() + { + assertEquals(0, StringUtilities.compareVersion("1-0.1", "1-0.1")); + assertEquals(0, StringUtilities.compareVersion("1.0.1", "1-0-1")); + assertEquals(1, StringUtilities.compareVersion("1-1.0", "1-0.0")); + assertEquals(-1, StringUtilities.compareVersion("1-0.0", "1-1.0")); + } + + @Test + public void compareVersionShouldStripOtherStuff() + { + assertEquals(0, StringUtilities.compareVersion("1-a0.b1", "1-g0.h1")); + assertEquals(0, StringUtilities.compareVersion("1.b0.a1", "1-e0-f1")); + assertEquals(1, StringUtilities.compareVersion("1-a1.b0", "1-c0.d0")); + assertEquals(-1, StringUtilities.compareVersion("1-c0.d0", "1-b1.a0")); + } + + /* + * joinStrings section. + */ + @Test + public void joinStringsShouldReturnEmptyStringWithEmptyInput() + { + List emptyList = new ArrayList(); + + String result = StringUtilities.joinStrings(emptyList, ""); + + assertTrue(result.equals("")); + } + + @Test + public void joinStringsShouldJoinTwoStrings() + { + String one = "oneString"; + String two = "oneString"; + List twoStrings = new ArrayList(); + twoStrings.add(one); + twoStrings.add(two); + + String result = StringUtilities.joinStrings(twoStrings, ""); + + assertTrue(result.equals(one + two)); + } + + @Test + public void joinStringsShouldJoinTwoStringsWithConjunction() + { + String one = "oneString"; + String two = "twoString"; + + List twoStrings = new ArrayList(); + twoStrings.add(one); + twoStrings.add(two); + + String result = StringUtilities.joinStrings(twoStrings, ", "); + + assertTrue(result.equals(one + ", " + two)); + } + + @Test + public void timeElapsedToStringShouldReturnZeroSecondsForZero() + { + String result = StringUtilities.timeElapsedToString(0); + + assertEquals("0 seconds", result); + } + + @Test + public void timeElapsedToStringShouldReturn1SecondFor1() + { + String result = StringUtilities.timeElapsedToString(1); + assertTrue(result.equals("1 second")); + } + + @Test + public void timeElapsedToStringShouldHandleMultipleSeconds() + { + String result = StringUtilities.timeElapsedToString(2); + + assertTrue(result.equals("2 seconds")); + } + + @Test + public void timeElapsedToStringShouldHandleOneMinuteNoSeconds() + { + String result = StringUtilities.timeElapsedToString(60); + + assertTrue(result.equals("1 minute")); + } + + @Test + public void timeElapsedToStringShouldHandleMultipleMinutesNoSeconds() + { + String result = StringUtilities.timeElapsedToString(120); + + assertTrue(result.equals("2 minutes")); + } + + @Test + public void timeElapsedToStringShouldHandleMinuteAndSecond() + { + String result = StringUtilities.timeElapsedToString(61); + + assertTrue(result.equals("1 minute, 1 second")); + } + + @Test + public void timeElapsedToStringShouldHandleMinuteAndSeconds() + { + String result = StringUtilities.timeElapsedToString(75); + + assertTrue(result.equals("1 minute, 15 seconds")); + } + + @Test + public void timeElapsedToStringShouldHandleMinutesAndSeconds() + { + String result = StringUtilities.timeElapsedToString(135); + + assertTrue(result.equals("2 minutes, 15 seconds")); + } + + @Test + public void timeElapsedToStringShouldHandle1Hour() + { + // 1 hour = 60m, 60 * 60 = 3600 seconds + String result = StringUtilities.timeElapsedToString(3600); + + assertTrue(result.equals("1 hour")); + } + + @Test + public void timeElapsedToStringShouldHandleHours() + { + // 2 hour = 120m, 120 * 60 = 7200 seconds + String result = StringUtilities.timeElapsedToString(7200); + + assertTrue(result.equals("2 hours")); + } + + @Test + public void timeElapsedToStringShouldHandleHourAndMinute() + { + // 1 hour = 60m, 60 * 60 = 3600 seconds, add 1 minute (60 seconds) + String result = StringUtilities.timeElapsedToString(3660); + + assertTrue(result.equals("1 hour, 1 minute")); + } + + @Test + public void timeElapsedToStringShouldHandle1Day() + { + // 60 seconds, 60 minutes, 24 hours = 86,400 + String result = StringUtilities.timeElapsedToString(86400); + + assertTrue(result.equals("1 day")); + } + + @Test + public void timeElapsedToStringShouldHandleDays() + { + // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days + String result = StringUtilities.timeElapsedToString(172800); + + assertTrue(result.equals("2 days")); + } + + @Test + public void timeElapsedToStringShouldHandleDaysAndSecond() + { + // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days + String result = StringUtilities.timeElapsedToString(172801); + + assertTrue(result.equals("2 days, 1 second")); + } + + @Test + public void timeElapsedToStringShouldHandleDaysAndHour() + { + // 60 seconds, 60 minutes, 24 hours = 86,400 * 2 makes two days + String result = StringUtilities.timeElapsedToString(176400); + + assertTrue(result.equals("2 days, 1 hour")); + } } \ No newline at end of file