├── .classpath
├── .gitignore
├── .project
├── .settings
├── org.eclipse.jdt.core.prefs
└── org.eclipse.m2e.core.prefs
├── README.md
├── build.number
├── build.xml
├── communitybridge.mf
├── documentation
└── developer
│ ├── communitybridgedeveloperdocumentation.kilepr
│ ├── developer documentation.pdf
│ ├── developer documentation.tex
│ ├── schemas
│ └── xenforo.sql
│ └── testing
│ ├── testScenarios.xlsx
│ └── testing-matrix.ods
├── manifest.mf
├── nbproject
├── coverage.properties
├── project.properties
└── project.xml
├── pom.xml
├── src
└── main
│ ├── java
│ └── org
│ │ └── communitybridge
│ │ ├── achievement
│ │ ├── Achievement.java
│ │ ├── AchievementAvatar.java
│ │ ├── AchievementGroup.java
│ │ ├── AchievementPostCount.java
│ │ ├── AchievementSectionPostCount.java
│ │ ├── PlayerAchievementState.java
│ │ └── SectionPostCount.java
│ │ ├── grouprules
│ │ ├── GroupRule.java
│ │ └── GroupRuleDirection.java
│ │ ├── linker
│ │ ├── UserIDDao.java
│ │ └── UserPlayerLinker.java
│ │ ├── main
│ │ ├── BukkitWrapper.java
│ │ ├── CBCommandExecutor.java
│ │ ├── CBMetrics.java
│ │ ├── CommunityBridge.java
│ │ ├── Configuration.java
│ │ ├── DatabaseHandler.java
│ │ ├── Environment.java
│ │ ├── Messages.java
│ │ ├── PlayerListener.java
│ │ ├── PlayerStatistics.java
│ │ ├── SQL.java
│ │ └── WebApplication.java
│ │ ├── permissionhandlers
│ │ ├── PermissionHandler.java
│ │ ├── PermissionHandlerBPermissions.java
│ │ ├── PermissionHandlerGroupManager.java
│ │ ├── PermissionHandlerPermissionsBukkit.java
│ │ ├── PermissionHandlerPermissionsEx.java
│ │ ├── PermissionHandlerVault.java
│ │ └── PermissionHandlerZPermissions.java
│ │ ├── synchronization
│ │ ├── MoneySynchronizer.java
│ │ ├── PlayerFileFetcher.java
│ │ ├── PlayerState.java
│ │ ├── PlayerSynchronizationDispatcher.java
│ │ ├── PlayerSynchronizer.java
│ │ ├── Synchronizer.java
│ │ ├── ban
│ │ │ ├── BanState.java
│ │ │ └── BanSynchronizer.java
│ │ └── dao
│ │ │ ├── JunctionWebGroupDao.java
│ │ │ ├── KeyValueWebGroupDao.java
│ │ │ ├── MoneyDao.java
│ │ │ ├── MultipleKeyValueWebGroupDao.java
│ │ │ ├── SingleWebGroupDao.java
│ │ │ └── WebGroupDao.java
│ │ └── utility
│ │ ├── Log.java
│ │ ├── MinecraftUtilities.java
│ │ └── StringUtilities.java
│ └── resources
│ ├── achievements.yml
│ ├── config.yml
│ ├── messages.yml
│ └── plugin.yml
├── test
└── org
│ └── communitybridge
│ ├── achievement
│ ├── AchievementAvatarTest.java
│ └── AchievementTest.java
│ ├── linker
│ ├── UserIDDaoTest.java
│ └── UserPlayerLinkerTest.java
│ ├── main
│ ├── .gitkeep
│ ├── PlayerStatisticsTest.java
│ └── WebApplicationTest.java
│ ├── permissionhandlers
│ └── PermissionHandlerTest.java
│ ├── synchronization
│ ├── MoneySynchronizerTest.java
│ ├── PlayerFileFetcherTest.java
│ ├── PlayerStateTest.java
│ ├── PlayerSynchronizationDispatcherTest.java
│ ├── SynchronizerTest.java
│ └── dao
│ │ ├── DaoTestsHelper.java
│ │ ├── JunctionWebGroupDaoTest.java
│ │ ├── KeyValueWebGroupDaoTest.java
│ │ ├── MoneyDaoTest.java
│ │ ├── MultipleKeyValueWebGroupDaoTest.java
│ │ ├── SingleWebGroupDaoTest.java
│ │ └── WebGroupDaoTest.java
│ └── utility
│ └── StringUtilitiesTest.java
└── website
└── images
├── CommunityBridgeLogo.png
└── buttons
├── code.png
├── credits.png
├── documentation.png
├── faq.png
├── help.png
└── permissions.png
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # NetBeans specific #
2 | nbproject/private/
3 | build/
4 | nbbuild/
5 | dist/
6 | nbdist/
7 | nbactions.xml
8 | nb-configuration.xml
9 |
10 | # Class Files #
11 | *.class
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | /nbproject/genfiles.properties
18 | /nbproject/build-impl.xml
19 | *.log
20 | *.aux
21 | /coverage
22 | /output
23 | *\.txt~
24 | *\.tex~
25 | *\.yml~
26 | *.synctex.gz
27 | /target/
28 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | CommunityBridge
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
3 | org.eclipse.jdt.core.compiler.compliance=1.7
4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
5 | org.eclipse.jdt.core.compiler.source=1.7
6 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | CommunityBridge
2 | ===============
3 |
4 | A Minecraft plugin for connecting your game to your website.
5 | Find the main page on BukkitDev: [CommunityBridge](http://dev.bukkit.org/bukkit-plugins/communitybridge-fm/)
6 |
7 | Help Translate!
8 | ---------------
9 | We're using Crowd-In to help us translate the messages into other languages at: [CommunityBridge on CrowdIn](http://crowdin.net/project/communitybridge)
10 |
--------------------------------------------------------------------------------
/build.number:
--------------------------------------------------------------------------------
1 | #Build Number for ANT. Do not edit!
2 | #Fri Aug 22 05:46:37 CDT 2014
3 | build.number=563
4 |
--------------------------------------------------------------------------------
/build.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Builds, tests, and runs the project CommunityBridge.
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/communitybridge.mf:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 |
3 |
--------------------------------------------------------------------------------
/documentation/developer/communitybridgedeveloperdocumentation.kilepr:
--------------------------------------------------------------------------------
1 | [General]
2 | bibliographyBackendAutoDetected=
3 | bibliographyBackendUserOverride=
4 | def_graphic_ext=eps
5 | img_extIsRegExp=false
6 | img_extensions=.eps .jpg .jpeg .png .pdf .ps .fig .gif
7 | kile_livePreviewEnabled=true
8 | kile_livePreviewStatusUserSpecified=false
9 | kile_livePreviewTool=LivePreview-PDFLaTeX
10 | kileprversion=2
11 | kileversion=2.9.60
12 | lastDocument=developer documentation.tex
13 | masterDocument=
14 | name=CommunityBridge Developer Documentation
15 | pkg_extIsRegExp=false
16 | pkg_extensions=.cls .sty .bbx .cbx .lbx
17 | src_extIsRegExp=false
18 | src_extensions=.tex .ltx .latex .dtx .ins
19 |
20 | [Tools]
21 | MakeIndex=
22 | QuickBuild=
23 |
24 | [document-settings,item:developer documentation.tex]
25 | Bookmarks=
26 | Encoding=UTF-8
27 | FoldedColumns=
28 | FoldedLines=
29 | Highlighting=LaTeX
30 | Indentation Mode=normal
31 | Mode=LaTeX
32 |
33 | [item:communitybridgedeveloperdocumentation.kilepr]
34 | archive=true
35 | column=1
36 | encoding=
37 | highlight=
38 | line=0
39 | mode=
40 | open=false
41 | order=-1
42 |
43 | [item:developer documentation.tex]
44 | archive=true
45 | column=15
46 | encoding=UTF-8
47 | highlight=LaTeX
48 | line=138
49 | mode=LaTeX
50 | open=true
51 | order=0
52 |
53 | [view-settings,view=0,item:developer documentation.tex]
54 | CursorColumn=15
55 | CursorLine=138
56 | JumpList=
57 | ViMarks=
58 |
--------------------------------------------------------------------------------
/documentation/developer/developer documentation.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/documentation/developer/developer documentation.pdf
--------------------------------------------------------------------------------
/documentation/developer/developer documentation.tex:
--------------------------------------------------------------------------------
1 | \documentclass[letterpaper,12pt]{article}
2 | \usepackage{amsfonts,amsmath,amssymb,fancyhdr,datetime}
3 |
4 | \usepackage[pdftex]{graphicx} % Great for including graphics
5 | \usepackage{wrapfig} % Wrapper for figures
6 |
7 | \usepackage{upquote}
8 | \usepackage{verbatim}
9 |
10 | % Relies on the datetime package to reformat the date the way I like.
11 | \newdateformat{iaindateformat}
12 | {\THEYEAR\hspace{.5em}\monthname[\THEMONTH]\hspace{.5em}\THEDAY}
13 | \iaindateformat
14 |
15 | \oddsidemargin 0.0in
16 | \evensidemargin 0.0in
17 | \textwidth 6.5in
18 |
19 | \topmargin 0.0in
20 | \headheight 1.0in
21 | \textheight 9.0in
22 |
23 | \renewcommand{\choose}[2]{\genfrac{(}{)}{0pt}{}{#1}{#2}}
24 |
25 | \renewcommand{\labelitemii}{$\circ$}
26 | \renewcommand{\thesection}{\arabic{section}}
27 |
28 | \pagestyle{fancy}
29 | \setlength\headheight{14.5pt}
30 | \renewcommand{\headrulewidth}{0.4pt}
31 | \renewcommand{\footrulewidth}{0.4pt}
32 | \fancyhead[R]{\bf Developer \thepage}
33 | \fancyhead[L]{\bf }
34 | \fancyfoot[R]{\bf Generated: \today\hspace{.5em}\currenttime}
35 | \fancyfoot[L]{\bf Community Bridge}
36 | \fancyfoot[C]{\bf \thepage}
37 | \setlength{\parindent}{0pt}
38 | \setlength{\parskip}{0.5em}
39 | \begin{document}
40 | \section{Overview}
41 | Throughout this document, the term ``web application'' is used. The web
42 | application can be any forum, CMS, blogging software, etc. that uses MySQL for
43 | its database.
44 |
45 | These are the major features of Community Bridge:
46 | \begin{enumerate}
47 | \item Minecraft player to web application user ``linking''.
48 | \item Group synchronization (currently a misnomer, since the
49 | ``synchronization'' is only one way)
50 | \item Recording statistical information about the players in web
51 | application custom fields.
52 | \item Kicking of players who are banned from the web application.
53 | \end{enumerate}
54 |
55 | The first of the features is essential, without it, none of the other
56 | features of the plugin would work. Given that the linking feature's
57 | importance, it is the first thing to evaluate when ensuring that
58 | CommunityBridge is operating correctly.
59 |
60 | \section{Database Handling}
61 | The config.yml section contains the hostname, port, database name, username,
62 | and password. It should correctly notify the server owner if the database
63 | information is incorrect or correct.
64 |
65 | \section{Linking Feature}
66 | For each of the following configurations, CB should:
67 | \begin{itemize}
68 | \item Recognize a player as not being registered, e.g., not present in the
69 | web application's database.
70 | \item Correctly identify a player as being registered--identifying the
71 | correct user.
72 | \item If kick-unregistered is turned on, kick unregistered players.
73 | \end{itemize}
74 |
75 | Possible Configurations (order of complexity):
76 | \begin{itemize}
77 | \item Minecraft playername and web application username are required to be
78 | the same. Required information: users table, user id column,
79 | username/playername column.
80 | \item Minecraft playername and web application username can be different;
81 | the Minecraft playername is in a separate column on the users table.
82 | Required information: users table, user id column, username/playername
83 | column.
84 | \item Minecraft playername and web application username can be different;
85 | the Minecraft playername is on a different table in its own column
86 | (frequently, this is because it is implemented through a custom profile
87 | field in the web application). Required information: tablename, user id
88 | column, username/playername column.
89 | \item Minecraft playername and web application username can be different;
90 | the Minecraft playername is on a different table that data is stored in
91 | the key-value format. Required information: tablename, user id column,
92 | key column, value column, data key name.
93 | \end{itemize}
94 |
95 | Fortunately, the overall result is the first three possible configurations
96 | require the same information. Only when the minecraft playername is stored in
97 | a key-value pair do we need different information.
98 |
99 | \section{Authentication}
100 | \begin{itemize}
101 | \item {\bf (NYI)} If authentication is off {\bf DO NOT} force
102 | authentication.
103 | \item {\bf (NYI)} If authentication is on, handle a valid authentication
104 | by...
105 | \item {\bf (NYI)} If authentication is on, respond to an failed
106 | authentication attempt by...
107 | \end{itemize}
108 |
109 | \section{Group Synchronization}
110 | Many web applications have a notion of a primary group. In fact, some only
111 | allow a member to have membership in a single group.
112 |
113 | On the other hand, permissions systems appear to rarely have a notion of a
114 | primary group. In addition, they frequently have per-world settings, so the
115 | world name must be included any operations with a permissions system.
116 |
117 | Possible configuration types for a ``primary'' group includes:
118 | \begin{itemize}
119 | \item A ``primary'' group\_id stored on a table alongside a user\_id.
120 | Required
121 | information includes: table\_name, user\_id column, group\_id column.
122 | \item A ``primary'' group\_id stored in a key-value pair. Required
123 | information
124 | includes: table\_name, user\_id column, key column, value column, data key
125 | name
126 | \end{itemize}
127 |
128 | Possible configuration types for ``secondary'' group includes:
129 | \begin{itemize}
130 | \item A list of ``secondary'' group IDs stored in a single field alongside a
131 | user\_id. Required information includes: table\_name, user\_id column,
132 | group\_ids column, group\_id delimiter.
133 | \item A junction table to create the many-to-many relationship between
134 | user IDs and group IDs. Required information includes: table\_name, user\_id
135 | column, group\_id column.
136 | \item A series of key-value pairs on a key-value table. Required information
137 | includes: table\_name, user\_id column, key volumn, value column, data key
138 | name
139 | \end{itemize}
140 | \end{document}
141 |
--------------------------------------------------------------------------------
/documentation/developer/testing/testScenarios.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/documentation/developer/testing/testScenarios.xlsx
--------------------------------------------------------------------------------
/documentation/developer/testing/testing-matrix.ods:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/documentation/developer/testing/testing-matrix.ods
--------------------------------------------------------------------------------
/manifest.mf:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | X-COMMENT: Main-Class will be added automatically by build
3 |
4 |
--------------------------------------------------------------------------------
/nbproject/coverage.properties:
--------------------------------------------------------------------------------
1 | #coverage viewer module properties for project
2 | #Fri Aug 01 21:36:09 CDT 2014
3 | coverage.activity=OFF
4 | project.type=java
5 | coverage.coverageFile=coverage/coverage.emma
6 | coverage.templateFile=coverage/template.emma
7 |
--------------------------------------------------------------------------------
/nbproject/project.properties:
--------------------------------------------------------------------------------
1 | annotation.processing.enabled=true
2 | annotation.processing.enabled.in.editor=true
3 | annotation.processing.processors.list=
4 | annotation.processing.run.all.processors=true
5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
6 | application.desc=
7 | application.title=CommunityBridge
8 | application.vendor=Feaelin (Iain E. Davis)
9 | build.classes.dir=${build.dir}/classes
10 | build.classes.excludes=**/*.java,**/*.form
11 | # This directory is removed when the project is cleaned:
12 | build.dir=build
13 | build.generated.dir=${build.dir}/generated
14 | build.generated.sources.dir=${build.dir}/generated-sources
15 | # Only compile against the classpath explicitly listed here:
16 | build.sysclasspath=ignore
17 | build.test.classes.dir=${build.dir}/test/classes
18 | build.test.results.dir=${build.dir}/test/results
19 | # Uncomment to specify the preferred debugger connection transport:
20 | #debug.transport=dt_socket
21 | debug.classpath=\
22 | ${run.classpath}
23 | debug.test.classpath=\
24 | ${run.test.classpath}
25 | # This directory is removed when the project is cleaned:
26 | dist.dir=dist
27 | dist.jar=${dist.dir}/CommunityBridge.jar
28 | dist.javadoc.dir=${dist.dir}/javadoc
29 | endorsed.classpath=
30 | excludes=org/communitybridge/grouprules/
31 | file.reference.bPermissions.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\bPermissions.jar
32 | file.reference.bukkit-1.7.9-R0.2.jar=..\\..\\0-Library Jars\\CraftBukkit\\bukkit-1.7.9-R0.2.jar
33 | file.reference.commons-lang3-3.3.1.jar=..\\..\\..\\Java\\0-Library Jars\\commons-lang3-3.3.1\\commons-lang3-3.3.1.jar
34 | file.reference.CommunityBridge-src=src
35 | file.reference.CommunityBridge-test=test
36 | file.reference.EssentialsGroupManager.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\EssentialsGroupManager.jar
37 | file.reference.hamcrest-core-1.3.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\hamcrest-core-1.3.jar
38 | file.reference.javassist.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\javassist.jar
39 | file.reference.junit-4.11.jar=..\\..\\..\\Java\\0-Library Jars\\JUnit\\junit-4.11.jar
40 | file.reference.mockito-all-1.9.5.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\mockito-all-1.9.5.jar
41 | file.reference.PermissionsBukkit-2.3.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsBukkit-2.3.jar
42 | file.reference.PermissionsEx.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\PermissionsEx.jar
43 | file.reference.powermock-mockito-1.5.4-full.jar=..\\..\\..\\Java\\0-Library Jars\\Mockito\\powermock-mockito-1.5.4-full.jar
44 | file.reference.Vault-1.4.1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\Vault-1.4.1.jar
45 | file.reference.zPermissions-1.3beta1.jar=..\\..\\0-Library Jars\\CraftBukkitPlugins\\zPermissions-1.3beta1.jar
46 | includes=**
47 | jar.archive.disabled=${jnlp.enabled}
48 | jar.compress=true
49 | jar.index=${jnlp.enabled}
50 | javac.classpath=\
51 | ${file.reference.bPermissions.jar}:\
52 | ${file.reference.EssentialsGroupManager.jar}:\
53 | ${file.reference.PermissionsEx.jar}:\
54 | ${file.reference.PermissionsBukkit-2.3.jar}:\
55 | ${file.reference.zPermissions-1.3beta1.jar}:\
56 | ${file.reference.Vault-1.4.1.jar}:\
57 | ${file.reference.bukkit-1.7.9-R0.2.jar}
58 | # Space-separated list of extra javac options
59 | javac.compilerargs=-Xlint:deprecation -Xlint:unchecked
60 | javac.deprecation=true
61 | javac.processorpath=\
62 | ${javac.classpath}
63 | javac.source=1.6
64 | javac.target=1.6
65 | javac.test.classpath=\
66 | ${javac.classpath}:\
67 | ${build.classes.dir}:\
68 | ${file.reference.junit-4.11.jar}:\
69 | ${file.reference.hamcrest-core-1.3.jar}:\
70 | ${file.reference.javassist.jar}:\
71 | ${file.reference.mockito-all-1.9.5.jar}:\
72 | ${file.reference.powermock-mockito-1.5.4-full.jar}:\
73 | ${file.reference.commons-lang3-3.3.1.jar}
74 | javac.test.processorpath=\
75 | ${javac.test.classpath}
76 | javadoc.additionalparam=
77 | javadoc.author=true
78 | javadoc.encoding=${source.encoding}
79 | javadoc.noindex=false
80 | javadoc.nonavbar=false
81 | javadoc.notree=false
82 | javadoc.private=true
83 | javadoc.splitindex=true
84 | javadoc.use=true
85 | javadoc.version=true
86 | javadoc.windowtitle=
87 | jnlp.codebase.type=no.codebase
88 | jnlp.descriptor=application
89 | jnlp.enabled=false
90 | jnlp.mixed.code=default
91 | jnlp.offline-allowed=false
92 | jnlp.signed=false
93 | jnlp.signing=
94 | jnlp.signing.alias=
95 | jnlp.signing.keystore=
96 | main.class=
97 | manifest.file=manifest.mf
98 | meta.inf.dir=${src.dir}/META-INF
99 | mkdist.disabled=true
100 | platform.active=default_platform
101 | run.classpath=\
102 | ${javac.classpath}:\
103 | ${build.classes.dir}
104 | # Space-separated list of JVM arguments used when running the project.
105 | # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
106 | # To set system properties for unit tests define test-sys-prop.name=value:
107 | run.jvmargs=-Xms1024m -Xmx2048m
108 | run.test.classpath=\
109 | ${javac.test.classpath}:\
110 | ${build.test.classes.dir}
111 | source.encoding=UTF-8
112 | src.dir=${file.reference.CommunityBridge-src}
113 | test.test.dir=test
114 |
--------------------------------------------------------------------------------
/nbproject/project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | org.netbeans.modules.java.j2seproject
4 |
5 |
6 | CommunityBridge
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | CommunityBridge
4 | CommunityBridge
5 | 0.0.1-SNAPSHOT
6 |
7 |
8 |
9 |
10 | org.spigotmc
11 | spigot-api
12 | 1.9-R0.1-SNAPSHOT
13 |
14 |
15 |
16 |
17 | de.bananaco
18 | bPermissions
19 | v2.12-DEV
20 | provided
21 |
22 |
23 |
24 | net.milkbowl.vault
25 | VaultAPI
26 | LATEST
27 | provided
28 |
29 |
30 |
31 | EssentialsGroupManager
32 | EssentialsGroupManager
33 | v1
34 | system
35 | D:/ProjetosBukkit/APIs/EssentialsGroupManager.jar
36 |
37 |
38 |
39 | PermissionsBukkit
40 | PermissionsBukkit
41 | v1
42 | system
43 | D:/ProjetosBukkit/APIs/PermissionsBukkit-2.5.jar
44 |
45 |
46 |
47 | PermissionsEx
48 | PermissionsEx
49 | v1
50 | system
51 | D:/ProjetosBukkit/APIs/PermissionsEx-1.23.4.jar
52 |
53 |
54 |
55 | zPermissions
56 | zPermissions
57 | v1
58 | system
59 | D:/ProjetosBukkit/APIs/zPermissions-1.3beta1.jar
60 |
61 |
62 |
63 |
64 |
65 | spigot-repo
66 | https://hub.spigotmc.org/nexus/content/groups/public/
67 |
68 |
69 |
70 | vault-repo
71 | http://nexus.theyeticave.net/content/repositories/pub_releases
72 |
73 |
74 |
75 | bPermissions-repo
76 | http://maven.elmakers.com/repository/
77 |
78 |
79 |
80 |
81 |
82 | ${project.name}
83 | clean package install
84 |
85 |
86 | org.apache.maven.plugins
87 | maven-compiler-plugin
88 | 3.1
89 |
90 | 1.7
91 | 1.7
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/Achievement.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import java.util.EnumMap;
4 | import java.util.Map;
5 | import java.util.Map.Entry;
6 | import java.util.Set;
7 | import org.bukkit.Material;
8 | import org.bukkit.configuration.ConfigurationSection;
9 | import org.bukkit.configuration.file.YamlConfiguration;
10 | import org.bukkit.entity.Player;
11 | import org.bukkit.inventory.Inventory;
12 | import org.bukkit.inventory.ItemStack;
13 | import org.communitybridge.main.BukkitWrapper;
14 | import org.communitybridge.main.Environment;
15 |
16 | public abstract class Achievement
17 | {
18 | protected Environment environment;
19 |
20 | protected int limit;
21 | protected double cashReward;
22 | protected Map itemRewards = new EnumMap(Material.class);
23 |
24 | protected BukkitWrapper bukkit = new BukkitWrapper();
25 |
26 | public abstract boolean playerQualifies(Player player, PlayerAchievementState state);
27 |
28 | public Achievement(Environment environment)
29 | {
30 | this.environment = environment;
31 | }
32 |
33 | public void rewardPlayer(Player player, PlayerAchievementState state)
34 | {
35 | if (environment.getConfiguration().economyEnabled)
36 | {
37 | environment.getEconomy().depositPlayer(player, cashReward);
38 | }
39 |
40 | for (Entry entry : itemRewards.entrySet())
41 | {
42 | ItemStack stack = new ItemStack(entry.getKey(), entry.getValue());
43 | player.getInventory().addItem(stack);
44 | }
45 | if (!itemRewards.isEmpty())
46 | {
47 | player.updateInventory();
48 | }
49 | }
50 |
51 | protected boolean canRewardAllItemRewards(Player player)
52 | {
53 | final Inventory testInventory = bukkit.getServer().createInventory(null, player.getInventory().getType());
54 | testInventory.setContents(player.getInventory().getContents());
55 |
56 | for (Entry entry : itemRewards.entrySet())
57 | {
58 | ItemStack stack = new ItemStack(entry.getKey(), entry.getValue());
59 | if (!testInventory.addItem(stack).isEmpty())
60 | {
61 | return false;
62 | }
63 | }
64 |
65 | return true;
66 | }
67 |
68 | public void load(YamlConfiguration configuration, String path)
69 | {
70 | limit = configuration.getInt(path + ".Limit", 1);
71 | cashReward = configuration.getDouble(path + ".Money", 0.0);
72 |
73 | ConfigurationSection itemsSection = configuration.getConfigurationSection(path + ".Items");
74 |
75 | if (itemsSection == null)
76 | {
77 | return;
78 | }
79 |
80 | Set itemSet = itemsSection.getKeys(false);
81 |
82 | for (String key : itemSet)
83 | {
84 | Material material = Material.getMaterial(key);
85 | if (material == null)
86 | {
87 | environment.getLog().warning("Invalid material in achievements file");
88 | continue;
89 | }
90 | int amount = itemsSection.getInt(key, 1);
91 | itemRewards.put(material, amount);
92 | }
93 | }
94 |
95 | public int getLimit()
96 | {
97 | return limit;
98 | }
99 |
100 | public void setLimit(int limit)
101 | {
102 | this.limit = limit;
103 | }
104 |
105 | public double getCashReward()
106 | {
107 | return cashReward;
108 | }
109 |
110 | public void setCashReward(double cashReward)
111 | {
112 | this.cashReward = cashReward;
113 | }
114 |
115 | public Map getItemRewards()
116 | {
117 | return itemRewards;
118 | }
119 |
120 | public void setItemRewards(Map itemRewards)
121 | {
122 | this.itemRewards = itemRewards;
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/AchievementAvatar.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import org.bukkit.entity.Player;
4 | import org.communitybridge.main.Environment;
5 |
6 | public class AchievementAvatar extends Achievement
7 | {
8 | public AchievementAvatar(Environment environment)
9 | {
10 | super(environment);
11 | }
12 |
13 | @Override
14 | public boolean playerQualifies(Player player, PlayerAchievementState state)
15 | {
16 | return environment.getConfiguration().avatarEnabled
17 | && environment.getWebApplication().playerHasAvatar(environment.getUserPlayerLinker().getUserID(player))
18 | && state.getAvatarAchievements() < limit
19 | && canRewardAllItemRewards(player);
20 | }
21 |
22 | @Override
23 | public void rewardPlayer(Player player, PlayerAchievementState state)
24 | {
25 | super.rewardPlayer(player, state);
26 | state.avatarIncrement();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/AchievementGroup.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import org.bukkit.entity.Player;
4 | import org.communitybridge.main.Environment;
5 |
6 | public class AchievementGroup extends Achievement
7 | {
8 | private String groupName;
9 |
10 | public AchievementGroup(Environment environment)
11 | {
12 | super(environment);
13 | }
14 |
15 | @Override
16 | public boolean playerQualifies(Player player, PlayerAchievementState state)
17 | {
18 | return environment.getPermissionHandler().isMemberOfGroup(player, groupName)
19 | && state.getGroupAchievement(groupName) < limit
20 | && canRewardAllItemRewards(player);
21 | }
22 |
23 | @Override
24 | public void rewardPlayer(Player player, PlayerAchievementState state)
25 | {
26 | super.rewardPlayer(player, state);
27 | state.groupIncrement(groupName);
28 | }
29 |
30 | public String getGroupName()
31 | {
32 | return groupName;
33 | }
34 |
35 | public void setGroupName(String groupName)
36 | {
37 | this.groupName = groupName;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/AchievementPostCount.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import org.bukkit.entity.Player;
4 | import org.communitybridge.main.Environment;
5 |
6 | public class AchievementPostCount extends Achievement
7 | {
8 | private int postCount;
9 |
10 | public AchievementPostCount(Environment environment)
11 | {
12 | super(environment);
13 | }
14 |
15 | @Override
16 | public boolean playerQualifies(Player player, PlayerAchievementState state)
17 | {
18 | return environment.getConfiguration().postCountEnabled
19 | && environment.getWebApplication().getUserPostCount(environment.getUserPlayerLinker().getUserID(player)) >= postCount
20 | && state.getPostCountAchievements(Integer.toString(postCount))< limit
21 | && canRewardAllItemRewards(player);
22 | }
23 |
24 | @Override
25 | public void rewardPlayer(Player player, PlayerAchievementState state)
26 | {
27 | super.rewardPlayer(player, state);
28 | state.postCountIncrement(Integer.toString(postCount));
29 | }
30 |
31 | public int getPostCount()
32 | {
33 | return postCount;
34 | }
35 |
36 | public void setPostCount(int postCount)
37 | {
38 | this.postCount = postCount;
39 | }
40 |
41 | public void setPostCount(String postCount)
42 | {
43 | this.postCount = Integer.parseInt(postCount);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/AchievementSectionPostCount.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this template, choose Tools | Templates
3 | * and open the template in the editor.
4 | */
5 |
6 | package org.communitybridge.achievement;
7 |
8 | import org.bukkit.entity.Player;
9 | import org.communitybridge.main.Environment;
10 |
11 | /**
12 | *
13 | * @author Iain E. Davis
14 | */
15 | public class AchievementSectionPostCount extends AchievementPostCount
16 | {
17 | private String sectionID;
18 |
19 | public AchievementSectionPostCount(Environment environment)
20 | {
21 | super(environment);
22 | }
23 |
24 | @Override
25 | public boolean playerQualifies(Player player, PlayerAchievementState state)
26 | {
27 | throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
28 | }
29 |
30 | public String getSectionID()
31 | {
32 | return sectionID;
33 | }
34 |
35 | public void setSectionID(String sectionName)
36 | {
37 | this.sectionID = sectionName;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/PlayerAchievementState.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 | import java.util.Map.Entry;
8 | import java.util.Set;
9 | import org.bukkit.configuration.ConfigurationSection;
10 | import org.bukkit.configuration.file.FileConfiguration;
11 | import org.bukkit.configuration.file.YamlConfiguration;
12 |
13 | public class PlayerAchievementState
14 | {
15 | String playerName;
16 | String fileName;
17 | File playerFolder;
18 |
19 | private int avatarAchievements;
20 | private Map groupAchievements = new HashMap();
21 | private Map postCountAchievements = new HashMap();
22 | private Map sectionPostCountAchievements = new HashMap();
23 |
24 | public PlayerAchievementState(String playerName, File playerDataFolder)
25 | {
26 | this.playerName = playerName;
27 | this.fileName = playerName + ".achievements.yml";
28 | this.playerFolder = playerDataFolder;
29 | this.avatarAchievements = 0;
30 | }
31 |
32 | public void load()
33 | {
34 | File playerFile = new File(playerFolder, fileName);
35 |
36 | if (playerFile.exists())
37 | {
38 | YamlConfiguration playerData = YamlConfiguration.loadConfiguration(playerFile);
39 |
40 | avatarAchievements = playerData.getInt("avatar");
41 |
42 | loadGroupAchievementCounts(playerData);
43 | loadPostCountAchievementCounts(playerData);
44 | loadSectionPostCountAchievementCounts(playerData);
45 | }
46 | }
47 |
48 | public void save() throws IOException
49 | {
50 | File playerFile = new File(playerFolder, fileName);
51 |
52 | FileConfiguration playerData = new YamlConfiguration();
53 |
54 | playerData.set("avatar", avatarAchievements);
55 |
56 | saveGroupAchievements(playerData);
57 | savePostCountAchievements(playerData);
58 | saveSectionPostCountAchievements(playerData);
59 | playerData.save(playerFile);
60 | }
61 |
62 | private void loadGroupAchievementCounts(YamlConfiguration playerData)
63 | {
64 | ConfigurationSection groupsSection = playerData.getConfigurationSection("groups");
65 | if (groupsSection != null)
66 | {
67 | Set groupNames = groupsSection.getKeys(false);
68 |
69 | for (String groupName : groupNames)
70 | {
71 | int count = groupsSection.getInt(groupName);
72 | groupAchievements.put(groupName, count);
73 | }
74 | }
75 | }
76 |
77 | private void loadPostCountAchievementCounts(YamlConfiguration playerData) throws NumberFormatException
78 | {
79 | ConfigurationSection postCountSection = playerData.getConfigurationSection("post-counts");
80 |
81 | if (postCountSection != null)
82 | {
83 | Set postCounts = postCountSection.getKeys(false);
84 |
85 | for (String postCount : postCounts)
86 | {
87 | int count = postCountSection.getInt(postCount);
88 | postCountAchievements.put(postCount, count);
89 | }
90 | }
91 | }
92 |
93 | private void loadSectionPostCountAchievementCounts(YamlConfiguration playerData) throws NumberFormatException
94 | {
95 | ConfigurationSection sectionPostCountSection = playerData.getConfigurationSection("section-post-counts");
96 | if (sectionPostCountSection != null) {
97 | Set sectionIDs = sectionPostCountSection.getKeys(false);
98 | for (String sectionID : sectionIDs)
99 | {
100 | ConfigurationSection postCountSection = sectionPostCountSection.getConfigurationSection(sectionID);
101 | Set postCounts = postCountSection.getKeys(false);
102 |
103 | for (String postCount : postCounts)
104 | {
105 | SectionPostCount sectionPostCount = new SectionPostCount(sectionID, Integer.parseInt(postCount));
106 | int count = postCountSection.getInt(postCount);
107 | sectionPostCountAchievements.put(sectionPostCount, count);
108 | }
109 | }
110 | }
111 | }
112 |
113 | private void saveGroupAchievements(FileConfiguration playerData)
114 | {
115 | for (Entry entry : groupAchievements.entrySet())
116 | {
117 | playerData.set("groups." + entry.getKey(), entry.getValue());
118 | }
119 | }
120 |
121 | private void savePostCountAchievements(FileConfiguration playerData)
122 | {
123 | for (Entry entry : postCountAchievements.entrySet())
124 | {
125 | playerData.set("post-counts." + entry.getKey(), entry.getValue());
126 | }
127 | }
128 |
129 | private void saveSectionPostCountAchievements(FileConfiguration playerData)
130 | {
131 | for (Entry entry : sectionPostCountAchievements.entrySet())
132 | {
133 | String path = "section-post-counts." + entry.getKey().getSectionID() + "." + entry.getKey().getPostCount();
134 | playerData.set(path, entry.getValue());
135 | }
136 | }
137 |
138 | public void avatarIncrement()
139 | {
140 | avatarAchievements++;
141 | }
142 |
143 | public void groupIncrement(String groupName)
144 | {
145 | Integer count = getGroupAchievement(groupName);
146 | count++;
147 | groupAchievements.put(groupName, count);
148 | }
149 |
150 | public void postCountIncrement(String postCount)
151 | {
152 | Integer count = getPostCountAchievements(postCount);
153 | count++;
154 | postCountAchievements.put(postCount, count);
155 | }
156 |
157 | public void sectionPostCountIncrement(String sectionID, int postCount)
158 | {
159 | SectionPostCount spt = new SectionPostCount(sectionID, postCount);
160 | Integer count = getSectionPostCountAchievements(spt);
161 | count++;
162 | sectionPostCountAchievements.put(spt, count);
163 | }
164 |
165 | public int getAvatarAchievements()
166 | {
167 | return avatarAchievements;
168 | }
169 |
170 | public Integer getGroupAchievement(String groupName)
171 | {
172 | Integer count = groupAchievements.get(groupName);
173 |
174 | if (count == null)
175 | {
176 | count = new Integer(0);
177 | }
178 |
179 | return count;
180 | }
181 |
182 | public Integer getPostCountAchievements(String postCount)
183 | {
184 | Integer count = postCountAchievements.get(postCount);
185 |
186 | if (count == null)
187 | {
188 | count = new Integer(0);
189 | }
190 |
191 | return count;
192 | }
193 |
194 | public Integer getSectionPostCountAchievements(String sectionID, int postCount)
195 | {
196 | SectionPostCount spt = new SectionPostCount(sectionID, postCount);
197 | return getSectionPostCountAchievements(spt);
198 | }
199 |
200 | private Integer getSectionPostCountAchievements(SectionPostCount spt)
201 | {
202 | Integer count = sectionPostCountAchievements.get(spt);
203 |
204 | if (count == null)
205 | {
206 | count = new Integer(0);
207 | }
208 |
209 | return count;
210 | }
211 | }
212 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/achievement/SectionPostCount.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | class SectionPostCount
4 | {
5 | private String sectionID;
6 | private int postCount;
7 |
8 | public SectionPostCount(String sectionID, int postCount)
9 | {
10 | this.sectionID = sectionID;
11 | this.postCount = postCount;
12 | }
13 |
14 | @Override
15 | public boolean equals(Object other)
16 | {
17 | if (other == null || this.getClass() != other.getClass())
18 | {
19 | return false;
20 | }
21 | return this.equals((SectionPostCount)other);
22 | }
23 |
24 | @Override
25 | public int hashCode()
26 | {
27 | int hash = 3;
28 | hash = 79 * hash + (this.sectionID != null ? this.sectionID.hashCode() : 0);
29 | hash = 79 * hash + this.postCount;
30 | return hash;
31 | }
32 |
33 | public boolean equals(SectionPostCount other)
34 | {
35 | return this.sectionID.equals(other.sectionID) && this.postCount == other.postCount;
36 | }
37 |
38 | public String getSectionID()
39 | {
40 | return sectionID;
41 | }
42 |
43 | public void setSectionID(String sectionID)
44 | {
45 | this.sectionID = sectionID;
46 | }
47 |
48 | public int getPostCount()
49 | {
50 | return postCount;
51 | }
52 |
53 | public void setPostCount(int postCount)
54 | {
55 | this.postCount = postCount;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/grouprules/GroupRule.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.grouprules;
2 |
3 | /**
4 | *
5 | * @author Feaelin (Iain E. Davis)
6 | */
7 | public class GroupRule
8 | {
9 | public String groupID;
10 | public String groupName;
11 | public String world;
12 | public boolean allWorlds;
13 | public GroupRuleDirection direction;
14 |
15 | public GroupRule()
16 | {
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/grouprules/GroupRuleDirection.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.grouprules;
2 |
3 | /**
4 | * Enumeration for possible group synchronization directions
5 | *
6 | * @author Iain E. Davis
7 | */
8 | public enum GroupRuleDirection
9 | {
10 | MINECRAFT,
11 | WEBAPP
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/linker/UserIDDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.linker;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.ResultSet;
5 | import java.sql.SQLException;
6 | import org.communitybridge.main.Configuration;
7 | import org.communitybridge.main.Environment;
8 |
9 | public class UserIDDao
10 | {
11 | protected static final String EXCEPTION_MESSAGE_GETUSERID = "Exception during UserIDDao.getUserID: ";
12 | protected static final String EXCEPTION_MESSAGE_GETUUID = "Exception during UserIDDao.getUUID: ";
13 |
14 | private Environment environment;
15 | private Configuration configuration;
16 | private ResultSet result;
17 |
18 | public UserIDDao(Environment environment)
19 | {
20 | this.environment = environment;
21 | this.configuration = environment.getConfiguration();
22 | }
23 |
24 | public String getUserID(String identifier)
25 | {
26 | String query = "SELECT `" + configuration.linkingTableName + "`.`" + configuration.linkingUserIDColumn + "` " + "FROM `" + configuration.linkingTableName + "` ";
27 | if (configuration.linkingUsesKey)
28 | {
29 | query = query + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' " + "AND `" + configuration.linkingValueColumn + "` = '" + identifier + "' ";
30 | }
31 | else
32 | {
33 | query = query + "WHERE LOWER(`" + configuration.linkingIdentifierColumn + "`) = LOWER('" + identifier + "') ";
34 | }
35 | query = query + "ORDER BY `" + configuration.linkingUserIDColumn + "` DESC";
36 | try
37 | {
38 | result = environment.getSql().sqlQuery(query);
39 | if (result != null && result.next())
40 | {
41 | return result.getString(configuration.linkingUserIDColumn);
42 | }
43 | }
44 | catch (IllegalAccessException exception)
45 | {
46 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUSERID + exception.getMessage());
47 | }
48 | catch (InstantiationException exception)
49 | {
50 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUSERID + exception.getMessage());
51 | }
52 | catch (MalformedURLException exception)
53 | {
54 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUSERID + exception.getMessage());
55 | }
56 | catch (SQLException exception)
57 | {
58 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUSERID + exception.getMessage());
59 | }
60 | return "";
61 | }
62 |
63 | public String getUUID(String userID)
64 | {
65 | String query;
66 | String uuid = "";
67 | if (configuration.linkingUsesKey)
68 | {
69 | query = "SELECT `" + configuration.linkingValueColumn + "` "
70 | + "FROM `" + configuration.linkingTableName + "` "
71 | + "WHERE `" + configuration.linkingKeyColumn + "` = '" + configuration.linkingKeyName + "' "
72 | + "AND `" + configuration.linkingUserIDColumn + "` = '" + userID + "'";
73 | }
74 | else
75 | {
76 | query = "SELECT `" + configuration.linkingIdentifierColumn + "` "
77 | + "FROM `" + configuration.linkingTableName + "` "
78 | + "WHERE `" + configuration.linkingUserIDColumn + "` = '" + userID + "'";
79 | }
80 | try
81 | {
82 | result = environment.getSql().sqlQuery(query);
83 | if (result != null && result.next())
84 | {
85 | if (configuration.linkingUsesKey)
86 | {
87 | uuid = result.getString(configuration.linkingValueColumn);
88 | }
89 | else
90 | {
91 | uuid = result.getString(configuration.linkingIdentifierColumn);
92 | }
93 | }
94 | }
95 | catch (MalformedURLException exception)
96 | {
97 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUUID + exception.getMessage());
98 | }
99 | catch (InstantiationException exception)
100 | {
101 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUUID + exception.getMessage());
102 | }
103 | catch (IllegalAccessException exception)
104 | {
105 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUUID + exception.getMessage());
106 | }
107 | catch (SQLException exception)
108 | {
109 | environment.getLog().severe(EXCEPTION_MESSAGE_GETUUID + exception.getMessage());
110 | }
111 | return uuid;
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/linker/UserPlayerLinker.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.linker;
2 |
3 | import org.communitybridge.main.BukkitWrapper;
4 | import java.util.Map;
5 | import java.util.UUID;
6 | import java.util.concurrent.ConcurrentHashMap;
7 | import org.bukkit.entity.Player;
8 | import org.communitybridge.main.Environment;
9 |
10 | public class UserPlayerLinker
11 | {
12 | private ConcurrentHashMap userIDCache = new ConcurrentHashMap();
13 | private Environment environment;
14 | private UserIDDao userIDDao;
15 | private BukkitWrapper bukkit;
16 | private int cacheLimit;
17 |
18 | public UserPlayerLinker(Environment environment, int cacheLimit)
19 | {
20 | this.cacheLimit = cacheLimit;
21 | this.environment = environment;
22 | this.userIDDao = new UserIDDao(environment);
23 | this.bukkit = new BukkitWrapper();
24 | }
25 |
26 | public void removeUserIDFromCache(String uuid, String name)
27 | {
28 | userIDCache.remove(uuid);
29 | userIDCache.remove(name);
30 | }
31 |
32 | public String getPlayerName(String userID)
33 | {
34 | String identifier = getIdentifier(userID);
35 | UUID uuid;
36 |
37 | try
38 | {
39 | uuid = UUID.fromString(identifier);
40 | }
41 | catch(IllegalArgumentException exception)
42 | {
43 | return identifier;
44 | }
45 | return bukkit.getPlayer(uuid).getName();
46 | }
47 |
48 | private String getIdentifier(String userID)
49 | {
50 | for (Map.Entry entry : userIDCache.entrySet())
51 | {
52 | if (userID.equals(entry.getValue()))
53 | {
54 | return entry.getKey();
55 | }
56 | }
57 | return userIDDao.getUUID(userID);
58 | }
59 |
60 | public String getUUID(String userID)
61 | {
62 | return getIdentifier(userID);
63 | }
64 |
65 | public String getUserID(String uuid)
66 | {
67 | return getUserIDFromCacheOrDatabase(uuid);
68 | }
69 |
70 | public String getUserID(Player player)
71 | {
72 | return getUserID(player.getUniqueId().toString(), player.getName());
73 | }
74 |
75 | public String getUserID(String uuid, String name)
76 | {
77 | String userID = "";
78 | String linkingMethod = environment.getConfiguration().linkingMethod;
79 |
80 | if (isValidMethod(linkingMethod, "uui"))
81 | {
82 | userID = getUserIDFromCacheOrDatabase(uuid);
83 | }
84 |
85 | if (userID.isEmpty() && isValidMethod(linkingMethod, "nam"))
86 | {
87 | userID = getUserIDFromCacheOrDatabase(name);
88 | }
89 | return userID;
90 | }
91 |
92 | private boolean isValidMethod(String linkingMethod, String valid)
93 | {
94 | return linkingMethod.startsWith(valid) || linkingMethod.startsWith("bot");
95 | }
96 |
97 | private String getUserIDFromCacheOrDatabase(String identifier)
98 | {
99 | String userID = userIDCache.get(identifier);
100 | if (userID == null)
101 | {
102 | userID = userIDDao.getUserID(identifier);
103 | if (userIDCache.size() == cacheLimit)
104 | {
105 | userIDCache.clear();
106 | }
107 | userIDCache.put(identifier, userID);
108 | }
109 | return userID;
110 | }
111 |
112 | protected ConcurrentHashMap getUserIDCache()
113 | {
114 | return userIDCache;
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/BukkitWrapper.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.util.Collection;
4 | import java.util.UUID;
5 |
6 | import org.bukkit.BanList;
7 | import org.bukkit.Bukkit;
8 | import org.bukkit.OfflinePlayer;
9 | import org.bukkit.Server;
10 | import org.bukkit.entity.Player;
11 | import org.bukkit.plugin.PluginManager;
12 |
13 | public class BukkitWrapper
14 | {
15 | public OfflinePlayer getOfflinePlayer(UUID uuid)
16 | {
17 | return Bukkit.getOfflinePlayer(uuid);
18 | }
19 |
20 | @SuppressWarnings("deprecation")
21 | public OfflinePlayer getOfflinePlayer(String name)
22 | {
23 | return Bukkit.getOfflinePlayer(name);
24 | }
25 |
26 | public Player getPlayer(UUID uuid)
27 | {
28 | return Bukkit.getPlayer(uuid);
29 | }
30 |
31 | public Server getServer()
32 | {
33 | return Bukkit.getServer();
34 | }
35 |
36 | public BanList getBanList(BanList.Type type)
37 | {
38 | return Bukkit.getBanList(type);
39 | }
40 |
41 | public PluginManager getPluginManager()
42 | {
43 | return Bukkit.getPluginManager();
44 | }
45 |
46 | public Collection extends Player> getOnlinePlayers()
47 | {
48 | return Bukkit.getOnlinePlayers();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/CBCommandExecutor.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import org.bukkit.ChatColor;
4 | import org.bukkit.command.Command;
5 | import org.bukkit.command.CommandExecutor;
6 | import org.bukkit.command.CommandSender;
7 | import org.bukkit.entity.Player;
8 |
9 | public class CBCommandExecutor implements CommandExecutor
10 | {
11 | private Environment environment;
12 |
13 | private BukkitWrapper bukkit;
14 |
15 | public CBCommandExecutor(Environment environment)
16 | {
17 | this.environment = environment;
18 | this.bukkit = new BukkitWrapper();
19 | }
20 |
21 | @Override
22 | public boolean onCommand(CommandSender sender, Command command, String label, String[] arguments)
23 | {
24 | label = label.toLowerCase();
25 | if (label.equals("cbreload"))
26 | {
27 | commandReload(arguments, sender);
28 | return true;
29 | }
30 |
31 | if (CommunityBridge.isActive() == false)
32 | {
33 | sendOrLog(sender, environment.getConfiguration().messages.get("communitybridge-inactive"), ChatColor.RED, false);
34 | return true;
35 | }
36 |
37 | if (label.equals("cbsync"))
38 | {
39 | if (arguments.length == 1 && (!(sender instanceof Player) || ((Player)sender).hasPermission("communitybridge.cbsynctarget")))
40 | {
41 | commandSyncTarget(sender, arguments[0]);
42 | }
43 | else
44 | {
45 | commandSync(sender);
46 | }
47 | return true;
48 | }
49 |
50 | if (label.equals("cbsyncall"))
51 | {
52 | commandSyncAll(sender);
53 | return true;
54 | }
55 |
56 | return true;
57 | }
58 |
59 | private void sendAndLog(CommandSender sender, String message, ChatColor color, boolean who)
60 | {
61 | if (sender instanceof Player)
62 | {
63 | sender.sendMessage(color + message);
64 | }
65 |
66 | if (who)
67 | {
68 | message = "(" + sender.getName() + ") " + message;
69 | }
70 |
71 | environment.getLog().info(message);
72 | }
73 |
74 | private void sendOrLog(CommandSender sender, String message, ChatColor color, boolean who)
75 | {
76 | if (sender instanceof Player)
77 | {
78 | sender.sendMessage(color + message);
79 | }
80 | else
81 | {
82 | if (who)
83 | {
84 | message = "(" + sender.getName() + ") " + message;
85 | }
86 | environment.getLog().info(message);
87 | }
88 | }
89 |
90 | private void commandReload(String[] arguments, CommandSender sender)
91 | {
92 | if (arguments.length > 1)
93 | {
94 | sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-too-many-arguments"), ChatColor.RED, false);
95 | }
96 |
97 | sendAndLog(sender, environment.getConfiguration().messages.get("cbreload"), ChatColor.GREEN, true);
98 |
99 | String error;
100 | String filename;
101 | if (arguments.length == 1)
102 | {
103 | filename = arguments[0];
104 | }
105 | else
106 | {
107 | filename = "config.yml";
108 | }
109 |
110 | error = environment.getConfiguration().reload(filename);
111 |
112 | if (error == null)
113 | {
114 | sendOrLog(sender, environment.getConfiguration().messages.get("cbreload-success").replace("~FILENAME~", filename), ChatColor.GREEN, false);
115 | if (CommunityBridge.isActive())
116 | {
117 | environment.getConfiguration().report();
118 | }
119 | }
120 | else
121 | {
122 | sendOrLog(sender, error, ChatColor.RED, false);
123 | }
124 | }
125 |
126 | private void commandSync(CommandSender sender)
127 | {
128 | if (sender instanceof Player)
129 | {
130 | sendOrLog(sender, environment.getConfiguration().messages.get("cbsync"), ChatColor.GREEN, false);
131 | environment.getWebApplication().runSynchronizePlayer(environment, (Player) sender, true);
132 | }
133 | else
134 | {
135 | sendOrLog(sender, environment.getConfiguration().messages.get("cbsync-ingame"), ChatColor.RED, false);
136 | }
137 | }
138 |
139 | private void commandSyncAll(CommandSender sender)
140 | {
141 | sendAndLog(sender, environment.getConfiguration().messages.get("cbsyncall"), ChatColor.GREEN, true);
142 | environment.getWebApplication().runSynchronizeAll();
143 | }
144 |
145 | private void commandSyncTarget(CommandSender sender, String playerName)
146 | {
147 | Player player = bukkit.getServer().getPlayerExact(playerName);
148 | if (player == null)
149 | {
150 | String message = environment.getConfiguration().messages.get("cbsync-target-not-found").replace("~PLAYERNAME~", playerName);
151 | sendOrLog(sender, message, ChatColor.RED, false);
152 | }
153 | else
154 | {
155 | String message = environment.getConfiguration().messages.get("cbsync-target").replace("~PLAYERNAME~", player.getName());
156 | sendAndLog(sender, message, ChatColor.GREEN, true);
157 | environment.getWebApplication().runSynchronizePlayer(environment, player, true);
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/DatabaseHandler.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.Connection;
5 | import java.sql.DriverManager;
6 | import java.sql.ResultSet;
7 | import java.sql.SQLException;
8 | import java.sql.Statement;
9 | import java.util.Properties;
10 | import org.communitybridge.utility.Log;
11 |
12 | public class DatabaseHandler
13 | {
14 | private Log log;
15 | private Connection connection;
16 | private String dblocation;
17 | private String username;
18 | private String password;
19 | private String database;
20 | private String localAddress;
21 |
22 | public DatabaseHandler(Log log, String dbLocation, String database, String username, String password, String localAddress)
23 | {
24 | this.log = log;
25 | this.dblocation = dbLocation;
26 | this.database = database;
27 | this.username = username;
28 | this.password = password;
29 | this.localAddress = localAddress;
30 | }
31 |
32 | private void openConnection() throws MalformedURLException, InstantiationException, IllegalAccessException
33 | {
34 | try
35 | {
36 | Class.forName("com.mysql.jdbc.Driver");
37 | Properties properties = new Properties();
38 | properties.setProperty("user", username);
39 | properties.setProperty("password", password);
40 | if (!localAddress.isEmpty())
41 | {
42 | properties.setProperty("localSocketAddress", localAddress);
43 | }
44 | connection = DriverManager.getConnection("jdbc:mysql://" + dblocation + "/" + database, properties);
45 | }
46 | catch (ClassNotFoundException exception)
47 | {
48 | log.severe("No MySQL Driver Found:" + exception.getMessage());
49 | connection = null;
50 | }
51 | catch (SQLException exception)
52 | {
53 | log.severe("Could not connect to MySQL Server:" + exception.getMessage());
54 | connection = null;
55 | }
56 | }
57 |
58 | public boolean checkConnection()
59 | {
60 | if (this.connection == null)
61 | {
62 | try
63 | {
64 | openConnection();
65 | if (this.connection == null)
66 | {
67 | return false;
68 | }
69 | return true;
70 | }
71 | catch (MalformedURLException exception)
72 | {
73 | log.severe("MalformedURLException! " + exception.getMessage());
74 | }
75 | catch (InstantiationException exception)
76 | {
77 | log.severe("InstantiationExceptioon! " + exception.getMessage());
78 | }
79 | catch (IllegalAccessException exception)
80 | {
81 | log.severe("IllegalAccessException! " + exception.getMessage());
82 | }
83 | return false;
84 | }
85 |
86 | try
87 | {
88 | return !connection.isClosed();
89 | }
90 | catch (SQLException e)
91 | {
92 | return false;
93 | }
94 | }
95 |
96 | public void closeConnection() {
97 | try
98 | {
99 | if (this.connection != null)
100 | {
101 | this.connection.close();
102 | }
103 | }
104 | catch (Exception e)
105 | {
106 | log.warning("Failed to close database connection! " + e.getMessage());
107 | }
108 | }
109 |
110 | public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException
111 | {
112 | if (this.connection == null)
113 | {
114 | openConnection();
115 | return this.connection;
116 | }
117 | else
118 | {
119 | try
120 | {
121 | if (this.connection.isClosed())
122 | {
123 | openConnection();
124 | }
125 |
126 | Statement statement = connection.createStatement();
127 | statement.setQueryTimeout(5);
128 | ResultSet result = statement.executeQuery("SELECT 1");
129 |
130 | if (result.next())
131 | {
132 | return this.connection;
133 | }
134 | openConnection();
135 | return this.connection;
136 | }
137 | catch (SQLException exception)
138 | {
139 | try
140 | {
141 | openConnection();
142 |
143 | Statement statement = connection.createStatement();
144 | statement.setQueryTimeout(5);
145 | ResultSet result = statement.executeQuery("SELECT 1");
146 | if (result.next())
147 | {
148 | return this.connection;
149 | }
150 | }
151 | catch (SQLException exception2)
152 | {
153 | log.warning("Database Connection Exception: " + exception2.getMessage());
154 | }
155 | }
156 | }
157 | return null;
158 | }
159 |
160 | public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
161 | {
162 | Connection connectionLocal = getConnection();
163 |
164 | if (connectionLocal == null)
165 | {
166 | return null;
167 | }
168 |
169 | Statement statement = connectionLocal.createStatement();
170 |
171 | statement.setQueryTimeout(10);
172 |
173 | return statement.executeQuery(query);
174 | }
175 |
176 | public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
177 | {
178 | try
179 | {
180 | Connection connectionLocal = getConnection();
181 |
182 | if (connectionLocal != null)
183 | {
184 | Statement statement = connectionLocal.createStatement();
185 | statement.executeUpdate(query);
186 | }
187 | }
188 | catch (SQLException exception)
189 | {
190 | if (!exception.toString().contains("not return ResultSet"))
191 | {
192 | throw exception;
193 | }
194 | }
195 | }
196 |
197 | public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException
198 | {
199 | try
200 | {
201 | Connection connectionLocal = getConnection();
202 |
203 | if (connectionLocal != null)
204 | {
205 | Statement statement = connectionLocal.createStatement();
206 | statement.executeUpdate(query);
207 | }
208 | }
209 | catch (SQLException exception)
210 | {
211 | if (!exception.toString().contains("not return ResultSet"))
212 | {
213 | log.warning("Exception at SQL UPDATE Query: " + exception);
214 | }
215 | }
216 | }
217 |
218 | public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException
219 | {
220 | try
221 | {
222 | Connection connectionLocal = getConnection();
223 |
224 | if (connectionLocal != null)
225 | {
226 | Statement statement = connectionLocal.createStatement();
227 | statement.executeUpdate(query);
228 | }
229 | }
230 | catch (SQLException exception)
231 | {
232 | if (!exception.toString().contains("not return ResultSet"))
233 | {
234 | log.warning("Exception at SQL DELETE Query: " + exception);
235 | }
236 | }
237 | }
238 |
239 | public boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException
240 | {
241 | try
242 | {
243 | Connection connectionLocal = getConnection();
244 |
245 | if (connectionLocal == null)
246 | {
247 | return false;
248 | }
249 | Statement statement = connectionLocal.createStatement();
250 |
251 | ResultSet result = statement.executeQuery("SELECT * FROM " + table);
252 |
253 | if (result == null)
254 | {
255 | return false;
256 | }
257 | return true;
258 | }
259 | catch (SQLException exception)
260 | {
261 | if (exception.getMessage().contains("exist"))
262 | {
263 | return false;
264 | }
265 |
266 | log.warning("Exception at SQL Query: " + exception.getMessage());
267 | }
268 | try
269 | {
270 | if (sqlQuery("SELECT * FROM " + table) == null)
271 | {
272 | return true;
273 | }
274 | }
275 | catch (SQLException exception)
276 | {
277 | log.warning("Exception at SQL Query: " + exception.getMessage());
278 | }
279 | return false;
280 | }
281 | }
282 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/Environment.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import net.milkbowl.vault.economy.Economy;
4 | import org.communitybridge.linker.UserPlayerLinker;
5 | import org.communitybridge.permissionhandlers.PermissionHandler;
6 | import org.communitybridge.utility.Log;
7 |
8 | public class Environment
9 | {
10 | private BukkitWrapper bukkit;
11 | private CommunityBridge plugin;
12 | private Configuration configuration;
13 | private Economy economy;
14 | private Log log;
15 | private PermissionHandler permissionHandler;
16 | private SQL sql;
17 | private UserPlayerLinker userPlayerLinker;
18 | private WebApplication webApplication;
19 |
20 | public Configuration getConfiguration()
21 | {
22 | return configuration;
23 | }
24 |
25 | public void setConfiguration(Configuration configuration)
26 | {
27 | this.configuration = configuration;
28 | }
29 |
30 | public Economy getEconomy()
31 | {
32 | return economy;
33 | }
34 |
35 | public void setEconomy(Economy economy)
36 | {
37 | this.economy = economy;
38 | }
39 |
40 | public SQL getSql()
41 | {
42 | return sql;
43 | }
44 |
45 | public void setSql(SQL sql)
46 | {
47 | this.sql = sql;
48 | }
49 |
50 | public Log getLog()
51 | {
52 | return log;
53 | }
54 |
55 | public void setLog(Log log)
56 | {
57 | this.log = log;
58 | }
59 |
60 | public PermissionHandler getPermissionHandler()
61 | {
62 | return permissionHandler;
63 | }
64 |
65 | public void setPermissionHandler(PermissionHandler permissionHandler)
66 | {
67 | this.permissionHandler = permissionHandler;
68 | }
69 |
70 | public CommunityBridge getPlugin()
71 | {
72 | return plugin;
73 | }
74 |
75 | public void setPlugin(CommunityBridge plugin)
76 | {
77 | this.plugin = plugin;
78 | }
79 |
80 | public UserPlayerLinker getUserPlayerLinker()
81 | {
82 | return userPlayerLinker;
83 | }
84 |
85 | public void setUserPlayerLinker(UserPlayerLinker userPlayerLinker)
86 | {
87 | this.userPlayerLinker = userPlayerLinker;
88 | }
89 |
90 | public WebApplication getWebApplication()
91 | {
92 | return webApplication;
93 | }
94 |
95 | public void setWebApplication(WebApplication webApplication)
96 | {
97 | this.webApplication = webApplication;
98 | }
99 |
100 |
101 | public BukkitWrapper getBukkit()
102 | {
103 | return bukkit;
104 | }
105 |
106 | public void setBukkit(BukkitWrapper bukkit)
107 | {
108 | this.bukkit = bukkit;
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/Messages.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class Messages
7 | {
8 | private Map messages = new HashMap();
9 |
10 | public void clear()
11 | {
12 | messages.clear();
13 | }
14 |
15 | public String get(String name)
16 | {
17 | String message = messages.get(name);
18 | if (message == null)
19 | {
20 | return "";
21 | }
22 | else
23 | {
24 | return message;
25 | }
26 | }
27 |
28 | public void put(String name, String message)
29 | {
30 | messages.put(name, message);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/PlayerListener.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import org.bukkit.ChatColor;
4 | import org.bukkit.entity.Player;
5 | import org.bukkit.event.EventHandler;
6 | import org.bukkit.event.EventPriority;
7 | import org.bukkit.event.Listener;
8 | import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
9 | import org.bukkit.event.player.PlayerJoinEvent;
10 | import org.bukkit.event.player.PlayerQuitEvent;
11 |
12 | public class PlayerListener implements Listener
13 | {
14 | private Environment environment;
15 |
16 | public PlayerListener(Environment environment)
17 | {
18 | this.environment = environment;
19 | }
20 |
21 | /**
22 | * This method is called by CraftBukkit as the player connects to the server.
23 | * We perform the initial linking here so that we can reject the login if
24 | * linking-kick-unregistered is turned on.
25 | */
26 | @EventHandler(priority = EventPriority.HIGH)
27 | public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event)
28 | {
29 | String uuid = event.getUniqueId().toString();
30 | String name = event.getName();
31 | environment.getUserPlayerLinker().removeUserIDFromCache(uuid, name);
32 |
33 | String userID = environment.getUserPlayerLinker().getUserID(uuid, name);
34 | if (userID.isEmpty())
35 | {
36 | preLoginUnregisteredPlayer(event);
37 | }
38 | else
39 | {
40 | preLoginRegisteredPlayer(userID, event);
41 | }
42 | }
43 |
44 | @EventHandler(priority = EventPriority.MONITOR)
45 | public void onPlayerJoin(PlayerJoinEvent event)
46 | {
47 | Player player = event.getPlayer();
48 |
49 | if (environment.getUserPlayerLinker().getUserID(player).isEmpty())
50 | {
51 | joinUnregistered(player);
52 | }
53 | else
54 | {
55 | joinRegistered(player);
56 | }
57 | }
58 |
59 | @EventHandler(priority = EventPriority.MONITOR)
60 | public void onPlayerQuit(PlayerQuitEvent event)
61 | {
62 | if (environment.getConfiguration().syncDuringQuit)
63 | {
64 | environment.getWebApplication().runSynchronizePlayer(environment, event.getPlayer(), false);
65 | }
66 | } // onPlayerQuit
67 |
68 | private void preLoginRegisteredPlayer(String userID, AsyncPlayerPreLoginEvent event)
69 | {
70 | environment.getLog().fine(event.getName() + " linked to web application user ID #" + userID + ".");
71 |
72 | if (environment.getConfiguration().avatarEnabled && environment.getConfiguration().requireAvatar && environment.getWebApplication().playerHasAvatar(userID) == false)
73 | {
74 | kickPlayer(event, "require-avatar-message");
75 | }
76 |
77 | if (environment.getConfiguration().postCountEnabled && environment.getConfiguration().requireMinimumPosts && environment.getWebApplication().getUserPostCount(userID) < environment.getConfiguration().requirePostsPostCount)
78 | {
79 | kickPlayer(event, "require-minimum-posts-message");
80 | }
81 | }
82 |
83 | private void preLoginUnregisteredPlayer(AsyncPlayerPreLoginEvent event)
84 | {
85 | if (environment.getConfiguration().linkingKickUnregistered)
86 | {
87 | event.setKickMessage(environment.getConfiguration().messages.get("link-unregistered-player"));
88 | event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST);
89 | }
90 |
91 | if (environment.getConfiguration().requireAvatar)
92 | {
93 | kickPlayer(event, "require-avatar-message");
94 | }
95 |
96 | if (environment.getConfiguration().requireMinimumPosts)
97 | {
98 | kickPlayer(event, "require-minimum-posts-message");
99 | }
100 | }
101 |
102 | private void kickPlayer(AsyncPlayerPreLoginEvent event, String messageKey)
103 | {
104 | event.setKickMessage(environment.getConfiguration().messages.get(messageKey));
105 | event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
106 | }
107 |
108 | private void joinUnregistered(Player player)
109 | {
110 | if (environment.getConfiguration().linkingNotifyUnregistered)
111 | {
112 | String message = ChatColor.RED + environment.getConfiguration().messages.get("link-unregistered-player");
113 | player.sendMessage(message);
114 | } // if config.linkingNotifyUnregistered
115 |
116 | if (!environment.getConfiguration().linkingUnregisteredGroup.isEmpty())
117 | {
118 | environment.getPermissionHandler().addToGroup(player, environment.getConfiguration().linkingUnregisteredGroup);
119 | if (environment.getConfiguration().linkingNotifyPlayerGroup)
120 | {
121 | String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change");
122 | message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingUnregisteredGroup);
123 | player.sendMessage(message);
124 | }
125 |
126 | if (environment.getConfiguration().linkingUnregisterFormerRegistered)
127 | {
128 | environment.getPermissionHandler().removeFromGroup(player, environment.getConfiguration().linkingRegisteredGroup);
129 | }
130 | }
131 | }
132 |
133 | private void joinRegistered(Player player)
134 | {
135 | if (environment.getConfiguration().linkingNotifyRegistered)
136 | {
137 | String message = ChatColor.GREEN + environment.getConfiguration().messages.get("link-registered-player");
138 | player.sendMessage(message);
139 | }
140 |
141 | maybeSwitchToRegistered(player);
142 |
143 | if (environment.getConfiguration().syncDuringJoin)
144 | {
145 | environment.getWebApplication().runSynchronizePlayer(environment, player, true);
146 | }
147 | }
148 |
149 | private void maybeSwitchToRegistered(Player player)
150 | {
151 | // We don't use the linking registered group if it is empty or group
152 | // synchronization is active.
153 | if (environment.getConfiguration().groupSynchronizationActive || environment.getConfiguration().linkingRegisteredGroup.isEmpty())
154 | {
155 | return;
156 | }
157 |
158 | // if this rule is turned on, we won't change groups unless they're
159 | // a member of the unregistered group or they have no groups.
160 | if (environment.getConfiguration().linkingRegisteredFormerUnregisteredOnly && !environment.getPermissionHandler().isMemberOfGroup(player, environment.getConfiguration().linkingUnregisteredGroup) && !environment.getPermissionHandler().getGroupsPure(player).isEmpty())
161 | {
162 | return;
163 | }
164 |
165 | environment.getPermissionHandler().switchGroup(player, environment.getConfiguration().linkingUnregisteredGroup, environment.getConfiguration().linkingRegisteredGroup);
166 |
167 | if (environment.getConfiguration().linkingNotifyPlayerGroup)
168 | {
169 | String message = ChatColor.RED + environment.getConfiguration().messages.get("link-notify-player-group-change");
170 | message = message.replace("~GROUPNAME~", environment.getConfiguration().linkingRegisteredGroup);
171 | player.sendMessage(message);
172 | }
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/PlayerStatistics.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.text.SimpleDateFormat;
4 | import org.communitybridge.utility.StringUtilities;
5 |
6 | public class PlayerStatistics
7 | {
8 | private final SimpleDateFormat dateFormat;
9 | private String userID;
10 | private String onlineStatus;
11 | private long lastOnlineTime;
12 | private long gameTime;
13 | private int level;
14 | private int totalXP;
15 | private float currentXP;
16 | private double health;
17 | private int lifeTicks;
18 |
19 | PlayerStatistics(SimpleDateFormat dateFormat)
20 | {
21 | this.dateFormat = dateFormat;
22 | }
23 |
24 | public String getUserID()
25 | {
26 | return userID;
27 | }
28 |
29 | public void setUserID(String userID)
30 | {
31 | this.userID = userID;
32 | }
33 |
34 | public String getOnlineStatus()
35 | {
36 | return onlineStatus;
37 | }
38 |
39 | public void setOnlineStatus(String onlineStatus)
40 | {
41 | this.onlineStatus = onlineStatus;
42 | }
43 |
44 | public int getLastOnlineTimeInSeconds()
45 | {
46 | return (int)(lastOnlineTime / 1000L);
47 | }
48 |
49 | public String getLastOnlineTimeFormatted()
50 | {
51 | return dateFormat.format(lastOnlineTime);
52 | }
53 |
54 | public void setLastOnlineTime(long lastonlineTime)
55 | {
56 | this.lastOnlineTime = lastonlineTime;
57 | }
58 |
59 | public long getGameTime()
60 | {
61 | return gameTime;
62 | }
63 |
64 | public String getGameTimeFormatted()
65 | {
66 | return StringUtilities.timeElapsedToString(gameTime);
67 | }
68 |
69 | public void setGameTime(long gameTime)
70 | {
71 | this.gameTime = gameTime;
72 | }
73 |
74 | public int getLevel()
75 | {
76 | return level;
77 | }
78 |
79 | public void setLevel(int level)
80 | {
81 | this.level = level;
82 | }
83 |
84 | public int getTotalXP()
85 | {
86 | return totalXP;
87 | }
88 |
89 | public void setTotalXP(int totalxp)
90 | {
91 | this.totalXP = totalxp;
92 | }
93 |
94 | public float getCurrentXP()
95 | {
96 | return currentXP;
97 | }
98 |
99 | public String getCurrentXPFormatted()
100 | {
101 | return ((int)(getCurrentXP() * 100)) + "%";
102 | }
103 |
104 | public void setCurrentXP(float currentxp)
105 | {
106 | this.currentXP = currentxp;
107 | }
108 |
109 | public double getHealth()
110 | {
111 | return health;
112 | }
113 |
114 | public void setHealth(double health)
115 | {
116 | this.health = health;
117 | }
118 |
119 | public int getLifeTicks()
120 | {
121 | return lifeTicks;
122 | }
123 |
124 | public String getLifeTicksFormatted()
125 | {
126 | return StringUtilities.timeElapsedToString(lifeTicks / 20);
127 | }
128 |
129 | public void setLifeTicks(int lifeticks)
130 | {
131 | this.lifeTicks = lifeticks;
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/main/SQL.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.Connection;
5 | import java.sql.ResultSet;
6 | import java.sql.SQLException;
7 | import org.communitybridge.utility.Log;
8 |
9 | public class SQL
10 | {
11 | private Log log;
12 | private String host;
13 | private DatabaseHandler manageDB;
14 | private String username;
15 | private String password;
16 | private String database;
17 | private String localAddress;
18 |
19 | public SQL(Log log, String host, String database, String username, String password, String localAddress)
20 | {
21 | this.log = log;
22 | this.database = database;
23 | this.host = host;
24 | this.username = username;
25 | this.password = password;
26 | this.localAddress = localAddress;
27 | }
28 |
29 | public boolean initialize()
30 | {
31 | this.manageDB = new DatabaseHandler(log, host, database, username, password, localAddress);
32 | return false;
33 | }
34 |
35 | public ResultSet sqlQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
36 | {
37 | log.finest(query);
38 | return this.manageDB.sqlQuery(query);
39 | }
40 |
41 | public void insertQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
42 | {
43 | log.finest(query);
44 | this.manageDB.insertQuery(query);
45 | }
46 |
47 | public void updateQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException
48 | {
49 | log.finest(query);
50 | this.manageDB.updateQuery(query);
51 | }
52 |
53 | public void deleteQuery(String query) throws MalformedURLException, InstantiationException, IllegalAccessException
54 | {
55 | log.finest(query);
56 | this.manageDB.deleteQuery(query);
57 | }
58 |
59 | public Boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException
60 | {
61 | return this.manageDB.checkTable(table);
62 | }
63 |
64 | public Connection getConnection() throws MalformedURLException, InstantiationException, IllegalAccessException
65 | {
66 | return this.manageDB.getConnection();
67 | }
68 |
69 | public void close()
70 | {
71 | this.manageDB.closeConnection();
72 | }
73 |
74 | public boolean checkConnection()
75 | {
76 | return this.manageDB.checkConnection();
77 | }
78 | }
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandler.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.List;
4 | import org.bukkit.entity.Player;
5 | import org.bukkit.plugin.Plugin;
6 | import org.communitybridge.main.BukkitWrapper;
7 | import org.communitybridge.utility.StringUtilities;
8 |
9 | public abstract class PermissionHandler
10 | {
11 | protected final String NOT_FOUND = " not found.";
12 | protected final String NOT_ENABLED = " is not enabled.";
13 | protected final String WRONG_VERSION = " should be at least version ";
14 |
15 | protected BukkitWrapper bukkit = new BukkitWrapper();
16 |
17 | public abstract boolean addToGroup(Player player, String groupName);
18 | public abstract List getGroups(Player player);
19 | public abstract List getGroupsPure(Player player);
20 | public abstract String getPrimaryGroup(Player player);
21 | public abstract boolean isMemberOfGroup(Player player, String groupName);
22 | public abstract boolean isPrimaryGroup(Player player, String groupName);
23 | public abstract boolean removeFromGroup(Player player, String groupName);
24 | public abstract boolean setPrimaryGroup(Player player, String groupName, String formerGroupName);
25 | public abstract boolean supportsPrimaryGroups();
26 |
27 | public void switchGroup(Player player, String formerGroupName, String newGroupName)
28 | {
29 | if (formerGroupName != null && !formerGroupName.isEmpty())
30 | {
31 | removeFromGroup(player, formerGroupName);
32 | }
33 | addToGroup(player, newGroupName);
34 | }
35 |
36 | protected void validate(Plugin plugin, String name, String version) throws IllegalStateException
37 | {
38 | if (plugin == null)
39 | {
40 | throw new IllegalStateException(name + NOT_FOUND);
41 | }
42 |
43 | if (!plugin.isEnabled())
44 | {
45 | throw new IllegalStateException(name + NOT_ENABLED);
46 | }
47 |
48 | if (StringUtilities.compareVersion(plugin.getDescription().getVersion(), version) < 0) {
49 | throw new IllegalStateException(name + WRONG_VERSION + version);
50 | }
51 | }
52 |
53 | protected String determineWorld(Player player)
54 | {
55 | String worldName;
56 | if (player == null)
57 | {
58 | worldName = bukkit.getServer().getWorlds().get(0).getName();
59 | }
60 | else
61 | {
62 | worldName = player.getWorld().getName();
63 | }
64 | return worldName;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerBPermissions.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import de.bananaco.bpermissions.api.ApiLayer;
4 | import de.bananaco.bpermissions.api.CalculableType;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.Iterator;
8 | import java.util.List;
9 | import org.bukkit.Bukkit;
10 | import org.bukkit.entity.Player;
11 | import org.bukkit.plugin.Plugin;
12 |
13 | /**
14 | * Implements the PermissionHandler interface for bPermissions
15 | * Notes about bPermissions
16 | * 2013-May-03: bP does not support the notion of a primary group.
17 | *
18 | * @author Feaelin
19 | */
20 | public class PermissionHandlerBPermissions extends PermissionHandler
21 | {
22 | public PermissionHandlerBPermissions() throws IllegalStateException
23 | {
24 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("bPermissions");
25 |
26 | validate(plugin, "bPermissions", "2.9");
27 | }
28 |
29 | @Override
30 | public boolean addToGroup(Player player, String groupName)
31 | {
32 | ApiLayer.addGroup(determineWorld(player), CalculableType.USER, player.getName(), groupName);
33 |
34 | return true;
35 | }
36 |
37 | @Override
38 | public List getGroups(Player player)
39 | {
40 | List groups = new ArrayList(Arrays.asList(ApiLayer.getGroups(determineWorld(player), CalculableType.USER, player.getName())));
41 |
42 | return groups;
43 | }
44 |
45 | @Override
46 | public List getGroupsPure(Player player)
47 | {
48 | List groupList = getGroups(player);
49 |
50 | Iterator group = groupList.iterator();
51 | while (group.hasNext())
52 | {
53 | if (group.next().equalsIgnoreCase("default"))
54 | {
55 | group.remove();
56 | }
57 | }
58 | return groupList;
59 | }
60 |
61 | @Override
62 | public String getPrimaryGroup(Player player)
63 | {
64 | List groups = getGroupsPure(player);
65 |
66 | if (groups.isEmpty())
67 | {
68 | return "";
69 | }
70 | else
71 | {
72 | return groups.get(0);
73 | }
74 | }
75 |
76 | @Override
77 | public boolean isMemberOfGroup(Player player, String groupName)
78 | {
79 | return getGroupsPure(player).contains(groupName);
80 | }
81 |
82 | @Override
83 | public boolean isPrimaryGroup(Player player, String groupName)
84 | {
85 | return groupName.equalsIgnoreCase(getPrimaryGroup(player));
86 | }
87 |
88 | @Override
89 | public boolean removeFromGroup(Player player, String groupName)
90 | {
91 |
92 | ApiLayer.removeGroup(determineWorld(player), CalculableType.USER, player.getName(), groupName);
93 |
94 | return true;
95 | }
96 |
97 | /**
98 | * bPermissions doesn't really have a notion of a "primary" group. For now,
99 | * this simply performs an addToGroup.
100 | */
101 | @Override
102 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
103 | {
104 | boolean result;
105 | if (formerGroupName == null)
106 | {
107 | result = true;
108 | }
109 | else
110 | {
111 | result = removeFromGroup(player, formerGroupName);
112 | }
113 | return result && addToGroup(player, groupName);
114 | }
115 |
116 | @Override
117 | public boolean supportsPrimaryGroups()
118 | {
119 | return false;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerGroupManager.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.anjocaido.groupmanager.GroupManager;
6 | import org.anjocaido.groupmanager.data.Group;
7 | import org.anjocaido.groupmanager.data.User;
8 | import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder;
9 | import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
10 | import org.bukkit.Bukkit;
11 | import org.bukkit.entity.Player;
12 | import org.bukkit.plugin.Plugin;
13 |
14 | /**
15 | * 2013-May-03: GroupManager has a notion of a primary group (an odd notion)
16 | *
17 | */
18 | public class PermissionHandlerGroupManager extends PermissionHandler
19 | {
20 | private static GroupManager groupManager;
21 |
22 | public PermissionHandlerGroupManager() throws IllegalStateException
23 | {
24 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("GroupManager");
25 |
26 | validate(plugin, "GroupManager", "2.1.6");
27 |
28 | groupManager = (GroupManager)plugin;
29 | }
30 |
31 | @Override
32 | public boolean addToGroup(Player player, String groupName)
33 | {
34 | OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName());
35 |
36 | if (worldHolder == null)
37 | {
38 | return false;
39 | }
40 |
41 | User user = worldHolder.getUser(player.getName());
42 |
43 | if (user == null)
44 | {
45 | return false;
46 | }
47 | Group group = getOrCreateGroup(worldHolder, groupName);
48 |
49 | // If it is a primary group, set as a primary group.
50 | if (user.getGroup().equals(worldHolder.getDefaultGroup()))
51 | {
52 | user.setGroup(group, false);
53 | }
54 | else if (group.getInherits().contains(user.getGroup().getName().toLowerCase()))
55 | {
56 | user.setGroup(group, false);
57 | }
58 | else
59 | {
60 | user.addSubGroup(group);
61 | }
62 |
63 | return true;
64 | }
65 |
66 | @Override
67 | public List getGroups(Player player)
68 | {
69 | OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName());
70 |
71 | if (worldHolder == null)
72 | {
73 | return new ArrayList();
74 | }
75 |
76 | User user = worldHolder.getUser(player.getName());
77 |
78 | if (user == null)
79 | {
80 | return new ArrayList();
81 | }
82 |
83 | return user.subGroupListStringCopy();
84 | }
85 |
86 | @Override
87 | public List getGroupsPure(Player player)
88 | {
89 | return getGroups(player);
90 | }
91 |
92 | @Override
93 | public String getPrimaryGroup(Player player)
94 | {
95 | AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player));
96 |
97 | if (handler == null)
98 | {
99 | throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler");
100 | }
101 |
102 | String group = handler.getGroup(player.getName());
103 |
104 | if (group == null)
105 | {
106 | return "";
107 | }
108 | else
109 | {
110 | return group;
111 | }
112 | }
113 |
114 | @Override
115 | public boolean isMemberOfGroup(Player player, String groupName) throws RuntimeException
116 | {
117 | AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(determineWorld(player));
118 |
119 | if (handler == null)
120 | {
121 | throw new RuntimeException("isMemberOfGroup(): Failed to obtain a GroupManager permissions handler");
122 | }
123 | else
124 | {
125 | return handler.inGroup(player.getName(), groupName);
126 | }
127 | }
128 |
129 | @Override
130 | public boolean isPrimaryGroup(Player player, String groupName)
131 | {
132 | return groupName.equalsIgnoreCase(getPrimaryGroup(player));
133 | }
134 |
135 | @Override
136 | public boolean removeFromGroup(Player player, String groupName)
137 | {
138 | OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName());
139 |
140 | if (worldHolder == null)
141 | {
142 | return false;
143 | }
144 |
145 | User user = worldHolder.getUser(player.getName());
146 |
147 | if (user == null)
148 | {
149 | return false;
150 | }
151 |
152 | if (user.getGroup() != null && user.getGroup().getName().equalsIgnoreCase(groupName))
153 | {
154 | user.setGroup(worldHolder.getDefaultGroup(), false);
155 | return true;
156 | }
157 | else
158 | {
159 | Group group = getOrCreateGroup(worldHolder, groupName);
160 | return user.removeSubGroup(group);
161 | }
162 | }
163 |
164 | @Override
165 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
166 | {
167 | OverloadedWorldHolder worldHolder = groupManager.getWorldsHolder().getWorldDataByPlayerName(player.getName());
168 |
169 | if (worldHolder == null)
170 | {
171 | return false;
172 | }
173 |
174 | User user = worldHolder.getUser(player.getName());
175 |
176 | if (user == null)
177 | {
178 | return false;
179 | }
180 |
181 | Group group = getOrCreateGroup(worldHolder, groupName);
182 | user.setGroup(group, false);
183 |
184 | return true;
185 | }
186 |
187 | @Override
188 | public boolean supportsPrimaryGroups()
189 | {
190 | return true;
191 | }
192 |
193 | private Group getOrCreateGroup(OverloadedWorldHolder worldHolder, String groupName)
194 | {
195 | Group group = worldHolder.getGroup(groupName);
196 |
197 | if (group == null)
198 | {
199 | group = worldHolder.createGroup(groupName);
200 | }
201 |
202 | return group;
203 | }
204 | }
205 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsBukkit.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import com.platymuus.bukkit.permissions.Group;
4 | import com.platymuus.bukkit.permissions.PermissionsPlugin;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | import org.bukkit.Bukkit;
10 | import org.bukkit.entity.Player;
11 | import org.bukkit.plugin.Plugin;
12 |
13 | public class PermissionHandlerPermissionsBukkit extends PermissionHandler
14 | {
15 | private static PermissionsPlugin permissions;
16 |
17 | public PermissionHandlerPermissionsBukkit() throws IllegalStateException
18 | {
19 | if (permissions == null)
20 | {
21 | Plugin plugin;
22 | plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsBukkit");
23 | validate(plugin, "PermissionsBukkit", "2.3");
24 | permissions = (PermissionsPlugin) plugin;
25 | }
26 | }
27 |
28 | @Override
29 | public boolean addToGroup(Player player, String groupName)
30 | {
31 | return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player addgroup " + player.getUniqueId().toString() + " " + groupName);
32 | }
33 |
34 | @Override
35 | public List getGroups(Player player)
36 | {
37 | List groupNames = new ArrayList();
38 |
39 | for (Group group : permissions.getAllGroups())
40 | {
41 | if (isMemberOfGroup(player, group))
42 | {
43 | groupNames.add(group.getName());
44 | }
45 | }
46 |
47 | return groupNames;
48 | }
49 |
50 | @Override
51 | public List getGroupsPure(Player player)
52 | {
53 | return getGroups(player);
54 | }
55 |
56 | @Override
57 | public String getPrimaryGroup(Player player)
58 | {
59 | List groups = getGroups(player);
60 | if (groups.isEmpty())
61 | {
62 | return "";
63 | }
64 | return groups.get(0);
65 | }
66 |
67 | @Override
68 | public boolean isMemberOfGroup(Player player, String groupName)
69 | {
70 | Group group = permissions.getGroup(groupName);
71 |
72 | if (group == null)
73 | {
74 | return false;
75 | }
76 |
77 | return isMemberOfGroup(player, group);
78 | }
79 |
80 | @SuppressWarnings("deprecation")
81 | private boolean isMemberOfGroup(Player player, Group group)
82 | {
83 | return group.getPlayers().contains(player.getUniqueId().toString())
84 | ||group.getPlayers().contains(player.getName().toLowerCase());
85 | }
86 |
87 | @Override
88 | public boolean isPrimaryGroup(Player player, String groupName)
89 | {
90 | String primaryGroup = this.getPrimaryGroup(player);
91 | return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup);
92 | }
93 |
94 | @Override
95 | public boolean removeFromGroup(Player player, String groupName)
96 | {
97 | return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions player removegroup " + player.getUniqueId().toString() + " " + groupName);
98 | }
99 |
100 | /**
101 | * PermissionsBukkit doesn't have a primary group, so this calls AddToGroup.
102 | */
103 | @Override
104 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
105 | {
106 | boolean result;
107 | if (formerGroupName == null)
108 | {
109 | result = true;
110 | }
111 | else
112 | {
113 | result = removeFromGroup(player, formerGroupName);
114 | }
115 | return result && addToGroup(player, groupName);
116 | }
117 |
118 | @Override
119 | public boolean supportsPrimaryGroups()
120 | {
121 | return false;
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerPermissionsEx.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.bukkit.Bukkit;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.plugin.Plugin;
8 | import ru.tehkode.permissions.PermissionGroup;
9 | import ru.tehkode.permissions.PermissionUser;
10 | import ru.tehkode.permissions.bukkit.PermissionsEx;
11 |
12 | public class PermissionHandlerPermissionsEx extends PermissionHandler
13 | {
14 | public PermissionHandlerPermissionsEx() throws IllegalStateException
15 | {
16 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx");
17 |
18 | validate(plugin, "PermissionsEx", "1.21.4");
19 | }
20 |
21 | @Override
22 | public boolean addToGroup(Player player, String groupName)
23 | {
24 | PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName);
25 | PermissionUser user = getPermissionUser(player);
26 | if (group == null || user == null)
27 | {
28 | return false;
29 | }
30 | else
31 | {
32 | user.addGroup(group);
33 | return true;
34 | }
35 | }
36 |
37 | @Override
38 | public List getGroups(Player player)
39 | {
40 | PermissionUser permissionUser = getPermissionUser(player);
41 | if (permissionUser == null)
42 | {
43 | return new ArrayList();
44 | }
45 | return new ArrayList(permissionUser.getParentIdentifiers());
46 | }
47 |
48 | @Override
49 | public List getGroupsPure(Player player)
50 | {
51 | List groups = getGroups(player);
52 |
53 | if (groups.size() == 1 && groups.get(0).equalsIgnoreCase("default"))
54 | {
55 | return new ArrayList();
56 | }
57 |
58 | return groups;
59 | }
60 |
61 | @Override
62 | public String getPrimaryGroup(Player player)
63 | {
64 | List groups = getGroupsPure(player);
65 | if (groups.isEmpty())
66 | {
67 | return "";
68 | }
69 |
70 | return groups.get(0);
71 | }
72 |
73 | @Override
74 | public boolean isMemberOfGroup(Player player, String groupName)
75 | {
76 | PermissionUser permissionUser = getPermissionUser(player);
77 |
78 | if (permissionUser == null)
79 | {
80 | return false;
81 | }
82 |
83 | return permissionUser.inGroup(groupName, false);
84 | }
85 |
86 | @Override
87 | public boolean isPrimaryGroup(Player player, String groupName)
88 | {
89 | String primaryGroup = this.getPrimaryGroup(player);
90 | return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup);
91 | }
92 |
93 | @Override
94 | public boolean removeFromGroup(Player player, String groupName)
95 | {
96 | PermissionUser permissionUser = getPermissionUser(player);
97 | if (permissionUser == null)
98 | {
99 | return false;
100 | }
101 |
102 | permissionUser.removeGroup(groupName);
103 | return true;
104 | }
105 |
106 | @Override
107 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
108 | {
109 | boolean result;
110 | if (formerGroupName == null)
111 | {
112 | result = true;
113 | }
114 | else
115 | {
116 | result = removeFromGroup(player, formerGroupName);
117 | }
118 | return result && addToGroup(player, groupName);
119 | }
120 |
121 | @Override
122 | public boolean supportsPrimaryGroups()
123 | {
124 | return false;
125 | }
126 |
127 | private PermissionUser getPermissionUser(Player player)
128 | {
129 | PermissionUser user = PermissionsEx.getUser(player);
130 | user.getName();
131 | return user;
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerVault.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import net.milkbowl.vault.permission.Permission;
7 | import org.bukkit.Bukkit;
8 | import org.bukkit.entity.Player;
9 | import org.bukkit.plugin.Plugin;
10 | import org.bukkit.plugin.RegisteredServiceProvider;
11 |
12 | /**
13 | * 2013-July-06: As vault is a gateway to many permissions systems, most of whom
14 | * do not support the notion of a primary group, in effect,
15 | * vault does not support the notion of a primary group.
16 | */
17 | public class PermissionHandlerVault extends PermissionHandler
18 | {
19 | private static Permission vault;
20 | public PermissionHandlerVault() throws IllegalStateException
21 | {
22 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("Vault");
23 | validate(plugin, "Vault", "1.4.1");
24 | RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
25 | vault = rsp.getProvider();
26 | }
27 |
28 | @Override
29 | public boolean addToGroup(Player player, String groupName)
30 | {
31 | return vault.playerAddGroup(determineWorld(player), player, groupName);
32 | }
33 |
34 | @Override
35 | public List getGroups(Player player)
36 | {
37 | return new ArrayList(Arrays.asList(vault.getPlayerGroups(determineWorld(player), player)));
38 | }
39 |
40 | @Override
41 | public List getGroupsPure(Player player)
42 | {
43 | return getGroups(player);
44 | }
45 |
46 | @Override
47 | public String getPrimaryGroup(Player player)
48 | {
49 | throw new UnsupportedOperationException("Vault does not support primary groups.");
50 | }
51 |
52 | @Override
53 | public boolean isMemberOfGroup(Player player, String groupName)
54 | {
55 | return vault.playerInGroup(determineWorld(player), player, groupName);
56 | }
57 |
58 | @Override
59 | public boolean isPrimaryGroup(Player player, String groupName)
60 | {
61 | throw new UnsupportedOperationException("Vault does not support primary groups.");
62 | }
63 |
64 | @Override
65 | public boolean removeFromGroup(Player player, String groupName)
66 | {
67 | return vault.playerRemoveGroup(determineWorld(player), player, groupName);
68 | }
69 |
70 | @Override
71 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
72 | {
73 | throw new UnsupportedOperationException("Vault does not support setting a primary group.");
74 | }
75 |
76 | @Override
77 | public boolean supportsPrimaryGroups()
78 | {
79 | return false;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/permissionhandlers/PermissionHandlerZPermissions.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.bukkit.Bukkit;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.plugin.Plugin;
8 | import org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService;
9 |
10 | public class PermissionHandlerZPermissions extends PermissionHandler
11 | {
12 | private ZPermissionsService service;
13 |
14 | public PermissionHandlerZPermissions() throws IllegalStateException
15 | {
16 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("zPermissions");
17 | validate(plugin, "zPermissions", "1.3");
18 | service = Bukkit.getServer().getServicesManager().load(ZPermissionsService.class);
19 |
20 | if (service == null)
21 | {
22 | throw new IllegalStateException("zPermissions service class load failed.");
23 | }
24 | }
25 |
26 | @Override
27 | public boolean addToGroup(Player player, String groupName)
28 | {
29 | return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions group " + groupName + " add " + player.getUniqueId().toString());
30 | }
31 |
32 | @Override
33 | public List getGroups(Player player)
34 | {
35 | return new ArrayList(service.getPlayerGroups(player.getUniqueId()));
36 | }
37 |
38 | @Override
39 | public List getGroupsPure(Player player)
40 | {
41 | return getGroups(player);
42 | }
43 |
44 | @Override
45 | public String getPrimaryGroup(Player player)
46 | {
47 | return service.getPlayerPrimaryGroup(player.getUniqueId());
48 | }
49 |
50 | @Override
51 | public boolean isMemberOfGroup(Player player, String groupName)
52 | {
53 | List groups = getGroups(player);
54 |
55 | return groups.contains(groupName);
56 | }
57 |
58 | @Override
59 | public boolean isPrimaryGroup(Player player, String groupName)
60 | {
61 | String primaryGroup = this.getPrimaryGroup(player);
62 | return primaryGroup != null && groupName.equalsIgnoreCase(primaryGroup);
63 | }
64 |
65 | @Override
66 | public boolean removeFromGroup(Player player, String groupName)
67 | {
68 | return Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "permissions group " + groupName + " remove " + player.getUniqueId().toString());
69 | }
70 |
71 | @Override
72 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
73 | {
74 | boolean result;
75 | if (formerGroupName == null)
76 | {
77 | result = true;
78 | }
79 | else
80 | {
81 | result = removeFromGroup(player, formerGroupName);
82 | }
83 | return result && addToGroup(player, groupName);
84 | }
85 |
86 | @Override
87 | public boolean supportsPrimaryGroups()
88 | {
89 | return false;
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/MoneySynchronizer.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.net.MalformedURLException;
4 | import net.milkbowl.vault.economy.Economy;
5 | import org.bukkit.entity.Player;
6 | import org.communitybridge.main.Environment;
7 | import org.communitybridge.synchronization.dao.MoneyDao;
8 |
9 | public class MoneySynchronizer extends Synchronizer implements PlayerSynchronizer
10 | {
11 | private MoneyDao money = new MoneyDao();
12 |
13 | MoneySynchronizer(Environment environment)
14 | {
15 | super(environment);
16 | }
17 |
18 | @Override
19 | public boolean isActive(Environment environment)
20 | {
21 | return environment.getConfiguration().walletEnabled;
22 | }
23 |
24 | @Override
25 | public PlayerState synchronize(Environment environment, Player player, String userId, PlayerState previous, PlayerState current, PlayerState result)
26 | {
27 | result = synchronizeGameToWeb(environment, previous, current, result, userId);
28 | return synchronizeWebToGame(environment.getEconomy(), previous, current, result, player);
29 | }
30 |
31 | private PlayerState synchronizeGameToWeb(Environment environment, PlayerState previous, PlayerState current, PlayerState result, String userId)
32 | {
33 | double change = current.getMinecraftWallet() - previous.getMinecraftWallet();
34 | double amount = current.getWebApplicationWallet() + change;
35 | result.setWebApplicationWallet(amount);
36 | if (change != 0)
37 | {
38 | try
39 | {
40 | money.setBalance(environment, userId, amount);
41 | }
42 | catch (IllegalAccessException exception)
43 | {
44 | environment.getLog().severe("Exception updating web application money" + exception.getMessage());
45 | }
46 | catch (InstantiationException exception)
47 | {
48 | environment.getLog().severe("Exception updating web application money" + exception.getMessage());
49 | }
50 | catch (MalformedURLException exception)
51 | {
52 | environment.getLog().severe("Exception updating web application money" + exception.getMessage());
53 | }
54 | }
55 | return result;
56 | }
57 |
58 | private PlayerState synchronizeWebToGame(Economy economy, PlayerState previous, PlayerState current, PlayerState result, Player player)
59 | {
60 | double change = current.getWebApplicationWallet() - previous.getWebApplicationWallet();
61 | double amount = current.getMinecraftWallet() + change;
62 | result.setMinecraftWallet(amount);
63 | /*
64 | System.out.println("&cCurrent: "+current.getMinecraftWallet());
65 | System.out.println("&cPrevious: "+previous.getMinecraftWallet());
66 | System.out.println("&cChange: "+change);
67 | System.out.println("&cAmount: "+amount);
68 | */
69 | if (change > 0)
70 | {
71 | economy.depositPlayer(player, change);
72 | }
73 | else if (change < 0)
74 | {
75 | economy.withdrawPlayer(player, Math.abs(change));
76 | }
77 |
78 | return result;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/PlayerFileFetcher.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.io.File;
4 | import org.bukkit.entity.Player;
5 |
6 | public class PlayerFileFetcher
7 | {
8 | private File folder;
9 | private File playerFile;
10 |
11 | public File getPlayerFile(File dataFolder, Player player, boolean allowOldFile)
12 | {
13 | folder = makeFile(dataFolder, "Players");
14 | playerFile = makeFile(folder, player.getUniqueId().toString() + ".yml");
15 | if (!playerFile.exists() && allowOldFile)
16 | {
17 | return new File(folder, player.getName() + ".yml");
18 | }
19 | return playerFile;
20 | }
21 |
22 | File makeFile(File folder, String filename)
23 | {
24 | return new File(folder, filename);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/PlayerState.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.net.MalformedURLException;
6 | import java.sql.SQLException;
7 | import java.util.ArrayList;
8 | import java.util.List;
9 | import org.bukkit.configuration.file.FileConfiguration;
10 | import org.bukkit.configuration.file.YamlConfiguration;
11 | import org.bukkit.entity.Player;
12 | import org.communitybridge.main.Environment;
13 | import org.communitybridge.synchronization.dao.MoneyDao;
14 | import org.communitybridge.utility.Log;
15 |
16 | public class PlayerState
17 | {
18 | private String webappPrimaryGroupID = "";
19 | private List webappGroupIDs = new ArrayList();
20 |
21 | private String permissionsSystemPrimaryGroupName = "";
22 | private List permissionsSystemGroupNames= new ArrayList();
23 |
24 | private double minecraftWallet = 0;
25 | private double webApplicationWallet = 0;
26 |
27 | private boolean isNewFile;
28 |
29 | private FileConfiguration playerData = new YamlConfiguration();
30 | private MoneyDao money = new MoneyDao();
31 |
32 | public void generate(Environment environment, Player player, String userId) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
33 | {
34 | if (environment.getConfiguration().economyEnabled && environment.getConfiguration().walletEnabled)
35 | {
36 | minecraftWallet = environment.getEconomy().getBalance(player);
37 | webApplicationWallet = money.getBalance(environment, userId);
38 | }
39 | if (environment.getConfiguration().groupSynchronizationActive)
40 | {
41 | permissionsSystemGroupNames = environment.getPermissionHandler().getGroups(player);
42 | permissionsSystemPrimaryGroupName = getPrimaryGroupName(player, environment);
43 | if (environment.getConfiguration().webappSecondaryGroupEnabled)
44 | {
45 | webappGroupIDs = environment.getWebApplication().getUserSecondaryGroupIDs(userId);
46 | }
47 | if (environment.getConfiguration().webappPrimaryGroupEnabled)
48 | {
49 | webappPrimaryGroupID = environment.getWebApplication().getUserPrimaryGroupID(userId);
50 | }
51 | }
52 | }
53 |
54 | public void load(File file, double def)
55 | {
56 | if (file.exists())
57 | {
58 | playerData = YamlConfiguration.loadConfiguration(file);
59 | minecraftWallet = playerData.getDouble("minecraft-money", def);
60 | webApplicationWallet = playerData.getDouble("web-application-money", def);
61 | permissionsSystemGroupNames = playerData.getStringList("permissions-system.group-names");
62 | permissionsSystemPrimaryGroupName = playerData.getString("permissions-system.primary-group-name", "");
63 | webappGroupIDs = playerData.getStringList("webapp.group-ids");
64 | webappPrimaryGroupID = playerData.getString("webapp.primary-group-id", "");
65 | isNewFile = false;
66 | }
67 | else
68 | {
69 | isNewFile = true;
70 | minecraftWallet = def;
71 | webApplicationWallet = def;
72 | permissionsSystemGroupNames = new ArrayList();
73 | permissionsSystemPrimaryGroupName = "";
74 | webappPrimaryGroupID = "";
75 | webappGroupIDs = new ArrayList();
76 | }
77 | }
78 |
79 | public void save(Player player, File file, Log log)
80 | {
81 | playerData.set("last-known-name", player.getName());
82 | playerData.set("minecraft-money", minecraftWallet);
83 | playerData.set("web-application-money", webApplicationWallet);
84 | playerData.set("permissions-system.primary-group-name", permissionsSystemPrimaryGroupName);
85 | playerData.set("permissions-system.group-names", permissionsSystemGroupNames);
86 | playerData.set("webapp.primary-group-id", webappPrimaryGroupID);
87 | playerData.set("webapp.group-ids", webappGroupIDs);
88 |
89 | try
90 | {
91 | playerData.save(file);
92 | }
93 | catch (IOException exception)
94 | {
95 | log.severe("Exception while saving player state for " + player.getName() + ": " + exception.getMessage());
96 | }
97 | }
98 |
99 | public PlayerState copy()
100 | {
101 | PlayerState copy = new PlayerState();
102 | copy.isNewFile = isNewFile;
103 | copy.setMinecraftWallet(minecraftWallet);
104 | copy.setWebApplicationWallet(webApplicationWallet);
105 | copy.setPermissionsSystemGroupNames(permissionsSystemGroupNames);
106 | copy.setPermissionsSystemPrimaryGroupName(permissionsSystemPrimaryGroupName);
107 | copy.setWebappGroupIDs(webappGroupIDs);
108 | copy.setWebappPrimaryGroupID(webappPrimaryGroupID);
109 | return copy;
110 | }
111 |
112 | public String getWebappPrimaryGroupID()
113 | {
114 | return webappPrimaryGroupID;
115 | }
116 |
117 | public void setWebappPrimaryGroupID(String webappPrimaryGroupID)
118 | {
119 | this.webappPrimaryGroupID = webappPrimaryGroupID;
120 | }
121 |
122 | public List getWebappGroupIDs()
123 | {
124 | return webappGroupIDs;
125 | }
126 |
127 | public void setWebappGroupIDs(List webappGroupIDs)
128 | {
129 | this.webappGroupIDs = webappGroupIDs;
130 | }
131 |
132 | public String getPermissionsSystemPrimaryGroupName()
133 | {
134 | return permissionsSystemPrimaryGroupName;
135 | }
136 |
137 | public void setPermissionsSystemPrimaryGroupName(String permissionsSystemPrimaryGroupName)
138 | {
139 | this.permissionsSystemPrimaryGroupName = permissionsSystemPrimaryGroupName;
140 | }
141 |
142 | public List getPermissionsSystemGroupNames()
143 | {
144 | return permissionsSystemGroupNames;
145 | }
146 |
147 | public void setPermissionsSystemGroupNames(List permissionsSystemGroupNames)
148 | {
149 | this.permissionsSystemGroupNames = permissionsSystemGroupNames;
150 | }
151 |
152 | public boolean isIsNewFile()
153 | {
154 | return isNewFile;
155 | }
156 |
157 | public double getMinecraftWallet()
158 | {
159 | return minecraftWallet;
160 | }
161 |
162 | public void setMinecraftWallet(double wallet)
163 | {
164 | this.minecraftWallet = wallet;
165 | }
166 |
167 | public double getWebApplicationWallet()
168 | {
169 | return webApplicationWallet;
170 | }
171 |
172 | public void setWebApplicationWallet(double wallet)
173 | {
174 | this.webApplicationWallet = wallet;
175 | }
176 |
177 | private String getPrimaryGroupName(Player player, Environment environment)
178 | {
179 | if (environment.getPermissionHandler().supportsPrimaryGroups())
180 | {
181 | return environment.getPermissionHandler().getPrimaryGroup(player);
182 | }
183 | else
184 | {
185 | for (String groupName : environment.getConfiguration().simpleSynchronizationGroupsTreatedAsPrimary)
186 | {
187 | if (permissionsSystemGroupNames.contains(groupName))
188 | {
189 | permissionsSystemGroupNames.remove(groupName);
190 | return groupName;
191 | }
192 | }
193 | return "";
194 | }
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/PlayerSynchronizationDispatcher.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.io.File;
4 | import java.net.MalformedURLException;
5 | import java.sql.SQLException;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 | import org.bukkit.entity.Player;
9 | import org.communitybridge.main.Environment;
10 |
11 | public class PlayerSynchronizationDispatcher
12 | {
13 | private static final String SYNCHRONIZATION_EXCEPTION = "Exception occurred during synchronization: ";
14 | private final Boolean synchronizationLock = true;
15 | private List playerLocks = new ArrayList();
16 | private PlayerState previous = new PlayerState();
17 | private PlayerState current = new PlayerState();
18 | private PlayerState result = new PlayerState();
19 | private MoneySynchronizer moneySynchronizer = new MoneySynchronizer(null);
20 |
21 | public void synchronize(Environment environment)
22 | {
23 | environment.getLog().finest("Running player synchronization.");
24 | for (Player player : environment.getBukkit().getOnlinePlayers())
25 | {
26 | synchronizePlayer(environment, player, true);
27 | }
28 | environment.getLog().finest("Player synchronization complete.");
29 | }
30 |
31 | public void synchronizePlayer(Environment environment, Player player, boolean online)
32 | {
33 | if (!playerLocks.contains(player))
34 | {
35 | String userID = environment.getUserPlayerLinker().getUserID(player);
36 | if (userID == null)
37 | {
38 | return;
39 | }
40 | synchronized (synchronizationLock) { playerLocks.add(player);}
41 | playerStateBaseSynchronization(environment, player, userID);
42 | if (environment.getConfiguration().statisticsEnabled)
43 | {
44 | environment.getWebApplication().updateStatistics(player, online);
45 | }
46 | if (environment.getConfiguration().useAchievements)
47 | {
48 | environment.getWebApplication().rewardAchievements(player);
49 | }
50 | synchronized (synchronizationLock) { playerLocks.remove(player); }
51 | }
52 | }
53 |
54 | private void playerStateBaseSynchronization(Environment environment, Player player, String userID)
55 | {
56 | try
57 | {
58 | PlayerFileFetcher fetcher = new PlayerFileFetcher();
59 | File playerFile = fetcher.getPlayerFile(environment.getPlugin().getDataFolder(), player, true);
60 |
61 | current.generate(environment, player, userID);
62 | previous.load(playerFile, current.getMinecraftWallet());
63 | result = current.copy();
64 |
65 | if (environment.getConfiguration().groupSynchronizationActive)
66 | {
67 | result = environment.getWebApplication().synchronizeGroups(player, userID, previous, current, result);
68 | }
69 | if (moneySynchronizer.isActive(environment))
70 | {
71 | result = moneySynchronizer.synchronize(environment, player, userID, previous, current, result);
72 | }
73 | if (environment.getConfiguration().groupSynchronizationActive || moneySynchronizer.isActive(environment))
74 | {
75 | playerFile = fetcher.getPlayerFile(environment.getPlugin().getDataFolder(), player, false);
76 | result.save(player, playerFile, environment.getLog());
77 | }
78 | }
79 | catch (InstantiationException exception)
80 | {
81 | environment.getLog().severe(SYNCHRONIZATION_EXCEPTION + exception.getMessage());
82 | }
83 | catch (IllegalAccessException exception)
84 | {
85 | environment.getLog().severe(SYNCHRONIZATION_EXCEPTION + exception.getMessage());
86 | }
87 | catch (MalformedURLException exception)
88 | {
89 | environment.getLog().severe(SYNCHRONIZATION_EXCEPTION + exception.getMessage());
90 | }
91 | catch (SQLException exception)
92 | {
93 | environment.getLog().severe(SYNCHRONIZATION_EXCEPTION + exception.getMessage());
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/PlayerSynchronizer.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import org.bukkit.entity.Player;
4 | import org.communitybridge.main.Environment;
5 |
6 | public interface PlayerSynchronizer
7 | {
8 | PlayerState synchronize(Environment environment, Player player, String userID, PlayerState previous, PlayerState current, PlayerState result);
9 |
10 | boolean isActive(Environment environment);
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/Synchronizer.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import org.communitybridge.main.Environment;
4 |
5 | public class Synchronizer
6 | {
7 | protected Environment environment;
8 |
9 | public Synchronizer(Environment environment)
10 | {
11 | this.environment = environment;
12 | }
13 |
14 | protected boolean isValidDirection(String direction, String validDirection)
15 | {
16 | return direction.startsWith("two") || direction.startsWith(validDirection);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/ban/BanState.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.ban;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.net.MalformedURLException;
6 | import java.sql.ResultSet;
7 | import java.sql.SQLException;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import org.bukkit.OfflinePlayer;
11 | import org.bukkit.configuration.file.FileConfiguration;
12 | import org.bukkit.configuration.file.YamlConfiguration;
13 | import org.communitybridge.main.BukkitWrapper;
14 | import org.communitybridge.main.Environment;
15 |
16 | public class BanState
17 | {
18 | private Environment environment;
19 | private File file;
20 | private BukkitWrapper bukkit;
21 | private List bannedUUIDs = new ArrayList();
22 | private List bannedUserIDs = new ArrayList();
23 |
24 | public BanState(Environment environment)
25 | {
26 | this.environment = environment;
27 | this.file = new File(environment.getPlugin().getDataFolder(), "banstate.yml");
28 | this.bukkit = new BukkitWrapper();
29 | }
30 |
31 | public void generate()
32 | {
33 | collectGameBans();
34 | collectWebBans();
35 | }
36 |
37 | public void load()
38 | {
39 | bannedUserIDs.clear();
40 | bannedUUIDs.clear();
41 | if (file.exists())
42 | {
43 | FileConfiguration banData = YamlConfiguration.loadConfiguration(file);
44 | bannedUserIDs = banData.getStringList("banned-user-ids");
45 | bannedUUIDs = banData.getStringList("banned-uuids");
46 |
47 | convertNamesIfNeeded(banData);
48 | }
49 | }
50 |
51 | public void save() throws IOException
52 | {
53 | FileConfiguration banData = new YamlConfiguration();
54 | banData.set("banned-user-ids", bannedUserIDs);
55 | banData.set("banned-uuids", bannedUUIDs);
56 | banData.set("ban-file-version", "2");
57 | banData.save(file);
58 | }
59 |
60 | private void collectGameBans()
61 | {
62 | bannedUUIDs.clear();
63 | for (OfflinePlayer player : bukkit.getServer().getBannedPlayers())
64 | {
65 | bannedUUIDs.add(player.getPlayer().getUniqueId().toString());
66 | }
67 | }
68 |
69 | private void collectWebBans()
70 | {
71 | bannedUserIDs.clear();
72 | if (environment.getConfiguration().banSynchronizationMethod.startsWith("tab"))
73 | {
74 | collectWebBansTableMethod();
75 | }
76 | else if (environment.getConfiguration().banSynchronizationMethod.startsWith("use"))
77 | {
78 | collectWebBansUserMethod();
79 | }
80 | else if (environment.getConfiguration().banSynchronizationMethod.startsWith("gro"))
81 | {
82 | collectWebBansGroupMethod(environment.getConfiguration().banSynchronizationBanGroup);
83 | }
84 | }
85 |
86 | private void collectWebBansTableMethod()
87 | {
88 | String exceptionBase = "Exception in collectWebBans: ";
89 | String query = "SELECT * FROM `" + environment.getConfiguration().banSynchronizationTableName + "`";
90 |
91 | try
92 | {
93 | ResultSet result = environment.getSql().sqlQuery(query);
94 | while(result.next())
95 | {
96 | bannedUserIDs.add(result.getString(environment.getConfiguration().banSynchronizationUserIDColumn));
97 | }
98 | }
99 | catch (MalformedURLException exception)
100 | {
101 | environment.getLog().severe(exceptionBase + exception.getMessage());
102 | }
103 | catch (InstantiationException exception)
104 | {
105 | environment.getLog().severe(exceptionBase + exception.getMessage());
106 | }
107 | catch (IllegalAccessException exception)
108 | {
109 | environment.getLog().severe(exceptionBase + exception.getMessage());
110 | }
111 | catch (SQLException exception)
112 | {
113 | environment.getLog().severe(exceptionBase + exception.getMessage());
114 | }
115 | }
116 |
117 | public List getBannedUUIDs()
118 | {
119 | return bannedUUIDs;
120 | }
121 |
122 | public void setBannedUUIDs(List bannedUUIDs)
123 | {
124 | this.bannedUUIDs = bannedUUIDs;
125 | }
126 |
127 | public List getBannedUserIDs()
128 | {
129 | return bannedUserIDs;
130 | }
131 |
132 | public void setBannedUserIDs(List bannedUserIDs)
133 | {
134 | this.bannedUserIDs = bannedUserIDs;
135 | }
136 |
137 | private void collectWebBansGroupMethod(String groupID)
138 | {
139 | environment.getWebApplication().getWebGroupDao().getGroupUserIDs(groupID);
140 | }
141 |
142 | private void collectWebBansUserMethod()
143 | {
144 | String exceptionBase = "Exception in collectWebBansUser: ";
145 | String query = "SELECT * FROM `" + environment.getConfiguration().banSynchronizationTableName + "` "
146 | + "WHERE `" + environment.getConfiguration().banSynchronizationBanColumn + "` = '" + environment.getConfiguration().banSynchronizationValueBanned + "'";
147 |
148 | try
149 | {
150 | ResultSet result = environment.getSql().sqlQuery(query);
151 |
152 | while(result.next())
153 | {
154 | bannedUserIDs.add(result.getString(environment.getConfiguration().banSynchronizationUserIDColumn));
155 | }
156 | }
157 | catch (MalformedURLException exception)
158 | {
159 | environment.getLog().severe(exceptionBase + exception.getMessage());
160 | }
161 | catch (InstantiationException exception)
162 | {
163 | environment.getLog().severe(exceptionBase + exception.getMessage());
164 | }
165 | catch (IllegalAccessException exception)
166 | {
167 | environment.getLog().severe(exceptionBase + exception.getMessage());
168 | }
169 | catch (SQLException exception)
170 | {
171 | environment.getLog().severe(exceptionBase + exception.getMessage());
172 | }
173 | }
174 |
175 | private void convertNamesIfNeeded(FileConfiguration banData)
176 | {
177 | String version = banData.getString("ban-file-version", "");
178 | if (version.isEmpty())
179 | {
180 | List names = banData.getStringList("banned-player-names");
181 | for (String name : names)
182 | {
183 | bannedUUIDs.add(bukkit.getOfflinePlayer(name).getUniqueId().toString());
184 | }
185 | }
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/ban/BanSynchronizer.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.ban;
2 |
3 | import java.io.IOException;
4 | import java.net.MalformedURLException;
5 | import java.sql.SQLException;
6 | import java.util.UUID;
7 | import org.bukkit.BanList;
8 | import org.bukkit.OfflinePlayer;
9 | import org.bukkit.entity.Player;
10 | import org.communitybridge.main.BukkitWrapper;
11 | import org.communitybridge.main.Configuration;
12 | import org.communitybridge.main.Environment;
13 | import org.communitybridge.synchronization.Synchronizer;
14 | import org.communitybridge.utility.Log;
15 |
16 | public class BanSynchronizer extends Synchronizer
17 | {
18 | private Configuration configuration;
19 | private Log log;
20 |
21 | private BukkitWrapper bukkit;
22 |
23 | public BanSynchronizer(Environment environment)
24 | {
25 | super(environment);
26 | this.configuration = environment.getConfiguration();
27 | this.log = environment.getLog();
28 | this.bukkit = new BukkitWrapper();
29 | }
30 |
31 | public void synchronize()
32 | {
33 | BanState previous = new BanState(environment);
34 | previous.load();
35 |
36 | BanState current = new BanState(environment);
37 | current.generate();
38 |
39 | if (isValidDirection(configuration.banSynchronizationDirection, "web"))
40 | {
41 | synchronizeWebToGame(previous, current);
42 | }
43 |
44 | if (isValidDirection(configuration.banSynchronizationDirection, "min"))
45 | {
46 | synchronizeGameToWeb(previous, current);
47 | }
48 |
49 | current.generate();
50 |
51 | try
52 | {
53 | current.save();
54 | }
55 | catch (IOException exception)
56 | {
57 | log.severe("Error while saving ban synchronization state: " + exception.getMessage());
58 | }
59 | }
60 |
61 | private void unbanPlayerGame(String uuid)
62 | {
63 | OfflinePlayer playerOffline = bukkit.getOfflinePlayer(UUID.fromString(uuid));
64 | bukkit.getBanList(BanList.Type.NAME).pardon(playerOffline.getName());
65 | }
66 |
67 | private void banPlayerGame(String uuidString)
68 | {
69 | UUID uuid = UUID.fromString(uuidString);
70 |
71 | Player player = bukkit.getPlayer(uuid);
72 | if (player == null)
73 | {
74 | player = bukkit.getOfflinePlayer(uuid).getPlayer();
75 | }
76 |
77 | bukkit.getBanList(BanList.Type.NAME).addBan(player.getName(), "banned by CommunityBridge synchronization", null, "");
78 | player.kickPlayer("Banned via forums.");
79 | }
80 |
81 | private void unbanPlayerWeb(String userID)
82 | {
83 | if (configuration.banSynchronizationMethod.startsWith("tab"))
84 | {
85 | unbanPlayerWebTable(userID);
86 | }
87 | else if (configuration.banSynchronizationMethod.startsWith("use"))
88 | {
89 | unbanPlayerWebUser(userID);
90 | }
91 | }
92 |
93 | private void banPlayerWeb(String userID)
94 | {
95 | if (configuration.banSynchronizationMethod.startsWith("tab"))
96 | {
97 | banPlayerWebTable(userID);
98 | }
99 | else if (configuration.banSynchronizationMethod.startsWith("use"))
100 | {
101 | banPlayerWebUser(userID);
102 | }
103 | }
104 |
105 | private void banPlayerWebUser(String userID)
106 | {
107 | String errorBase = "Error during banPlayerWebUser: ";
108 | String query = "UPDATE `" + configuration.banSynchronizationTableName + "` "
109 | + "SET `" + configuration.banSynchronizationBanColumn + "` = '" + configuration.banSynchronizationValueBanned + "' "
110 | + "WHERE `" + configuration.banSynchronizationUserIDColumn + "` = '" + userID + "'";
111 |
112 | try
113 | {
114 | environment.getSql().updateQuery(query);
115 | }
116 | catch (MalformedURLException exception)
117 | {
118 | log.severe(errorBase + exception.getMessage());
119 | }
120 | catch (InstantiationException exception)
121 | {
122 | log.severe(errorBase + exception.getMessage());
123 | }
124 | catch (IllegalAccessException exception)
125 | {
126 | log.severe(errorBase + exception.getMessage());
127 | }
128 | }
129 |
130 | private void unbanPlayerWebUser(String userID)
131 | {
132 | String errorBase = "Error during unbanPlayerWebUser: ";
133 | String query = "UPDATE `" + configuration.banSynchronizationTableName + "` "
134 | + "SET `" + configuration.banSynchronizationBanColumn + "` = '" + configuration.banSynchronizationValueNotBanned + "' "
135 | + "WHERE `" + configuration.banSynchronizationUserIDColumn + "` = '" + userID + "'";
136 |
137 | try
138 | {
139 | environment.getSql().updateQuery(query);
140 | }
141 | catch (MalformedURLException exception)
142 | {
143 | log.severe(errorBase + exception.getMessage());
144 | }
145 | catch (InstantiationException exception)
146 | {
147 | log.severe(errorBase + exception.getMessage());
148 | }
149 | catch (IllegalAccessException exception)
150 | {
151 | log.severe(errorBase + exception.getMessage());
152 | }
153 | }
154 |
155 | private void banPlayerWebTable(String userID)
156 | {
157 | String errorBase = "Error during banPlayerWebTable: ";
158 | String columns = "`" + configuration.banSynchronizationUserIDColumn + "`, ";
159 | String values = userID + ", ";
160 |
161 | if (!configuration.banSynchronizationReasonColumn.isEmpty())
162 | {
163 | columns = columns + "`" + configuration.banSynchronizationReasonColumn + "`, ";
164 | values = values + "'banned via minecraft server', ";
165 | }
166 | if (!configuration.banSynchronizationStartTimeColumn.isEmpty())
167 | {
168 | columns = columns + "`" + configuration.banSynchronizationStartTimeColumn + "`, ";
169 | values = values + (System.currentTimeMillis() / 1000) + ", ";
170 | }
171 | if (!configuration.banSynchronizationEndTimeColumn.isEmpty())
172 | {
173 | columns = columns + "`" + configuration.banSynchronizationEndTimeColumn + "`, ";
174 | values = values + "2147483647, ";
175 | }
176 | if (!configuration.banSynchronizationBanGroupIDColumn.isEmpty() && !configuration.banSynchronizationBanGroupID.isEmpty())
177 | {
178 | columns = columns + "`" + configuration.banSynchronizationBanGroupIDColumn + "`, ";
179 | values = values + "'" + configuration.banSynchronizationBanGroupID + "', ";
180 | }
181 |
182 | columns = columns.substring(0, columns.length() - 2);
183 | values = values.substring(0, values.length() - 2);
184 | String query = "INSERT INTO `" + configuration.banSynchronizationTableName + "` (" + columns + ") " + "VALUES (" + values + ")";
185 |
186 | try
187 | {
188 | environment.getSql().insertQuery(query);
189 | }
190 | catch (MalformedURLException exception)
191 | {
192 | log.severe(errorBase + exception.getMessage());
193 | }
194 | catch (InstantiationException exception)
195 | {
196 | log.severe(errorBase + exception.getMessage());
197 | }
198 | catch (IllegalAccessException exception)
199 | {
200 | log.severe(errorBase + exception.getMessage());
201 | }
202 | catch (SQLException exception)
203 | {
204 | log.severe(errorBase + exception.getMessage());
205 | }
206 | }
207 |
208 | private void unbanPlayerWebTable(String userID)
209 | {
210 | String errorBase = "Error during unbanPlayerWebTable: ";
211 | String query = "DELETE FROM `" + configuration.banSynchronizationTableName
212 | + "` WHERE `" + configuration.banSynchronizationUserIDColumn + "` = '" + userID + "'";
213 |
214 | try
215 | {
216 | environment.getSql().deleteQuery(query);
217 | }
218 | catch (MalformedURLException exception)
219 | {
220 | log.severe(errorBase + exception.getMessage());
221 | }
222 | catch (InstantiationException exception)
223 | {
224 | log.severe(errorBase + exception.getMessage());
225 | }
226 | catch (IllegalAccessException exception)
227 | {
228 | log.severe(errorBase + exception.getMessage());
229 | }
230 | }
231 |
232 | private void synchronizeWebToGame(BanState previous, BanState current)
233 | {
234 | for (String userID : previous.getBannedUserIDs())
235 | {
236 | if (!current.getBannedUserIDs().contains(userID))
237 | {
238 | unbanPlayerGame(environment.getUserPlayerLinker().getPlayerName(userID));
239 | }
240 | }
241 |
242 | for (String userID : current.getBannedUserIDs())
243 | {
244 | if (!previous.getBannedUserIDs().contains(userID))
245 | {
246 | banPlayerGame(environment.getUserPlayerLinker().getPlayerName(userID));
247 | }
248 | }
249 | }
250 |
251 | private void synchronizeGameToWeb(BanState previous, BanState current)
252 | {
253 | for (String uuid : previous.getBannedUUIDs())
254 | {
255 | if (!current.getBannedUUIDs().contains(uuid))
256 | {
257 | unbanPlayerWeb(environment.getUserPlayerLinker().getUserID(uuid));
258 | }
259 | }
260 |
261 | for (String uuid : current.getBannedUUIDs())
262 | {
263 | if (!previous.getBannedUUIDs().contains(uuid))
264 | {
265 | banPlayerWeb(environment.getUserPlayerLinker().getUserID(uuid));
266 | }
267 | }
268 | }
269 | }
270 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/JunctionWebGroupDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.SQLException;
5 | import java.util.ArrayList;
6 | import java.util.List;
7 | import java.util.Map.Entry;
8 |
9 | import org.communitybridge.main.Environment;
10 |
11 | public class JunctionWebGroupDao extends WebGroupDao
12 | {
13 | public static final String EXCEPTION_MESSAGE_GETSECONDARY = "Error during WebApplication.getUserGroupIDsJunction(): ";
14 |
15 | public JunctionWebGroupDao(Environment environment)
16 | {
17 | super(environment);
18 | }
19 |
20 | @SuppressWarnings("rawtypes")
21 | @Override
22 | public void addUserToGroup(String userID, String groupID, int currentGroupCount) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
23 | {
24 | String columns = "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn;
25 | String values = "VALUES ('" + userID + "', '" + groupID;
26 |
27 | for (Entry entry : configuration.webappSecondaryAdditionalColumns.entrySet())
28 | {
29 | columns = columns + "`, `" + entry.getKey();
30 | values = values + "', '" + entry.getValue();
31 | }
32 |
33 | columns = columns + "`) ";
34 | values = values + "')";
35 |
36 | String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` " + columns + values;
37 | sql.insertQuery(query);
38 | }
39 |
40 | @Override
41 | public void removeUserFromGroup(String userID, String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
42 | {
43 | String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` "
44 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' "
45 | + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' ";
46 | sql.deleteQuery(query);
47 | }
48 |
49 | @Override
50 | public List getSecondaryGroupIDs(String userID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
51 | {
52 | List groupIDs = new ArrayList();
53 | String query = "SELECT `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
54 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
55 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' ";
56 |
57 | result = sql.sqlQuery(query);
58 |
59 | while (result.next())
60 | {
61 | addCleanID(result.getString(configuration.webappSecondaryGroupGroupIDColumn), groupIDs);
62 | }
63 | return groupIDs;
64 | }
65 |
66 | @Override
67 | public List getSecondaryGroupUserIDs(String groupID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
68 | {
69 | List userIDs = new ArrayList();
70 |
71 | String query =
72 | "SELECT `" + configuration.webappSecondaryGroupUserIDColumn + "` "
73 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
74 | + "WHERE `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' ";
75 |
76 | result = sql.sqlQuery(query);
77 |
78 | while (result.next())
79 | {
80 | addCleanID(result.getString(configuration.webappSecondaryGroupUserIDColumn), userIDs);
81 | }
82 | return userIDs;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/KeyValueWebGroupDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.SQLException;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import org.communitybridge.main.Environment;
9 | import org.communitybridge.utility.StringUtilities;
10 |
11 | public class KeyValueWebGroupDao extends WebGroupDao
12 | {
13 | public static final String EXCEPTION_MESSAGE_GETSECONDARY = "Exception during KeyValueWebGroupDao.getSecondaryGroups(): ";
14 |
15 | public KeyValueWebGroupDao(Environment environment)
16 | {
17 | super(environment);
18 | }
19 |
20 | @Override
21 | public void addUserToGroup(String userID, String groupID, int currentGroupCount) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
22 | {
23 | result = sql.sqlQuery(getSecondaryGroupReadQuery(userID));
24 |
25 | if (result.next())
26 | {
27 | List groupIDs = getGroupIDsFromResult();
28 | groupIDs.add(groupID);
29 | sql.updateQuery(getGroupIDsUpdateQuery(groupIDs, userID));
30 | }
31 | else
32 | {
33 | sql.insertQuery(getGroupIDInsertQuery(userID, groupID));
34 | }
35 | }
36 |
37 | @Override
38 | public void removeUserFromGroup(String userID, String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
39 | {
40 | result = sql.sqlQuery(getSecondaryGroupReadQuery(userID));
41 |
42 | if (result.next())
43 | {
44 | List groupIDs = getGroupIDsFromResult();
45 | groupIDs.remove(groupID);
46 | sql.updateQuery(getGroupIDsUpdateQuery(groupIDs, userID));
47 | }
48 | }
49 |
50 | protected List getGroupIDsFromResult() throws SQLException
51 | {
52 | List groupIDs = new ArrayList();
53 | String groupIDString = result.getString(configuration.webappSecondaryGroupGroupIDColumn);
54 |
55 | if (groupIDString == null)
56 | {
57 | return groupIDs;
58 | }
59 |
60 | groupIDString = groupIDString.trim();
61 |
62 | if (groupIDString.isEmpty())
63 | {
64 | return groupIDs;
65 | }
66 |
67 | groupIDs.addAll(Arrays.asList(groupIDString.split(configuration.webappSecondaryGroupGroupIDDelimiter)));
68 | return groupIDs;
69 | }
70 |
71 | protected String getSecondaryGroupReadQuery(String userID)
72 | {
73 | return "SELECT `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
74 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
75 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' "
76 | + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' ";
77 | }
78 |
79 | protected String getGroupIDsUpdateQuery(List groupIDs, String userID)
80 | {
81 | String groupIDString = StringUtilities.joinStrings(groupIDs, configuration.webappSecondaryGroupGroupIDDelimiter);
82 | return "UPDATE `" + configuration.webappSecondaryGroupTable + "` "
83 | + "SET `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupIDString + "' "
84 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' "
85 | + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "'";
86 | }
87 |
88 | protected String getGroupIDInsertQuery(String userID, String groupID)
89 | {
90 | String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` "
91 | + "(`"
92 | + configuration.webappSecondaryGroupUserIDColumn + "`, `"
93 | + configuration.webappSecondaryGroupKeyColumn + "`, `"
94 | + configuration.webappSecondaryGroupGroupIDColumn + "`) "
95 | + "VALUES ('"
96 | + userID + "', '"
97 | + configuration.webappSecondaryGroupKeyName + "', '"
98 | + groupID + "')";
99 | return query;
100 | }
101 |
102 | @Override
103 | public List getSecondaryGroupIDs(String userID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
104 | {
105 | List groupIDs = new ArrayList();
106 |
107 | result = sql.sqlQuery(getSecondaryGroupReadQuery(userID));
108 |
109 | if (result.next())
110 | {
111 | return convertDelimitedIDString(result.getString(configuration.webappSecondaryGroupGroupIDColumn));
112 | }
113 | return groupIDs;
114 | }
115 |
116 | @Override
117 | public List getSecondaryGroupUserIDs(String groupID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
118 | {
119 | List userIDs = new ArrayList();
120 | result = sql.sqlQuery(getSecondaryGroupUserIDsReadQuery());
121 | while(result.next())
122 | {
123 | List groupIDs = convertDelimitedIDString(result.getString(configuration.webappSecondaryGroupGroupIDColumn));
124 | if (groupIDs.contains(groupID))
125 | {
126 | userIDs.add(result.getString(configuration.webappSecondaryGroupUserIDColumn));
127 | }
128 | }
129 |
130 | return userIDs;
131 | }
132 |
133 | protected String getSecondaryGroupUserIDsReadQuery()
134 | {
135 | return "SELECT `" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
136 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
137 | + "WHERE `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' ";
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/MoneyDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.ResultSet;
5 | import java.sql.SQLException;
6 | import org.communitybridge.main.Configuration;
7 | import org.communitybridge.main.Environment;
8 |
9 | public class MoneyDao
10 | {
11 | public Double getBalance(Environment environment, String userId) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
12 | {
13 | String query;
14 | String column;
15 | ResultSet result;
16 | Configuration configuration = environment.getConfiguration();
17 | if (configuration.walletUsesKey)
18 | {
19 | query = "SELECT `" + configuration.walletValueColumn + "` "
20 | + "FROM `" + configuration.walletTableName + "` "
21 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + userId + "' "
22 | + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'";
23 | result = environment.getSql().sqlQuery(query);
24 | column = configuration.walletValueColumn;
25 | }
26 | else
27 | {
28 | query = "SELECT `" + configuration.walletColumnOrKey + "` "
29 | + "FROM `" + configuration.walletTableName + "` "
30 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + userId + "'";
31 | result = environment.getSql().sqlQuery(query);
32 | column = configuration.walletColumnOrKey;
33 | }
34 | if (result.next())
35 | {
36 | return result.getDouble(column);
37 | }
38 | else
39 | {
40 | return new Double(0.0);
41 | }
42 | }
43 |
44 | public void setBalance(Environment environment, String userId, Double balance) throws IllegalAccessException, InstantiationException, MalformedURLException
45 | {
46 | String query;
47 | Configuration configuration = environment.getConfiguration();
48 | if (configuration.walletUsesKey)
49 | {
50 | query = "UPDATE `" + configuration.walletTableName + "` "
51 | + "SET `" + configuration.walletValueColumn + "` = '" + balance.toString() + "' "
52 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + userId + "'"
53 | + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'";
54 | }
55 | else
56 | {
57 | query = "UPDATE `" + configuration.walletTableName + "` "
58 | + "SET `" + configuration.walletColumnOrKey + "` = '" + balance.toString() + "' "
59 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + userId + "'";
60 | }
61 | environment.getSql().updateQuery(query);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/MultipleKeyValueWebGroupDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.SQLException;
5 | import java.util.ArrayList;
6 | import java.util.List;
7 | import org.communitybridge.main.Environment;
8 |
9 | public class MultipleKeyValueWebGroupDao extends WebGroupDao
10 | {
11 | public static final String EXCEPTION_MESSAGE_GETSECONDARY = "Exception during MultipleKeyValueWebGroupDao.getSecondaryGroups(): ";
12 |
13 | public MultipleKeyValueWebGroupDao(Environment environment)
14 | {
15 | super(environment);
16 | }
17 |
18 | @Override
19 | public void addUserToGroup(String userID, String groupID, int currentGroupCount) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
20 | {
21 | String query = "INSERT INTO `" + configuration.webappSecondaryGroupTable + "` "
22 | + "(`" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupKeyColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "`) "
23 | + "VALUES ('" + userID + "', '" + configuration.webappSecondaryGroupKeyName + "', '" + groupID + "')";
24 | sql.insertQuery(query);
25 | }
26 |
27 | @Override
28 | public void removeUserFromGroup(String userID, String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
29 | {
30 | String query = "DELETE FROM `" + configuration.webappSecondaryGroupTable + "` "
31 | + "WHERE `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' "
32 | + "AND `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' ";
33 | sql.deleteQuery(query);
34 | }
35 |
36 | @Override
37 | public List getSecondaryGroupIDs(String userID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
38 | {
39 | List groupIDs = new ArrayList();
40 |
41 | String query =
42 | "SELECT `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
43 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
44 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' "
45 | + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' ";
46 |
47 | result = sql.sqlQuery(query);
48 |
49 | while (result.next())
50 | {
51 | addCleanID(result.getString(configuration.webappSecondaryGroupGroupIDColumn), groupIDs);
52 | }
53 | return groupIDs;
54 | }
55 |
56 | @Override
57 | public List getSecondaryGroupUserIDs(String groupID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
58 | {
59 | List userIDs = new ArrayList();
60 |
61 | String query =
62 | "SELECT `" + configuration.webappSecondaryGroupUserIDColumn + "` "
63 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
64 | + "WHERE `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' "
65 | + "AND `" + configuration.webappSecondaryGroupKeyColumn + "` = '" + configuration.webappSecondaryGroupKeyName + "' ";
66 |
67 | result = sql.sqlQuery(query);
68 |
69 | while (result.next())
70 | {
71 | addCleanID(result.getString(configuration.webappSecondaryGroupUserIDColumn), userIDs);
72 | }
73 | return userIDs;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/SingleWebGroupDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.SQLException;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.communitybridge.main.Environment;
10 | import org.communitybridge.utility.StringUtilities;
11 |
12 | public class SingleWebGroupDao extends WebGroupDao
13 | {
14 | public static final String EXCEPTION_MESSAGE_GETSECONDARY = "Exception during SingleMethodWebGroupDao.getSecondaryGroups(): ";
15 | public static final String EXCEPTION_MESSAGE_GET_USERIDS = "Exception during SingleMethodWebGroupDao.getGroupUserIDs(): ";
16 | public static final String EXCEPTION_MESSAGE_GETSECONDARY_USERIDS = "Exception during SingleMethodWebGroupDao.getSecondaryGroupUserIDs(): ";
17 | public SingleWebGroupDao(Environment environment)
18 | {
19 | super(environment);
20 | }
21 |
22 | @Override
23 | public void addUserToGroup(String userID, String groupID, int currentGroupCount) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
24 | {
25 | if (currentGroupCount >= 1)
26 | {
27 | groupID = configuration.webappSecondaryGroupGroupIDDelimiter + groupID;
28 | }
29 | String query = "UPDATE `" + configuration.webappSecondaryGroupTable + "` "
30 | + "SET `" + configuration.webappSecondaryGroupGroupIDColumn + "` = CONCAT(`" + configuration.webappSecondaryGroupGroupIDColumn + "`, '" + groupID + "') "
31 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'";
32 | sql.updateQuery(query);
33 | }
34 |
35 | @Override
36 | public void removeUserFromGroup(String userID, String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
37 | {
38 | String query = "SELECT `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
39 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
40 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'";
41 | result = sql.sqlQuery(query);
42 |
43 | if (result.next())
44 | {
45 | String groupIDs = result.getString(configuration.webappSecondaryGroupGroupIDColumn);
46 | List groupIDsAsList = new ArrayList(Arrays.asList(groupIDs.split(configuration.webappSecondaryGroupGroupIDDelimiter)));
47 | groupIDsAsList.remove(groupID);
48 | groupIDs = StringUtilities.joinStrings(groupIDsAsList, configuration.webappSecondaryGroupGroupIDDelimiter);
49 | query = "UPDATE `" + configuration.webappSecondaryGroupTable + "` "
50 | + "SET `" + configuration.webappSecondaryGroupGroupIDColumn + "` = '" + groupIDs + "' "
51 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'";
52 | sql.updateQuery(query);
53 | }
54 | }
55 |
56 | @Override
57 | public List getSecondaryGroupIDs(String userID) throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException
58 | {
59 | if (!configuration.webappSecondaryGroupEnabled)
60 | {
61 | return EMPTY_LIST;
62 | }
63 | String query =
64 | "SELECT `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
65 | + "FROM `" + configuration.webappSecondaryGroupTable + "` "
66 | + "WHERE `" + configuration.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' ";
67 |
68 | result = sql.sqlQuery(query);
69 |
70 | if (result.next())
71 | {
72 | return convertDelimitedIDString(result.getString(configuration.webappSecondaryGroupGroupIDColumn));
73 | }
74 | return EMPTY_LIST;
75 | }
76 |
77 | @Override
78 | public List getSecondaryGroupUserIDs(String groupID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException
79 | {
80 | List userIDs = new ArrayList();
81 |
82 | if (!configuration.webappSecondaryGroupEnabled)
83 | {
84 | return userIDs;
85 | }
86 |
87 | String query =
88 | "SELECT `" + configuration.webappSecondaryGroupUserIDColumn + "`, `" + configuration.webappSecondaryGroupGroupIDColumn + "` "
89 | + "FROM `" + configuration.webappSecondaryGroupTable + "` ";
90 | result = sql.sqlQuery(query);
91 | while(result.next())
92 | {
93 | String groupIDs = result.getString(configuration.webappSecondaryGroupGroupIDColumn);
94 | if (groupIDs != null)
95 | {
96 | groupIDs = groupIDs.trim();
97 | if (!groupIDs.isEmpty())
98 | {
99 | for (String id : groupIDs.split(configuration.webappSecondaryGroupGroupIDDelimiter))
100 | {
101 | if (id.equals(groupID))
102 | {
103 | userIDs.add(result.getString(configuration.webappSecondaryGroupUserIDColumn));
104 | }
105 | }
106 | }
107 | }
108 | }
109 | return userIDs;
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/synchronization/dao/WebGroupDao.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.ResultSet;
5 | import java.sql.SQLException;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 | import static org.communitybridge.synchronization.dao.SingleWebGroupDao.EXCEPTION_MESSAGE_GET_USERIDS;
9 | import org.communitybridge.main.Configuration;
10 | import org.communitybridge.main.Environment;
11 | import org.communitybridge.main.SQL;
12 | import org.communitybridge.utility.Log;
13 |
14 | public abstract class WebGroupDao
15 | {
16 | protected static final List EMPTY_LIST = new ArrayList();
17 |
18 | protected Configuration configuration;
19 | protected SQL sql;
20 | protected Log log;
21 | protected ResultSet result;
22 |
23 | WebGroupDao(Environment environment)
24 | {
25 | this.configuration = environment.getConfiguration();
26 | this.sql = environment.getSql();
27 | this.log = environment.getLog();
28 | }
29 |
30 | abstract public void addUserToGroup(String userID, String groupID, int currentGroupCount) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException;
31 |
32 | abstract public void removeUserFromGroup(String userID, String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException;
33 |
34 | abstract public List getSecondaryGroupIDs(String userID) throws IllegalAccessException, InstantiationException,MalformedURLException, SQLException;
35 | abstract public List getSecondaryGroupUserIDs(String groupID) throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException;
36 |
37 | public String getPrimaryGroupID(String userID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
38 | {
39 | if (!configuration.webappPrimaryGroupEnabled)
40 | {
41 | return "";
42 | }
43 | String query = determinePrimaryGroupQuery(userID);
44 |
45 | result = sql.sqlQuery(query);
46 |
47 | if (result.next())
48 | {
49 | return result.getString(configuration.webappPrimaryGroupGroupIDColumn);
50 | }
51 | else
52 | {
53 | return "";
54 | }
55 | }
56 |
57 | private String determinePrimaryGroupQuery(String userID)
58 | {
59 | if (configuration.webappPrimaryGroupUsesKey)
60 | {
61 | return "SELECT `" + configuration.webappPrimaryGroupGroupIDColumn + "` "
62 | + "FROM `" + configuration.webappPrimaryGroupTable + "` "
63 | + "WHERE `" + configuration.webappPrimaryGroupUserIDColumn + "` = '" + userID + "' "
64 | + "AND `" + configuration.webappPrimaryGroupKeyColumn + "` = '" + configuration.webappPrimaryGroupKeyName + "' ";
65 | }
66 | else
67 | {
68 | return "SELECT `" + configuration.webappPrimaryGroupGroupIDColumn + "` "
69 | + "FROM `" + configuration.webappPrimaryGroupTable + "` "
70 | + "WHERE `" + configuration.webappPrimaryGroupUserIDColumn + "` = '" + userID + "'";
71 | }
72 | }
73 |
74 | protected void addCleanID(String id, List idList)
75 | {
76 | if (id != null && !id.isEmpty())
77 | {
78 | id = id.trim();
79 | if (!id.isEmpty())
80 | {
81 | idList.add(id);
82 | }
83 | }
84 | }
85 |
86 | protected List convertDelimitedIDString(String ids)
87 | {
88 | List idList = new ArrayList();
89 | if (ids != null)
90 | {
91 | for (String id : ids.split(configuration.webappSecondaryGroupGroupIDDelimiter))
92 | {
93 | addCleanID(id, idList);
94 | }
95 | }
96 | return idList;
97 | }
98 |
99 | public List getGroupUserIDs(String groupID)
100 | {
101 | List userIDs = new ArrayList();
102 | try
103 | {
104 | userIDs.addAll(getUserIDsFromPrimaryGroup(groupID));
105 | userIDs.addAll(getSecondaryGroupUserIDs(groupID));
106 |
107 | return userIDs;
108 | }
109 | catch (IllegalAccessException exception)
110 | {
111 | log.severe(EXCEPTION_MESSAGE_GET_USERIDS + exception.getMessage());
112 | return userIDs;
113 | }
114 | catch (InstantiationException exception)
115 | {
116 | log.severe(EXCEPTION_MESSAGE_GET_USERIDS + exception.getMessage());
117 | return userIDs;
118 | }
119 | catch (MalformedURLException exception)
120 | {
121 | log.severe(EXCEPTION_MESSAGE_GET_USERIDS + exception.getMessage());
122 | return userIDs;
123 | }
124 | catch (SQLException exception)
125 | {
126 | log.severe(EXCEPTION_MESSAGE_GET_USERIDS + exception.getMessage());
127 | return userIDs;
128 | }
129 | }
130 |
131 | protected List getUserIDsFromPrimaryGroup(String groupID) throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
132 | {
133 | List userIDs = new ArrayList();
134 |
135 | if (!configuration.webappPrimaryGroupEnabled)
136 | {
137 | return userIDs;
138 | }
139 |
140 | String query =
141 | "SELECT `" + configuration.webappPrimaryGroupUserIDColumn + "` "
142 | + "FROM `" + configuration.webappPrimaryGroupTable + "` "
143 | + "WHERE `" + configuration.webappPrimaryGroupGroupIDColumn + "` = '" + groupID + "' ";
144 | result = sql.sqlQuery(query);
145 | while(result.next())
146 | {
147 | userIDs.add(result.getString(configuration.webappPrimaryGroupUserIDColumn));
148 | }
149 | return userIDs;
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/utility/Log.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.utility;
2 |
3 | import java.util.logging.Level;
4 | import java.util.logging.Logger;
5 |
6 | /**
7 | * Presents a familiar interface to the built-in logging facility while giving
8 | * us our own level of control over logging levels.
9 | *
10 | * @author Feaelin (Iain E. Davis)
11 | */
12 | public class Log
13 | {
14 |
15 | private static Logger log;
16 | private static Level level;
17 |
18 | /**
19 | * Constructor for only passing in reference to the logger object.
20 | *
21 | * @param log Logger object referencing the Bukkit Server logger.
22 | */
23 | public Log(Logger log)
24 | {
25 | Log.log = log;
26 | level = Level.INFO;
27 | }
28 |
29 | /**
30 | * Constructor to specify both the logger and the initial logging level.
31 | *
32 | * @param log Logger object referencing the Bukkit Server logger.
33 | * @param level Level type from java.util.logging.Level
34 | */
35 | public Log(Logger log, Level level)
36 | {
37 | Log.log = log;
38 | Log.level = level;
39 | }
40 |
41 | /**
42 | * Returns the current logging level.
43 | *
44 | * @return Level Java's Level enumerated type
45 | */
46 | public Level getLevel()
47 | {
48 | return Log.level;
49 | }
50 |
51 | /**
52 | * Set the logging level based on a string.
53 | *
54 | * @param level String containing the specified level. One of: all, finest, finer, fine, config, info, warning, severe
55 | */
56 | public void setLevel(String level)
57 | {
58 | if (level.equalsIgnoreCase("info"))
59 | {
60 | this.setLevel(Level.INFO);
61 | }
62 | else if (level.equalsIgnoreCase("config"))
63 | {
64 | this.setLevel(Level.CONFIG);
65 | }
66 | else if (level.equalsIgnoreCase("fine"))
67 | {
68 | this.setLevel(Level.FINE);
69 | }
70 | else if (level.equalsIgnoreCase("finer"))
71 | {
72 | this.setLevel(Level.FINER);
73 | }
74 | else if (level.equalsIgnoreCase("finest"))
75 | {
76 | this.setLevel(Level.FINEST);
77 | }
78 | else if (level.equalsIgnoreCase("all"))
79 | {
80 | this.setLevel(Level.ALL);
81 | }
82 | else if (level.equalsIgnoreCase("warning"))
83 | {
84 | this.setLevel(Level.WARNING);
85 | }
86 | else if (level.equalsIgnoreCase("severe"))
87 | {
88 | this.setLevel(Level.SEVERE);
89 | }
90 | }
91 |
92 | /**
93 | * Sets the logging level using a java.util.logging.Level type
94 | *
95 | * @param level Level from java.util.logging.Level
96 | */
97 | public void setLevel(Level level)
98 | {
99 | Log.level = level;
100 | }
101 |
102 | /**
103 | * Sends 'message' to the log if the logging level is high enough.
104 | *
105 | * @param message String containing message to be sent.
106 | */
107 | public void finest(String message)
108 | {
109 | // Finest: 300
110 | if (level.intValue() <= Level.FINEST.intValue())
111 | {
112 | log.info(message);
113 | }
114 | }
115 |
116 | /**
117 | * Sends 'message' to the log if the logging level is high enough.
118 | *
119 | * @param message String containing message to be sent.
120 | */
121 | public void finer(String message)
122 | {
123 | // Finer: 400
124 | if (level.intValue() <= Level.FINER.intValue())
125 | {
126 | log.info(message);
127 | }
128 | }
129 |
130 | /**
131 | * Sends 'message' to the log if the logging level is high enough.
132 | *
133 | * @param message String containing message to be sent.
134 | */
135 | public void fine(String message)
136 | {
137 | // Fine: 500
138 | if (level.intValue() <= Level.FINE.intValue())
139 | {
140 | log.info(message);
141 | }
142 | }
143 |
144 | /**
145 | * Sends 'message' to the log if the logging level is high enough.
146 | *
147 | * @param message String containing message to be sent.
148 | */
149 | public void config(String message)
150 | {
151 | // Config: 700
152 | if (level.intValue() <= Level.CONFIG.intValue())
153 | {
154 | log.info(message);
155 | }
156 | }
157 |
158 | /**
159 | * Sends 'message' to the log if the logging level is high enough.
160 | *
161 | * @param message String containing message to be sent.
162 | */
163 | public void info(String message)
164 | {
165 | // Info: 800
166 | if (level.intValue() <= Level.INFO.intValue())
167 | {
168 | log.info(message);
169 | }
170 | }
171 |
172 | /**
173 | * Sends 'message' to the log if the logging level is high enough.
174 | *
175 | * @param message String containing message to be sent.
176 | */
177 | public void warning(String message)
178 | {
179 | // Warning: 900
180 | if (level.intValue() <= Level.WARNING.intValue())
181 | {
182 | log.warning(message);
183 | }
184 | }
185 |
186 | /**
187 | * Sends 'message' to the log if the logging level is high enough.
188 | *
189 | * @param message String containing message to be sent.
190 | */
191 | public void severe(String message)
192 | {
193 | // Severe: 1000
194 | if (level.intValue() <= Level.SEVERE.intValue())
195 | {
196 | log.severe(message);
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/utility/MinecraftUtilities.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.utility;
2 |
3 | import org.bukkit.Bukkit;
4 | import org.bukkit.plugin.Plugin;
5 |
6 | public final class MinecraftUtilities
7 | {
8 | private MinecraftUtilities() {}
9 |
10 | public static String getPluginVersion(String pluginName)
11 | {
12 | Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginName);
13 | if (plugin == null)
14 | {
15 | return null;
16 | }
17 |
18 | return plugin.getDescription().getVersion();
19 | }
20 |
21 | public static String getBukkitVersion()
22 | {
23 | return Bukkit.getBukkitVersion();
24 | }
25 |
26 | public static void startTask(Plugin plugin, Runnable runnable)
27 | {
28 | Bukkit.getScheduler().runTaskAsynchronously(plugin, runnable);
29 | }
30 |
31 | public static void startTaskTimer(Plugin plugin, long every, Runnable runnable)
32 | {
33 | Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, every, every);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/communitybridge/utility/StringUtilities.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.utility;
2 |
3 | import java.util.List;
4 |
5 | public final class StringUtilities
6 | {
7 | public final static int NOT_FOUND = -1;
8 |
9 | private StringUtilities() {}
10 |
11 | /**
12 | * Returns:
13 | * 1 -- if left is greater than right
14 | * 0 -- if they are equal
15 | * -1 -- if left is less than right
16 | * @param leftVersion
17 | * @param rightVersion
18 | */
19 | public static int compareVersion(String leftVersion, String rightVersion) throws IllegalArgumentException
20 | {
21 | if (leftVersion == null)
22 | {
23 | leftVersion = "";
24 | }
25 |
26 | if (rightVersion == null)
27 | {
28 | rightVersion = "";
29 | }
30 |
31 | leftVersion = leftVersion.replace("-", ".").replaceAll("[^0-9\\.]", "");
32 | rightVersion = rightVersion.replace("-", ".").replaceAll("[^0-9\\.]", "");
33 |
34 | if (leftVersion.isEmpty() && rightVersion.isEmpty())
35 | {
36 | return 0;
37 | }
38 | else if (leftVersion.isEmpty())
39 | {
40 | return -1;
41 | }
42 | else if (rightVersion.isEmpty())
43 | {
44 | return 1;
45 | }
46 |
47 | String[] leftParts = leftVersion.split("\\.");
48 | String[] rightParts = rightVersion.split("\\.");
49 | int leftLength = leftParts.length;
50 | int rightLength = rightParts.length;
51 |
52 | // Which is shortest?
53 | int shortest = leftLength < rightLength ? leftLength : rightLength;
54 |
55 | // Determine if they are equal up to the point they are the same length.
56 | for (int i = 0; i < shortest; i++)
57 | {
58 | int leftPart = Integer.parseInt(leftParts[i]);
59 | int rightPart = Integer.parseInt(rightParts[i]);
60 |
61 | if (leftPart > rightPart)
62 | {
63 | return 1;
64 | }
65 | else if (leftPart < rightPart)
66 | {
67 | return -1;
68 | }
69 | }
70 |
71 | if (shortest < leftParts.length)
72 | {
73 | for (int i = shortest; i < leftParts.length; i++)
74 | {
75 | if (Integer.parseInt(leftParts[i]) > 0)
76 | {
77 | return 1;
78 | }
79 | }
80 | }
81 | else if (shortest < rightParts.length)
82 | {
83 | for (int i = shortest; i < rightParts.length; i++)
84 | {
85 | if (Integer.parseInt(rightParts[i]) > 0)
86 | {
87 | return -1;
88 | }
89 | }
90 | }
91 |
92 | // Same length, so equal.
93 | return 0;
94 | }
95 |
96 | /**
97 | * Finds the first position, of any of the characters in searchCharacters, if none of the characters are found StringUtilities.NOT_FOUND (-1) is returned.
98 | *
99 | * @param stringToSearch string to be searched, e.g., the haystack.
100 | * @param searchCharacters string containing the characters to search for, e.g., the needles.
101 | * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string.
102 | * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty.
103 | */
104 | public static int find_first_of(String stringToSearch, String searchCharacters) throws IllegalArgumentException
105 | {
106 | return StringUtilities.find_first_of(stringToSearch, searchCharacters, 0);
107 | }
108 | /**
109 | * 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.
110 | *
111 | * @param stringToSearch string to be searched, e.g., the haystack.
112 | * @param searchCharacters string containing the characters to search for, e.g., the needles.
113 | * @param startingPosition integer of where to begin the search in the string.
114 | * @return StringUtilities.NOT_FOUND (-1) if not found, otherwise the position of a character within the search string.
115 | * @throws IllegalArgumentException If stringToSearch or searchCharacters is null. Or if searchCharacters is empty.
116 | */
117 | public static int find_first_of(String stringToSearch, String searchCharacters, int startingPosition) throws IllegalArgumentException
118 | {
119 | if (stringToSearch == null)
120 | {
121 | throw new IllegalArgumentException("stringToSearch cannot be null.");
122 | }
123 |
124 | if (searchCharacters == null)
125 | {
126 | throw new IllegalArgumentException("searchCharacters cannot be null.");
127 | }
128 |
129 | if (searchCharacters.isEmpty())
130 | {
131 | throw new IllegalArgumentException("At least one character required for search.");
132 | }
133 |
134 |
135 | for (int position = startingPosition; position < stringToSearch.length(); position++)
136 | {
137 | if (searchCharacters.indexOf(stringToSearch.charAt(position)) > -1)
138 | {
139 | return position;
140 | }
141 | }
142 |
143 | return NOT_FOUND;
144 | }
145 |
146 | public static String joinStrings(List stringList, String conjunction)
147 | {
148 | StringBuilder stringBuilder = new StringBuilder();
149 | boolean first = true;
150 |
151 | for (String string : stringList)
152 | {
153 | if (first)
154 | {
155 | first = false;
156 | }
157 | else
158 | {
159 | stringBuilder.append(conjunction);
160 | }
161 | stringBuilder.append(string);
162 | }
163 |
164 | return stringBuilder.toString();
165 | }
166 |
167 | public static String timeElapsedToString(long time)
168 | {
169 | int count = 0;
170 |
171 | if (time == 0)
172 | {
173 | return "0 seconds";
174 | }
175 |
176 | String result = "";
177 |
178 | if (time >= 86400)
179 | {
180 | long days = time / 86400;
181 | time = time - days * 86400;
182 | result = result + days + (days == 1 ? " day" : " days");
183 | count++;
184 | }
185 |
186 | if (time >= 3600)
187 | {
188 | if (count >= 1)
189 | {
190 | result = result + ", ";
191 | }
192 | long hours = time / 3600;
193 | time = time - hours * 3600;
194 | result = result + hours + (hours == 1 ? " hour" : " hours");
195 | count++;
196 | }
197 |
198 | if (time >= 60)
199 | {
200 | if (count >= 1)
201 | {
202 | result = result + ", ";
203 | }
204 | long minutes = time / 60;
205 | time = time - minutes * 60;
206 | result = result + minutes + (minutes == 1 ? " minute" : " minutes");
207 | count++;
208 | }
209 |
210 | if (time > 0)
211 | {
212 | if (count >= 1)
213 | {
214 | result = result + ", ";
215 | }
216 | result = result + time + (time == 1 ? " second" : " seconds");
217 | }
218 |
219 | return result;
220 | }
221 | }
222 |
--------------------------------------------------------------------------------
/src/main/resources/achievements.yml:
--------------------------------------------------------------------------------
1 | # Item rewards use the name used by the enum constant. An online list resides at:
2 | # http://jd.bukkit.org/rb/apidocs/org/bukkit/Material.html
3 | #Avatar:
4 | # Limit: 1
5 | # Money: 0.0
6 | # Items:
7 | # EMERALD: 1
8 | #Groups:
9 | # Premium:
10 | # Limit: 1
11 | # Money: 100.0
12 | # Items:
13 | # EMERALD: 5
14 | #Post-Counts:
15 | # 10:
16 | # Limit: 1
17 | # Money: 0.0
18 | # Items:
19 | # EMERALD: 1
20 | # COAL: 1
21 | # 100:
22 | # Limit: 1
23 | # Money: 0.0
24 | # Items:
25 | # EMERALD: 10
26 | # COAL: 64
27 |
--------------------------------------------------------------------------------
/src/main/resources/messages.yml:
--------------------------------------------------------------------------------
1 | en:
2 | # Player Linking Messages
3 | # -----------------------------------------------------------------------------
4 | link-registered-player: Registered account, linked to forums.
5 | link-registered-player-group: Registered account, linked to forums. You have been placed in the ~GROUPNAME~ group.
6 | link-unregistered-player: Unregistered account - Please register at ~APPURL~ for full access.
7 | link-unregistered-reminder: Just a reminder to visit ~APPURL~ and register today!
8 | link-notify-player-group-change: 'You have been placed in the ~GROUPNAME~ group.'
9 |
10 | # Group Synchronization Messages
11 | # -----------------------------------------------------------------------------
12 | group-synchronization-primary-notify-player: Your primary group has been set to the group ~GROUPNAME~.
13 | group-synchronization-multiple-notify-player: 'You have been placed in the following groups: ~GROUPNAMES~.'
14 |
15 | # Command Interaction Messages
16 | # -----------------------------------------------------------------------------
17 | communitybridge-inactive: 'CommunityBridge is NOT active. Only the cbreload command is available.'
18 |
19 | # - cbreload
20 | cbreload: 'Reloading CommunityBridge configuration...'
21 | cbreload-success: 'Reload succeeded. Loaded from: ~FILENAME~'
22 | cbreload-too-many-arguments: 'Too many arguments. Usage: /cbreload [filename]'
23 |
24 | # cbsync
25 | cbsync: 'Your groups and/or statistics will be synchronized shortly.'
26 | cbsync-ingame: "You can only use 'cbsync' when connected as a player. You can use 'cbsyncall' to force a synchronization for all connected players."
27 | cbsync-target: "Synchronizing '~PLAYERNAME~'."
28 | cbsync-target-not-found: "'~PLAYERNAME~' is either offline or not a player."
29 |
30 | # cbsyncall
31 | cbsyncall: 'Groups and/or statistics will be synchronized for all connected players.'
32 |
33 | # Profile Requirements Messages
34 | # -----------------------------------------------------------------------------
35 | require-avatar-message: 'This server requires players to upload an avatar to their profile.'
36 | require-minimum-posts-message: 'This server requires players to have a minimum of ~MINIMUMPOSTCOUNT~ forum posts.'
37 |
--------------------------------------------------------------------------------
/src/main/resources/plugin.yml:
--------------------------------------------------------------------------------
1 | name: CommunityBridge
2 | version: 2.5.2.562
3 | description: Community Bridging plugin based off of ChillerCrafts ForumBridge plugin
4 | authors: [Feaelin, NoRC, ChillerCraft]
5 | website: http://dev.bukkit.org/server-mods/communitybridge-fm/
6 |
7 | softdepend: [bPermissions, GroupManager, PermissionsBukkit, PermissionsEx, Vault, zPermissions]
8 | main: org.communitybridge.main.CommunityBridge
9 |
10 | commands:
11 | cbreload:
12 | description: Reloads CommunityBridge's configuration from disk.
13 | permission: communitybridge.cbreload
14 | permission-message: "§cYou do not have access to that command."
15 | cbsync:
16 | description: Synchronizes yourself.
17 | permission: communitybridge.cbsync
18 | permission-message: "§cYou do not have access to that command."
19 | cbsynctarget:
20 | description: Synchronizes the specified player.
21 | permission: communitybridge.cbsync
22 | permission-message: "§cYou do not have access to that command."
23 | cbsyncall:
24 | description: Synchronizes all players.
25 | permission: communitybridge.cbsyncall
26 | permission-message: "§cYou do not have access to that command."
27 |
28 | permissions:
29 | communitybridge.*:
30 | description: Grants access to all CommunityBridge commands
31 | children:
32 | communitybridge.cbrank: true
33 | communitybridge.cbreload: true
34 | communitybridge.cbsync: true
35 | communitybridge.cbsynctarget: true
36 | communitybridge.cbsyncall: true
37 | communitybridge.cbrank:
38 | description: Allows use of the /cbrank command.
39 | default: op
40 | communitybridge.cbreload:
41 | description: Allows use of the /cbreload command.
42 | default: op
43 | communitybridge.cbsync:
44 | description: Allows use of the /cbsync command.
45 | default: true
46 | communitybridge.cbsynctarget:
47 | description: Allows use of the /cbsync command.
48 | default: op
49 | communitybridge.cbsyncall:
50 | description: Allows use of the /cbsyncall command.
51 | default: op
52 |
--------------------------------------------------------------------------------
/test/org/communitybridge/achievement/AchievementAvatarTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import java.util.EnumMap;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 | import org.apache.commons.lang.RandomStringUtils;
7 | import org.bukkit.Material;
8 | import org.bukkit.Server;
9 | import org.bukkit.entity.Player;
10 | import org.bukkit.event.inventory.InventoryType;
11 | import org.bukkit.inventory.ItemStack;
12 | import org.bukkit.inventory.PlayerInventory;
13 | import org.communitybridge.linker.UserPlayerLinker;
14 | import org.communitybridge.main.BukkitWrapper;
15 | import org.communitybridge.main.Configuration;
16 | import org.communitybridge.main.Environment;
17 | import org.communitybridge.main.WebApplication;
18 | import org.junit.Test;
19 | import static org.junit.Assert.*;
20 | import org.junit.Before;
21 | import static org.mockito.Mockito.*;
22 |
23 | public class AchievementAvatarTest
24 | {
25 | private Environment environment = new Environment();
26 | private Configuration configuration = mock(Configuration.class);
27 | private Player player = mock(Player.class);
28 | private WebApplication webApplication = mock(WebApplication.class);
29 | private UserPlayerLinker linker = mock(UserPlayerLinker.class);
30 | private PlayerAchievementState state = new PlayerAchievementState("Player", null);
31 | private String userID = RandomStringUtils.randomAlphabetic(2);
32 | private PlayerInventory playerInventory = mock(PlayerInventory.class);
33 | private PlayerInventory otherInventory = mock(PlayerInventory.class);
34 | private Server server = mock(Server.class);
35 |
36 | private BukkitWrapper bukkit = mock(BukkitWrapper.class);
37 |
38 | private AchievementAvatar achievement = new AchievementAvatar(environment);
39 |
40 | @Before
41 | public void beforeEach() {
42 | achievement.bukkit = bukkit;
43 | environment.setConfiguration(configuration);
44 | environment.setUserPlayerLinker(linker);
45 | configuration.avatarEnabled = true;
46 | environment.setWebApplication(webApplication);
47 | achievement.setLimit(1);
48 | when(bukkit.getServer()).thenReturn(server);
49 | when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory);
50 | when(player.getInventory()).thenReturn(playerInventory);
51 | when(playerInventory.getType()).thenReturn(InventoryType.PLAYER);
52 | when(linker.getUserID(player)).thenReturn(userID);
53 | when(webApplication.playerHasAvatar(userID)).thenReturn(true);
54 | Map itemRewards = new EnumMap(Material.class);
55 | itemRewards.put(Material.ACACIA_STAIRS, 10);
56 | itemRewards.put(Material.ACTIVATOR_RAIL, 10);
57 | achievement.setItemRewards(itemRewards);
58 | }
59 |
60 | @Test
61 | public void playerQualifiesReturnsTrue()
62 | {
63 | assertTrue(achievement.playerQualifies(player, state));
64 | }
65 |
66 | @Test
67 | public void playerQualifiesWithAvatarDisabledReturnsFalse()
68 | {
69 | configuration.avatarEnabled = false;
70 | assertFalse(achievement.playerQualifies(player, state));
71 | }
72 |
73 | @Test
74 | public void playerQualifiesWithNoUserIDReturnsFalse()
75 | {
76 | when(linker.getUserID(player)).thenReturn("");
77 | assertFalse(achievement.playerQualifies(player, state));
78 | }
79 |
80 | @Test
81 | public void playerQualifiesWithNoAvatarReturnsFalse()
82 | {
83 | when(webApplication.playerHasAvatar(userID)).thenReturn(false);
84 | assertFalse(achievement.playerQualifies(player, state));
85 | }
86 |
87 | @Test
88 | public void playerQualifiesOverLimitReturnsFalse()
89 | {
90 | achievement.setLimit(-1);
91 | assertFalse(achievement.playerQualifies(player, state));
92 | }
93 |
94 | @Test
95 | public void playerQualifiesWhenTooManyReturnsFalse()
96 | {
97 | HashMap rejected = new HashMap();
98 | ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64);
99 | rejected.put(0, stack);
100 |
101 | when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory);
102 | when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected);
103 |
104 | assertFalse(achievement.playerQualifies(player, state));
105 | }
106 |
107 | @Test
108 | public void rewardPlayerRewardsPlayer()
109 | {
110 | achievement.rewardPlayer(player, state);
111 | int rewardCount = achievement.getItemRewards().size();
112 | verify(playerInventory, times(rewardCount)).addItem(any(ItemStack.class));
113 | }
114 |
115 | @Test
116 | public void rewardPlayerIncrementsState()
117 | {
118 | int expected = state.getAvatarAchievements() + 1;
119 | achievement.rewardPlayer(player, state);
120 | assertEquals(expected, state.getAvatarAchievements());
121 | }
122 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/achievement/AchievementTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.achievement;
2 |
3 | import java.util.EnumMap;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 | import net.milkbowl.vault.economy.Economy;
7 | import org.apache.commons.lang3.RandomStringUtils;
8 | import org.apache.commons.lang3.RandomUtils;
9 | import org.bukkit.Material;
10 | import org.bukkit.Server;
11 | import org.bukkit.configuration.ConfigurationSection;
12 | import org.bukkit.configuration.file.YamlConfiguration;
13 | import org.bukkit.entity.Player;
14 | import org.bukkit.event.inventory.InventoryType;
15 | import org.bukkit.inventory.ItemStack;
16 | import org.bukkit.inventory.PlayerInventory;
17 | import org.communitybridge.main.BukkitWrapper;
18 | import org.communitybridge.main.Configuration;
19 | import org.communitybridge.main.Environment;
20 | import org.junit.Test;
21 | import org.junit.Before;
22 | import static org.junit.Assert.*;
23 | import static org.mockito.Mockito.*;
24 |
25 | public class AchievementTest
26 | {
27 | private Player player = mock(Player.class);
28 | private Environment environment = new Environment();
29 | private Configuration configuration = mock(Configuration.class);
30 | private PlayerInventory playerInventory = mock(PlayerInventory.class);
31 | private PlayerInventory otherInventory = mock(PlayerInventory.class);
32 | private BukkitWrapper bukkit = mock(BukkitWrapper.class);
33 | private Server server = mock(Server.class);
34 |
35 | Achievement achievement = new TestableAchievement(environment, bukkit);
36 |
37 | @Before
38 | public void beforeEach()
39 | {
40 | environment.setConfiguration(configuration);
41 | }
42 |
43 | @Test
44 | public void rewardPlayerPerformsCashReward()
45 | {
46 | Double amount = RandomUtils.nextDouble(10.0, 1000.0);
47 | configuration.economyEnabled = true;
48 | Economy economy = mock(Economy.class);
49 | environment.setEconomy(economy);
50 | when(economy.depositPlayer(player, amount)).thenReturn(null);
51 | achievement.setCashReward(amount);
52 | achievement.rewardPlayer(player, null);
53 | verify(economy).depositPlayer(player, amount);
54 | }
55 |
56 | @Test
57 | public void rewardPlayerNoEconomyNoCashAward()
58 | {
59 | Double amount = RandomUtils.nextDouble(10.0, 1000.0);
60 | configuration.economyEnabled = false;
61 | Economy economy = mock(Economy.class);
62 | environment.setEconomy(economy);
63 | when(economy.depositPlayer(player, amount)).thenReturn(null);
64 | achievement.setCashReward(amount);
65 | achievement.rewardPlayer(player, null);
66 | verifyZeroInteractions(economy);
67 | }
68 |
69 | @Test
70 | public void rewardPlayerOneItem()
71 | {
72 | configuration.economyEnabled = false;
73 | Map itemRewards = new EnumMap(Material.class);
74 | itemRewards.put(Material.ACACIA_STAIRS, 10);
75 | achievement.setItemRewards(itemRewards);
76 | when(player.getInventory()).thenReturn(playerInventory);
77 | when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null);
78 | achievement.rewardPlayer(player, null);
79 | verify(playerInventory).addItem(any(ItemStack.class));
80 | verify(player).updateInventory();
81 | }
82 |
83 | @Test
84 | public void rewardPlayerTwoItems()
85 | {
86 | configuration.economyEnabled = false;
87 | setupRewards();
88 | when(player.getInventory()).thenReturn(playerInventory);
89 | when(playerInventory.addItem(any(ItemStack.class))).thenReturn(null);
90 | achievement.rewardPlayer(player, null);
91 | verify(playerInventory, times(2)).addItem(any(ItemStack.class));
92 | verify(player, times(1)).updateInventory();
93 | }
94 |
95 | @Test
96 | public void rewardPlayerNoItemDontUpdateInventory()
97 | {
98 | configuration.economyEnabled = false;
99 | achievement.rewardPlayer(player, null);
100 | verify(player, never()).updateInventory();
101 | }
102 |
103 | @Test
104 | public void canRewardAllItemRewardsReturnTrue()
105 | {
106 | setupRewards();
107 |
108 | when(bukkit.getServer()).thenReturn(server);
109 | when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory);
110 | when(player.getInventory()).thenReturn(playerInventory);
111 | when(playerInventory.getType()).thenReturn(InventoryType.PLAYER);
112 | assertTrue(achievement.canRewardAllItemRewards(player));
113 | }
114 |
115 | @Test
116 | public void canRewardAllItemRewardsReturnFalseWhenTooMany()
117 | {
118 | setupRewards();
119 |
120 | HashMap rejected = new HashMap();
121 | ItemStack stack = new ItemStack(Material.ACACIA_STAIRS, 64);
122 | rejected.put(0, stack);
123 |
124 | when(bukkit.getServer()).thenReturn(server);
125 | when(server.createInventory(null, InventoryType.PLAYER)).thenReturn(otherInventory);
126 | when(player.getInventory()).thenReturn(playerInventory);
127 | when(playerInventory.getType()).thenReturn(InventoryType.PLAYER);
128 | when(otherInventory.addItem(any(ItemStack.class))).thenReturn(rejected);
129 |
130 | assertFalse(achievement.canRewardAllItemRewards(player));
131 | }
132 |
133 | @Test
134 | public void loadReadsLimit()
135 | {
136 | String path = RandomStringUtils.randomAlphabetic(7);
137 | YamlConfiguration yamlConfiguration = new YamlConfiguration();
138 | int limit = RandomUtils.nextInt(1,10);
139 | yamlConfiguration.set(path + ".Limit", limit);
140 | achievement.load(yamlConfiguration, path);
141 | assertEquals(limit, achievement.getLimit());
142 | }
143 |
144 | @Test
145 | public void loadReadsCashReward()
146 | {
147 | String path = RandomStringUtils.randomAlphabetic(7);
148 | YamlConfiguration yamlConfiguration = new YamlConfiguration();
149 | double cash = RandomUtils.nextDouble(1,10);
150 | yamlConfiguration.set(path + ".Money", cash);
151 | achievement.load(yamlConfiguration, path);
152 | assertEquals(cash, achievement.getCashReward(), 0);
153 | }
154 |
155 | @Test
156 | public void loadReadsOneItem()
157 | {
158 | String path = RandomStringUtils.randomAlphabetic(7);
159 | YamlConfiguration yamlConfiguration = new YamlConfiguration();
160 | ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items");
161 | Integer expected = RandomUtils.nextInt(1, 10);
162 | itemsSection.set("EMERALD", expected);
163 | achievement.load(yamlConfiguration, path);
164 | Integer actual = achievement.getItemRewards().get(Material.EMERALD);
165 | assertEquals(expected, actual);
166 | }
167 |
168 | @Test
169 | public void loadReadsMultipleItems()
170 | {
171 | String path = RandomStringUtils.randomAlphabetic(7);
172 | YamlConfiguration yamlConfiguration = new YamlConfiguration();
173 | ConfigurationSection itemsSection = yamlConfiguration.createSection(path + ".Items");
174 | Integer expectedEmerald = RandomUtils.nextInt(2, 10);
175 | Integer expectedCoal = RandomUtils.nextInt(2, 25);
176 | itemsSection.set("EMERALD", expectedEmerald);
177 | itemsSection.set("COAL", expectedCoal);
178 | achievement.load(yamlConfiguration, path);
179 | Integer actual = achievement.getItemRewards().get(Material.EMERALD);
180 | assertEquals(expectedEmerald, actual);
181 | actual = achievement.getItemRewards().get(Material.COAL);
182 | assertEquals(expectedCoal, actual);
183 | }
184 |
185 | private void setupRewards()
186 | {
187 | Map itemRewards = new EnumMap(Material.class);
188 | itemRewards.put(Material.ACACIA_STAIRS, 10);
189 | itemRewards.put(Material.ACTIVATOR_RAIL, 10);
190 | achievement.setItemRewards(itemRewards);
191 | }
192 |
193 | public class TestableAchievement extends Achievement
194 | {
195 | public TestableAchievement(Environment environment, BukkitWrapper bukkit)
196 | {
197 | super(environment);
198 | this.bukkit = bukkit;
199 | }
200 |
201 | @Override
202 | public boolean playerQualifies(Player player, PlayerAchievementState state)
203 | {
204 | return false;
205 | }
206 | }
207 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/main/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/test/org/communitybridge/main/.gitkeep
--------------------------------------------------------------------------------
/test/org/communitybridge/main/PlayerStatisticsTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.main;
2 |
3 | import java.text.SimpleDateFormat;
4 | import java.util.TimeZone;
5 | import org.junit.Test;
6 | import static org.junit.Assert.*;
7 | import org.junit.Before;
8 |
9 | public class PlayerStatisticsTest
10 | {
11 | private SimpleDateFormat dateFormat;
12 | private PlayerStatistics playerStatistics;
13 |
14 | @Before
15 | public void setup()
16 | {
17 | dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
18 | dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
19 | playerStatistics = new PlayerStatistics(dateFormat);
20 | }
21 |
22 | @Test
23 | public void testGetGameTimeFormatted()
24 | {
25 | playerStatistics.setGameTime(0);
26 | assertEquals("0 seconds", playerStatistics.getGameTimeFormatted());
27 | }
28 |
29 | @Test
30 | public void testGetCurrentXPFormatted()
31 | {
32 | playerStatistics.setCurrentXP(0);
33 | assertEquals("0%", playerStatistics.getCurrentXPFormatted());
34 | }
35 |
36 | @Test
37 | public void testGetLastOnlineTimeFormatted()
38 | {
39 | playerStatistics.setLastOnlineTime(1406378311373L);
40 | assertEquals("2014-07-26 12:38:31 PM", playerStatistics.getLastOnlineTimeFormatted());
41 | }
42 |
43 | @Test
44 | public void testGetLifeTicksFormatted()
45 | {
46 | playerStatistics.setLifeTicks(0);
47 | assertEquals("0 seconds", playerStatistics.getLifeTicksFormatted());
48 | }
49 |
50 | @Test
51 | public void testGetLastOnlineTimeInSeconds() {
52 | playerStatistics.setLastOnlineTime(1406378311373L);
53 | assertEquals(1406378311, playerStatistics.getLastOnlineTimeInSeconds());
54 | }
55 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/permissionhandlers/PermissionHandlerTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.permissionhandlers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.bukkit.Server;
6 | import org.bukkit.World;
7 | import org.bukkit.entity.Player;
8 | import org.bukkit.plugin.Plugin;
9 | import org.bukkit.plugin.PluginDescriptionFile;
10 | import org.communitybridge.main.BukkitWrapper;
11 | import org.junit.Test;
12 | import static org.junit.Assert.*;
13 | import static org.mockito.Mockito.mock;
14 | import static org.mockito.Mockito.when;
15 |
16 | public class PermissionHandlerTest
17 | {
18 | private String name = "someplugin";
19 | private String pluginVersion = "1.1";
20 | private Player player = mock(Player.class);
21 | private Plugin plugin = mock(Plugin.class);
22 | private PluginDescriptionFile description = new PluginDescriptionFile(name, pluginVersion, null);
23 | private final String playerName = "somePlayer";
24 | private final String groupOne = "groupOne";
25 | private final String groupTwo = "groupTwo";
26 |
27 | private BukkitWrapper bukkit = mock(BukkitWrapper.class);
28 | private TestablePermissionHandler permissionHandler = new TestablePermissionHandler(bukkit);
29 |
30 | @Test
31 | public void determineWorldFetchesPlayersWorld()
32 | {
33 | World world = mock(World.class);
34 |
35 | when(player.getWorld()).thenReturn(world);
36 | String worldName = "worldName";
37 | when(world.getName()).thenReturn(worldName);
38 | assertEquals(worldName, permissionHandler.determineWorld(player));
39 | }
40 |
41 | @Test
42 | public void determineWorldUsesDefaultWorld()
43 | {
44 | String worldName = "worldName";
45 | Server server = mock(Server.class);
46 | World world = mock(World.class);
47 | List worlds = new ArrayList();
48 | worlds.add(world);
49 |
50 | when(bukkit.getServer()).thenReturn(server);
51 | when(server.getWorlds()).thenReturn(worlds);
52 | when(world.getName()).thenReturn(worldName);
53 | assertEquals(worldName, permissionHandler.determineWorld(null));
54 | }
55 |
56 | @Test
57 | public void switchGroupCallsRemoveGroup()
58 | {
59 | permissionHandler.switchGroup(player, groupOne, groupTwo);
60 | assertEquals(playerName, permissionHandler.removePlayer);
61 | assertEquals(groupOne, permissionHandler.removeGroup);
62 | }
63 |
64 | @Test
65 | public void switchGroupCallsDoesNotCallRemoveGroupOnNull()
66 | {
67 | permissionHandler.switchGroup(player, null, groupTwo);
68 | assertEquals("", permissionHandler.removePlayer);
69 | assertEquals("", permissionHandler.removeGroup);
70 | }
71 |
72 | @Test
73 | public void switchGroupCallsAddGroup()
74 | {
75 | permissionHandler.switchGroup(player, groupOne, groupTwo);
76 | assertEquals(playerName, permissionHandler.addPlayer);
77 | assertEquals(groupTwo, permissionHandler.addGroup);
78 | }
79 |
80 | @Test
81 | public void validateHandlerDoesNotThrowErrorWithValidPlugin()
82 | {
83 | when(plugin.isEnabled()).thenReturn(true);
84 | when(plugin.getDescription()).thenReturn(description);
85 |
86 | try
87 | {
88 | permissionHandler.validate(plugin, name, pluginVersion);
89 | }
90 | catch (Exception exception)
91 | {
92 | fail("Caught an exception with valid plugin: " + exception.getMessage());
93 | }
94 | }
95 |
96 | @Test
97 | public void validateHandlerDoesNotThrowErrorWithValidPluginNewerVersion()
98 | {
99 | when(plugin.isEnabled()).thenReturn(true);
100 | when(plugin.getDescription()).thenReturn(description);
101 |
102 | try
103 | {
104 | permissionHandler.validate(plugin, name, "1.0");
105 | }
106 | catch (Exception exception)
107 | {
108 | fail("Caught an exception with valid plugin: " + exception.getMessage());
109 | }
110 | }
111 |
112 | @Test
113 | public void validateHandlerDoesThrowErrorWithValidPluginOlderVersion()
114 | {
115 | when(plugin.isEnabled()).thenReturn(true);
116 | when(plugin.getDescription()).thenReturn(description);
117 | String version = "1.2";
118 |
119 | try
120 | {
121 | permissionHandler.validate(plugin, name, version);
122 | fail("Failed to throw an exception.");
123 | }
124 | catch (IllegalStateException exception)
125 | {
126 | assertEquals(name + permissionHandler.WRONG_VERSION + version, exception.getMessage());
127 | }
128 | catch (Exception exception)
129 | {
130 | fail("Threw incorrect exception: " + exception.getMessage());
131 | }
132 | }
133 |
134 | @Test
135 | public void validateHandlerDoesThrowErrorWithNullPlugin()
136 | {
137 | try
138 | {
139 | permissionHandler.validate(null, name, pluginVersion);
140 | fail("Failed to throw an exception.");
141 | }
142 | catch (IllegalStateException exception)
143 | {
144 | assertEquals(name + permissionHandler.NOT_FOUND, exception.getMessage());
145 | }
146 | catch (Exception exception)
147 | {
148 | fail("Threw incorrect exception: " + exception.getMessage());
149 | }
150 | }
151 |
152 | @Test
153 | public void validateHandlerDoesThrowErrorWithDisabledPlugin()
154 | {
155 | when(plugin.isEnabled()).thenReturn(false);
156 |
157 | try
158 | {
159 | permissionHandler.validate(plugin, name, pluginVersion);
160 | fail("Failed to throw an exception.");
161 | }
162 | catch (IllegalStateException exception)
163 | {
164 | assertEquals(name + permissionHandler.NOT_ENABLED, exception.getMessage());
165 | }
166 | catch (Exception exception)
167 | {
168 | fail("Threw incorrect exception." + exception.getMessage());
169 | }
170 | }
171 |
172 | public class TestablePermissionHandler extends PermissionHandler
173 | {
174 | public String addPlayer = "";
175 | public String addGroup = "";
176 | public String removePlayer = "";
177 | public String removeGroup = "";
178 |
179 | public TestablePermissionHandler(BukkitWrapper bukkit)
180 | {
181 | this.bukkit = bukkit;
182 | }
183 |
184 | @Override
185 | public boolean addToGroup(Player player, String groupName)
186 | {
187 | addPlayer = playerName;
188 | addGroup = groupName;
189 | return true;
190 | }
191 |
192 | @Override
193 | public boolean removeFromGroup(Player player, String groupName)
194 | {
195 | removePlayer = playerName;
196 | removeGroup = groupName;
197 | return true;
198 | }
199 |
200 | @Override
201 | public List getGroups(Player player)
202 | {
203 | throw new UnsupportedOperationException("No implementation needed for tests.");
204 | }
205 |
206 | @Override
207 | public List getGroupsPure(Player player)
208 | {
209 | throw new UnsupportedOperationException("No implementation needed for tests.");
210 | }
211 |
212 | @Override
213 | public String getPrimaryGroup(Player player)
214 | {
215 | throw new UnsupportedOperationException("No implementation needed for tests.");
216 | }
217 |
218 | @Override
219 | public boolean isMemberOfGroup(Player player, String groupName)
220 | {
221 | throw new UnsupportedOperationException("No implementation needed for tests.");
222 | }
223 |
224 | @Override
225 | public boolean isPrimaryGroup(Player player, String groupName)
226 | {
227 | throw new UnsupportedOperationException("No implementation needed for tests.");
228 | }
229 |
230 | @Override
231 | public boolean setPrimaryGroup(Player player, String groupName, String formerGroupName)
232 | {
233 | throw new UnsupportedOperationException("No implementation needed for tests.");
234 | }
235 |
236 | @Override
237 | public boolean supportsPrimaryGroups()
238 | {
239 | throw new UnsupportedOperationException("No implementation needed for tests.");
240 | }
241 | }
242 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/synchronization/PlayerFileFetcherTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.UUID;
6 | import org.apache.commons.lang.math.RandomUtils;
7 | import org.apache.commons.lang3.RandomStringUtils;
8 | import org.bukkit.entity.Player;
9 | import org.junit.Assert;
10 | import org.junit.Before;
11 | import org.junit.Test;
12 | import org.mockito.Mock;
13 | import static org.mockito.Mockito.*;
14 |
15 | public class PlayerFileFetcherTest
16 | {
17 | private PlayerFileFetcher fetcher = new PlayerFileFetcher();
18 | private Player player = mock(Player.class);
19 | private UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong());
20 | private String PLAYER_NAME = RandomStringUtils.randomAlphabetic(10);
21 | @Mock private File folder;
22 | private File mockPlayerFile = mock(File.class);
23 | private File file = new File("/");
24 |
25 | private PlayerFileFetcher fetcher2 = spy(new PlayerFileFetcher());
26 | @Before
27 | public void beforeEach()
28 | {
29 | when(player.getUniqueId()).thenReturn(UUID);
30 | when(player.getName()).thenReturn(PLAYER_NAME);
31 | }
32 |
33 | @Test
34 | public void getPlayerShouldNeverReturnNull()
35 | {
36 | Assert.assertNotNull(fetcher.getPlayerFile(file, player, false));
37 | Assert.assertNotNull(fetcher.getPlayerFile(file, player, true));
38 | }
39 |
40 | @Test
41 | public void getPlayerShouldUsePlayersFolder() throws IOException
42 | {
43 | File playerFile = fetcher.getPlayerFile(file, player, false);
44 | Assert.assertEquals("Players", playerFile.getParent().substring(1));
45 | }
46 |
47 | @Test
48 | public void getPlayerShouldUseUUID()
49 | {
50 | File playerFile = fetcher.getPlayerFile(file, player, false);
51 | Assert.assertEquals(player.getUniqueId().toString() + ".yml", playerFile.getName());
52 | }
53 |
54 | @Test
55 | public void getPlayerWhenTypicalDoesNotExistAndAllowedShouldReturnOldPlayerFile()
56 | {
57 | doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString());
58 | doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString());
59 | when(mockPlayerFile.exists()).thenReturn(false);
60 | File playerFile = fetcher2.getPlayerFile(file, player, true);
61 | Assert.assertEquals(player.getName() + ".yml", playerFile.getName());
62 | }
63 |
64 | @Test
65 | public void getPlayerWhenTypicalDoesNotExistAndNotAllowedShouldReturnTypicalPlayerFile()
66 | {
67 | doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString());
68 | doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString());
69 | when(mockPlayerFile.exists()).thenReturn(false);
70 | File playerFile = fetcher2.getPlayerFile(file, player, false);
71 | Assert.assertSame(mockPlayerFile, playerFile);
72 | }
73 |
74 | @Test
75 | public void getPlayerWhenTypicalDoesExistAndAllowedShouldReturnTypicalPlayerFile()
76 | {
77 | doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString());
78 | doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString());
79 | when(mockPlayerFile.exists()).thenReturn(true);
80 | File playerFile = fetcher2.getPlayerFile(file, player, true);
81 | Assert.assertSame(mockPlayerFile, playerFile);
82 | }
83 |
84 | @Test
85 | public void getPlayerWhenTypicalDoesExistAndNotAllowedShouldReturnTypicalPlayerFile()
86 | {
87 | doReturn(folder).when(fetcher2).makeFile(any(File.class), anyString());
88 | doReturn(mockPlayerFile).when(fetcher2).makeFile(eq(folder), anyString());
89 | when(mockPlayerFile.exists()).thenReturn(true);
90 | File playerFile = fetcher2.getPlayerFile(file, player, false);
91 | Assert.assertSame(mockPlayerFile, playerFile);
92 | }
93 | }
94 |
95 |
--------------------------------------------------------------------------------
/test/org/communitybridge/synchronization/PlayerSynchronizationDispatcherTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import java.io.File;
4 | import java.util.ArrayList;
5 | import java.util.UUID;
6 | import org.apache.commons.lang.RandomStringUtils;
7 | import org.apache.commons.lang.math.RandomUtils;
8 | import org.bukkit.entity.Player;
9 | import org.communitybridge.linker.UserPlayerLinker;
10 | import org.communitybridge.main.BukkitWrapper;
11 | import org.communitybridge.main.CommunityBridge;
12 | import org.communitybridge.main.Configuration;
13 | import org.communitybridge.utility.Log;
14 | import org.communitybridge.main.Environment;
15 | import org.communitybridge.main.WebApplication;
16 | import org.junit.Test;
17 | import org.junit.Before;
18 | import org.junit.runner.RunWith;
19 | import org.mockito.InOrder;
20 | import org.mockito.InjectMocks;
21 | import org.mockito.Mock;
22 | import static org.mockito.Mockito.*;
23 | import org.powermock.api.mockito.PowerMockito;
24 | import org.powermock.core.MockGateway;
25 | import org.powermock.core.classloader.annotations.PrepareForTest;
26 | import org.powermock.modules.junit4.PowerMockRunner;
27 |
28 | @RunWith(PowerMockRunner.class)
29 | @PrepareForTest(CommunityBridge.class)
30 | public class PlayerSynchronizationDispatcherTest
31 | {
32 | private Environment environment = new Environment();
33 | private BukkitWrapper bukkit = mock(BukkitWrapper.class);
34 | private CommunityBridge plugin = PowerMockito.mock(CommunityBridge.class);
35 | private Configuration configuration = mock(Configuration.class);
36 | private Log log = mock(Log.class);
37 | private UserPlayerLinker userPlayerLinker = mock(UserPlayerLinker.class);
38 | private WebApplication webApplication = mock(WebApplication.class);
39 |
40 | private PlayerState result = mock(PlayerState.class);
41 |
42 | private Player player = mock(Player.class);
43 | private Player[] players = new Player[2];
44 | private static final String USER_ID = RandomStringUtils.randomAlphabetic(8);
45 | private static final UUID UUID = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong());
46 | private File dataFolder = new File("/");
47 |
48 | @Mock private File dataFile;
49 | @Mock private ArrayList playerLocks;
50 | @Mock private MoneySynchronizer moneySynchronizer;
51 |
52 | @InjectMocks
53 | private PlayerSynchronizationDispatcher dispatcher = new PlayerSynchronizationDispatcher();
54 |
55 | @Before
56 | public void beforeEach() throws Exception
57 | {
58 | MockGateway.MOCK_STANDARD_METHODS = false;
59 | environment.setBukkit(bukkit);
60 | environment.setConfiguration(configuration);
61 | environment.setLog(log);
62 | environment.setPlugin(plugin);
63 | environment.setUserPlayerLinker(userPlayerLinker);
64 | environment.setWebApplication(webApplication);
65 |
66 | configuration.groupSynchronizationActive = true;
67 | configuration.simpleSynchronizationGroupsTreatedAsPrimary = new ArrayList();
68 | configuration.statisticsEnabled = true;
69 | configuration.useAchievements = true;
70 | when(moneySynchronizer.isActive(environment)).thenReturn(true);
71 |
72 | players[0] = player;
73 | when(bukkit.getOnlinePlayers()).thenReturn(players);
74 | PowerMockito.when(plugin.getDataFolder()).thenReturn(dataFolder);
75 | when(dataFile.exists()).thenReturn(true);
76 | when(userPlayerLinker.getUserID(player)).thenReturn(USER_ID);
77 | when(player.getUniqueId()).thenReturn(UUID);
78 | when(webApplication.synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result);
79 | when(moneySynchronizer.synchronize(eq(environment), any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class))).thenReturn(result);
80 | }
81 |
82 | @Test
83 | public void synchronizeShouldLogStart()
84 | {
85 | dispatcher.synchronize(environment);
86 | verify(log).finest("Running player synchronization.");
87 | }
88 |
89 | @Test
90 | public void synchronizeShouldLogEnd()
91 | {
92 | dispatcher.synchronize(environment);
93 | verify(log).finest("Player synchronization complete.");
94 | }
95 |
96 | @Test
97 | public void synchronizeShouldSynchronizeGroups()
98 | {
99 | dispatcher.synchronize(environment);
100 | verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
101 | }
102 |
103 | @Test
104 | public void synchronizeShouldSynchronizeForMultiplePlayers()
105 | {
106 | Player player2 = mock(Player.class);
107 | players[1] = player2;
108 | when(userPlayerLinker.getUserID(player2)).thenReturn(USER_ID);
109 | when(player2.getUniqueId()).thenReturn(UUID);
110 | dispatcher.synchronize(environment);
111 |
112 | verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
113 | verify(webApplication).synchronizeGroups(eq(player2), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
114 | }
115 |
116 | @Test
117 | public void synchronizeWhenGroupSynchronizationInactiveShouldNotSynchronizeGroups()
118 | {
119 | configuration.groupSynchronizationActive = false;
120 | dispatcher.synchronize(environment);
121 | verify(webApplication, never()).synchronizeGroups(any(Player.class), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
122 | }
123 |
124 | @Test
125 | public void synchronizeWhenUserIDIsNullShouldNotSynchronize()
126 | {
127 | configuration.groupSynchronizationActive = true;
128 | when(userPlayerLinker.getUserID(player)).thenReturn(null);
129 | dispatcher.synchronize(environment);
130 | verify(webApplication, never()).synchronizeGroups(any(Player.class), isNull(String.class), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
131 | }
132 |
133 | @Test
134 | public void synchronizeWhenUserIDIsNullShouldNotAddPlayerLock()
135 | {
136 | configuration.groupSynchronizationActive = true;
137 | when(userPlayerLinker.getUserID(player)).thenReturn(null);
138 | dispatcher.synchronize(environment);
139 | verify(playerLocks, never()).add(player);
140 | }
141 |
142 | @Test
143 | public void synchronizeShouldOnlySynchronizePlayerOnce()
144 | {
145 | when(playerLocks.contains(player)).thenReturn(true);
146 |
147 | dispatcher.synchronize(environment);
148 |
149 | verify(webApplication, never()).synchronizeGroups(eq(player), anyString(), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
150 | }
151 |
152 | @Test
153 | public void synchronizeShouldAddPlayerToLock()
154 | {
155 | dispatcher.synchronize(environment);
156 | InOrder inOrder = inOrder(playerLocks, webApplication);
157 | inOrder.verify(playerLocks).add(player);
158 | inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
159 | }
160 |
161 | @Test
162 | public void synchronizeShouldRemovePlayerFromLock()
163 | {
164 | dispatcher.synchronize(environment);
165 |
166 | InOrder inOrder = inOrder(webApplication, playerLocks);
167 | inOrder.verify(webApplication).synchronizeGroups(eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
168 | inOrder.verify(playerLocks).remove(player);
169 | }
170 |
171 |
172 | @Test
173 | public void synchronizeShouldUpdateStatistics()
174 | {
175 | dispatcher.synchronize(environment);
176 | verify(webApplication).updateStatistics(player, true);
177 | }
178 |
179 | @Test
180 | public void synchronizeWhenStatisticsInactiveShouldNotUpdateStatistics()
181 | {
182 | configuration.statisticsEnabled = false;
183 | dispatcher.synchronize(environment);
184 | verify(webApplication, never()).updateStatistics(player, true);
185 | }
186 |
187 | @Test
188 | public void synchronizeShouldRewardAchievements()
189 | {
190 | dispatcher.synchronize(environment);
191 | verify(webApplication).rewardAchievements(player);
192 | }
193 |
194 | @Test
195 | public void synchronizeWhenAchievementsInactiveShouldNotRewardAchievements()
196 | {
197 | configuration.useAchievements = false;
198 | dispatcher.synchronize(environment);
199 | verify(webApplication, never()).rewardAchievements(player);
200 | }
201 |
202 | @Test
203 | public void synchronizeShouldSynchronizeMoney()
204 | {
205 | dispatcher.synchronize(environment);
206 | verify(moneySynchronizer).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
207 | }
208 |
209 | @Test
210 | public void synchronizeShouldNotSynchronizeMoney()
211 | {
212 | when(moneySynchronizer.isActive(environment)).thenReturn(false);
213 | dispatcher.synchronize(environment);
214 | verify(moneySynchronizer, never()).synchronize(eq(environment), eq(player), eq(USER_ID), any(PlayerState.class), any(PlayerState.class), any(PlayerState.class));
215 | }
216 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/synchronization/SynchronizerTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization;
2 |
3 | import org.apache.commons.lang.RandomStringUtils;
4 | import org.communitybridge.main.Environment;
5 | import org.junit.Test;
6 | import static org.junit.Assert.*;
7 |
8 | public class SynchronizerTest
9 | {
10 | Synchronizer synchronizer = new Synchronizer(new Environment());
11 |
12 | @Test
13 | public void isValidDirectionReturnsTrueForTwo()
14 | {
15 | assertTrue(synchronizer.isValidDirection("two", "aaa"));
16 | }
17 |
18 | @Test
19 | public void isValidDirectionReturnsTrueForWebWhenWeb()
20 | {
21 | assertTrue(synchronizer.isValidDirection("web", "web"));
22 | }
23 |
24 | @Test
25 | public void isValidDirectionReturnsTrueForMinWhenMin()
26 | {
27 | assertTrue(synchronizer.isValidDirection("min", "min"));
28 | }
29 |
30 | @Test
31 | public void isValidDirectionReturnsFalseForSomethingElseAgainstMin()
32 | {
33 | assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "min"));
34 | }
35 |
36 | @Test
37 | public void isValidDirectionReturnsFalseForSomethingElseAgainstWeb()
38 | {
39 | assertFalse(synchronizer.isValidDirection("aaa" + RandomStringUtils.randomAlphabetic(3), "web"));
40 | }
41 | }
--------------------------------------------------------------------------------
/test/org/communitybridge/synchronization/dao/DaoTestsHelper.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.util.LinkedHashMap;
4 | import org.communitybridge.main.Configuration;
5 |
6 | public class DaoTestsHelper
7 | {
8 | public static void setupConfiguration(Configuration configuration)
9 | {
10 | configuration.webappPrimaryGroupEnabled = true;
11 | configuration.webappPrimaryGroupTable = "primaryGroupTable";
12 | configuration.webappPrimaryGroupUserIDColumn = "primaryUserID";
13 | configuration.webappPrimaryGroupGroupIDColumn = "primaryGroupIDs";
14 | configuration.webappPrimaryGroupUsesKey = true;
15 | configuration.webappPrimaryGroupKeyName = "keyName";
16 | configuration.webappPrimaryGroupKeyColumn = "keyColumn";
17 | configuration.webappSecondaryGroupEnabled = true;
18 | configuration.webappSecondaryGroupUserIDColumn = "secondaryUserID";
19 | configuration.webappSecondaryGroupGroupIDColumn = "secondaryGroupIDs";
20 | configuration.webappSecondaryGroupGroupIDDelimiter = ",";
21 | configuration.webappSecondaryGroupTable = "secondaryGroupTable";
22 | configuration.webappSecondaryGroupKeyName = "secondaryGroupKeyName";
23 | configuration.webappSecondaryGroupKeyColumn = "secondaryGroupKeyColumn";
24 | configuration.webappSecondaryGroupStorageMethod = "single";
25 | configuration.webappSecondaryAdditionalColumns = new LinkedHashMap();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/test/org/communitybridge/synchronization/dao/MoneyDaoTest.java:
--------------------------------------------------------------------------------
1 | package org.communitybridge.synchronization.dao;
2 |
3 | import java.net.MalformedURLException;
4 | import java.sql.ResultSet;
5 | import java.sql.SQLException;
6 | import org.apache.commons.lang.math.RandomUtils;
7 | import org.apache.commons.lang3.RandomStringUtils;
8 | import org.communitybridge.main.Configuration;
9 | import org.communitybridge.main.Environment;
10 | import org.communitybridge.main.SQL;
11 | import org.junit.Assert;
12 | import org.junit.Before;
13 | import org.junit.Test;
14 | import org.mockito.Mockito;
15 | import static org.mockito.Mockito.mock;
16 | import static org.mockito.Mockito.when;
17 |
18 | public class MoneyDaoTest
19 | {
20 | MoneyDao dao = new MoneyDao();
21 | private final Environment environment = new Environment();
22 | private final Configuration configuration = mock(Configuration.class);
23 | private final SQL sql = mock(SQL.class);
24 | private final ResultSet result = mock(ResultSet.class);
25 | private String KEYED_QUERY;
26 | private String KEYLESS_QUERY;
27 | private final String USER_ID = RandomStringUtils.randomAlphabetic(2);
28 | private final double KEYLESS_BALANCE = RandomUtils.nextDouble();
29 | private final double KEYED_BALANCE = RandomUtils.nextDouble();
30 |
31 | @Before
32 | public void beforeEach() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
33 | {
34 | configuration.walletValueColumn = RandomStringUtils.randomAlphabetic(13);
35 | configuration.walletTableName = RandomStringUtils.randomAlphabetic(10);
36 | configuration.walletKeyColumn = RandomStringUtils.randomAlphabetic(9);
37 | configuration.walletUserIDColumn = RandomStringUtils.randomAlphabetic(8);
38 | configuration.walletColumnOrKey = RandomStringUtils.randomAlphabetic(7);
39 |
40 | environment.setConfiguration(configuration);
41 | environment.setSql(sql);
42 | KEYED_QUERY = "SELECT `" + configuration.walletValueColumn + "` "
43 | + "FROM `" + configuration.walletTableName + "` "
44 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "' "
45 | + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'";
46 | KEYLESS_QUERY = "SELECT `" + configuration.walletColumnOrKey + "` "
47 | + "FROM `" + configuration.walletTableName + "` "
48 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'";
49 |
50 | when(sql.sqlQuery(KEYED_QUERY)).thenReturn(result);
51 | when(sql.sqlQuery(KEYLESS_QUERY)).thenReturn(result);
52 | when(result.next()).thenReturn(true);
53 | when(result.getDouble(configuration.walletValueColumn)).thenReturn(KEYED_BALANCE);
54 | when(result.getDouble(configuration.walletColumnOrKey)).thenReturn(KEYLESS_BALANCE);
55 | }
56 |
57 | @Test
58 | public void getBalanceNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
59 | {
60 | Assert.assertNotNull(dao.getBalance(environment, USER_ID));
61 | }
62 |
63 | @Test
64 | public void getBalanceKeylessWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
65 | {
66 | configuration.walletUsesKey = false;
67 | when(result.next()).thenReturn(false);
68 | Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0);
69 | }
70 |
71 | @Test
72 | public void getBalanceKeylessReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
73 | {
74 | configuration.walletUsesKey = false;
75 | Assert.assertEquals(KEYLESS_BALANCE, dao.getBalance(environment, USER_ID), 0.0);
76 | }
77 |
78 | @Test
79 | public void getBalanceUsesKeyNeverReturnsNull() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
80 | {
81 | configuration.walletUsesKey = true;
82 | Assert.assertNotNull(dao.getBalance(environment, USER_ID));
83 | }
84 |
85 | @Test
86 | public void getBalanceKeyedWhenEmptyResultSetReturnsZero() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
87 | {
88 | configuration.walletUsesKey = true;
89 | when(result.next()).thenReturn(false);
90 | Assert.assertEquals(new Double(0.0), dao.getBalance(environment, USER_ID), 0.0);
91 | }
92 |
93 | @Test
94 | public void getBalanceUsesKeyReturnsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
95 | {
96 | configuration.walletUsesKey = true;
97 | Assert.assertEquals(KEYED_BALANCE, dao.getBalance(environment, USER_ID), 0.0);
98 | }
99 |
100 | @Test
101 | public void setBalanceKeylessSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
102 | {
103 | Double balance = RandomUtils.nextDouble();
104 | String query = "UPDATE `" + configuration.walletTableName + "` "
105 | + "SET `" + configuration.walletColumnOrKey + "` = '" + balance.toString() + "' "
106 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'";
107 | configuration.walletUsesKey = false;
108 | dao.setBalance(environment, USER_ID, balance);
109 | Mockito.verify(sql).updateQuery(query);
110 | }
111 |
112 | @Test
113 | public void setBalanceKeyedSetsBalance() throws IllegalAccessException, InstantiationException, MalformedURLException, SQLException
114 | {
115 | Double balance = RandomUtils.nextDouble();
116 | String query = "UPDATE `" + configuration.walletTableName + "` "
117 | + "SET `" + configuration.walletValueColumn + "` = '" + balance.toString() + "' "
118 | + "WHERE `" + configuration.walletUserIDColumn + "` = '" + USER_ID + "'"
119 | + "AND " + configuration.walletKeyColumn + "` = '" + configuration.walletColumnOrKey + "'";
120 | configuration.walletUsesKey = true;
121 | dao.setBalance(environment, USER_ID, balance);
122 | Mockito.verify(sql).updateQuery(query);
123 | }
124 | }
--------------------------------------------------------------------------------
/website/images/CommunityBridgeLogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/CommunityBridgeLogo.png
--------------------------------------------------------------------------------
/website/images/buttons/code.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/code.png
--------------------------------------------------------------------------------
/website/images/buttons/credits.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/credits.png
--------------------------------------------------------------------------------
/website/images/buttons/documentation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/documentation.png
--------------------------------------------------------------------------------
/website/images/buttons/faq.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/faq.png
--------------------------------------------------------------------------------
/website/images/buttons/help.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/help.png
--------------------------------------------------------------------------------
/website/images/buttons/permissions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tainz/CommunityBridge/09cccfb760bc45a495d19f567591fb30afaba105/website/images/buttons/permissions.png
--------------------------------------------------------------------------------