Skip to content

Commit

Permalink
Merge pull request #23 from GregDThomas/restore-compatibility
Browse files Browse the repository at this point in the history
Ensure compatibility with newer versions of Openfire (fixes #22)
GregDThomas authored Dec 26, 2024
2 parents 42b33f2 + 746c592 commit 4a418fd
Showing 15 changed files with 1,010 additions and 889 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -9,10 +9,10 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Set up JDK 1.8
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
java-version: 8.0
java-version: 11.0
distribution: temurin
cache: 'gradle'

211 changes: 120 additions & 91 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,92 +1,121 @@
import com.github.spotbugs.snom.Confidence
import com.github.spotbugs.snom.Effort
import com.github.spotbugs.snom.SpotBugsReport
import com.github.spotbugs.snom.SpotBugsTask

plugins {
id 'java-library'
id 'maven-publish'
id 'checkstyle'
id 'com.github.spotbugs' version '4.2.1'
}
apply from: 'build.openfire-plugin.gradle'

ext.lombokVersion = '1.18.12'
ext.junitVersion = '5.3.1'

group = 'org.igniterealtime.openfire.plugins'

java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withJavadocJar()
withSourcesJar()
}

test {
useJUnitPlatform()
testLogging {
showStandardStreams = true
}
}

checkstyle {
toolVersion '8.31'
maxWarnings 0
}

tasks.withType(Checkstyle) {
reports {
xml.enabled = false
html.enabled = true
}
exclude '**/org/jivesoftware/openfire/plugin/passwordreset/jsp/**'
}

spotbugs {
effort = Effort.MAX
reportLevel = Confidence.LOW
ignoreFailures.set false
extraArgs.add "-longBugCodes"
}

tasks.withType(SpotBugsTask) {
reports(({
text.enabled = true
} as Closure<NamedDomainObjectContainer<? extends SpotBugsReport>>))

//noinspection GroovyAssignabilityCheck
task "${it.name}Report" {
def input = file(reports.getByName("TEXT").destination)
inputs.file input
doLast {
input.readLines().forEach {
println(it)
}
}
}
it.finalizedBy "${it.name}Report"
}

spotbugsMain {
classes = classes.filter {
!it.path.contains(new File('/org/jivesoftware/openfire/plugin/passwordreset/jsp/').path)
}
}

dependencies {
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"

testCompileOnly "org.projectlombok:lombok:${lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"

implementation 'com.github.bbottema:emailaddress-rfc2822:2.1.4'

testImplementation 'com.github.spotbugs:spotbugs-annotations:4.0.1'
testImplementation platform('org.junit:junit-bom:5.6.2')
testImplementation 'org.junit.jupiter:junit-jupiter-api'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
testImplementation 'org.mockito:mockito-junit-jupiter:3.3.3'
testImplementation 'org.assertj:assertj-core:3.11.1'
import com.github.spotbugs.snom.Confidence
import com.github.spotbugs.snom.Effort
import com.github.spotbugs.snom.SpotBugsReport
import com.github.spotbugs.snom.SpotBugsTask

plugins {
id 'java-library'
id 'maven-publish'
id 'checkstyle'
id 'com.github.spotbugs' version '6.0.27'
id 'com.github.ben-manes.versions' version '0.51.0'
}

ext {
minOpenfireVersion = '4.7.0'
pluginName = 'Password Reset'
pluginDescription = 'Provides the ability for users to reset their own passwords if they have forgotten them.'
}

java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
withJavadocJar()
withSourcesJar()
}

apply from: 'build.openfire-plugin.gradle'

test {
useJUnitPlatform()
testLogging {
showStandardStreams = true
}
}

checkstyle {
toolVersion = '8.31'
maxWarnings = 0
}

tasks.withType(Checkstyle).configureEach {
reports {
xml.required = false
html.required = true
}
exclude '**/org/jivesoftware/openfire/plugin/passwordreset/jsp/**'
}

spotbugs {
effort = Effort.MAX
reportLevel = Confidence.values()[0] // LOW - See also https://github.com/spotbugs/spotbugs-gradle-plugin/issues/972
ignoreFailures.set false
extraArgs.add "-longBugCodes"
}

//noinspection ConfigurationAvoidance - as this registers a new task, we can't use .forEach
tasks.withType(SpotBugsTask) {
reports(({
text.enabled = true
xml.enabled = false
} as Closure<NamedDomainObjectContainer<? extends SpotBugsReport>>))

//noinspection GroovyAssignabilityCheck
tasks.register("${it.name}Report") {
def input = reports.named("text").get().outputLocation.asFile.get()
inputs.file input
doLast {
input.readLines().forEach {
println(it)
}
}
}
it.finalizedBy "${it.name}Report"
}

spotbugsMain {
classes = classes.filter {
!it.path.contains(new File('/org/jivesoftware/openfire/plugin/passwordreset/jsp/').path)
}
}

dependencies {

def lombok = 'org.projectlombok:lombok:1.18.36'

annotationProcessor lombok

compileOnly lombok
compileOnly 'com.github.spotbugs:spotbugs-annotations:4.8.6'

implementation 'com.github.bbottema:emailaddress-rfc2822:2.3.1'

testAnnotationProcessor lombok

testCompileOnly lombok

testImplementation 'com.github.spotbugs:spotbugs-annotations:4.0.1'
testImplementation platform('org.junit:junit-bom:5.11.4')
testImplementation 'org.junit.jupiter:junit-jupiter-api'
testImplementation 'org.mockito:mockito-junit-jupiter:5.14.2'
testImplementation 'org.assertj:assertj-core:3.27.0'

testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

dependencyUpdates.gradleReleaseChannel="current"

// See https://github.com/jeremylong/DependencyCheck/issues/2764#issuecomment-680680558 flr an expla nation
dependencies {
components {
withModule('org.dom4j:dom4j', ClearDependencies)
}
}

class ClearDependencies implements ComponentMetadataRule {
void execute(ComponentMetadataContext context) {
context.details.allVariants { withDependencies { clear() } }
}
}
111 changes: 64 additions & 47 deletions build.openfire-plugin.gradle
Original file line number Diff line number Diff line change
@@ -6,21 +6,26 @@ import java.time.Instant
repositories {
mavenCentral()
maven {
url 'https://maven.atlassian.com/repository/public'
url = 'https://maven.atlassian.com/repository/public'
}
maven {
url 'https://igniterealtime.org/archiva/repository/maven/'
url = 'https://igniterealtime.org/archiva/repository/maven/'
}
}

configurations {
jspc
}

dependencies {
compileOnly "org.igniterealtime.openfire:xmppserver:${minOpenfireVersion}"
testImplementation "org.igniterealtime.openfire:xmppserver:${minOpenfireVersion}"
jspc 'org.apache.ant:ant:1.10.15'
}

def canonicalName = project.name.replaceAll('\\W', '').toLowerCase()

task confirmChangeLog() {
tasks.register('confirmChangeLog') {
group = 'verification'
description = 'Checks the changelog contains the current date - but only if this is not a SNAPSHOT version'
def changelog = new File('src/plugin/changelog.html')
@@ -35,8 +40,8 @@ task confirmChangeLog() {
tasks.confirmChangeLog.onlyIf { !(project.version as String).contains("SNAPSHOT") }
tasks.check.dependsOn tasks.confirmChangeLog

task jspcLoggingProperties(type: WriteProperties) {
outputFile = file("$buildDir/jspc-log4j/log4j2.properties")
tasks.register('jspcLoggingProperties', WriteProperties) {
destinationFile = file("${layout.buildDirectory.get()}/jspc-log4j/log4j2.properties")
property('appender.console.type', 'Console')
property('appender.console.name', 'STDOUT')
property('appender.console.layout.type', 'PatternLayout')
@@ -47,9 +52,13 @@ def jspCompile(File srcDir, File destDir, File mergedWebXml, String javaPackage)
def xmlFragment = file("${destDir}/web.xml.fragment")
// Create the target WEB-INF folder so the JspC can create the web.xml.partial
xmlFragment.getParentFile().mkdirs()
javaexec {
classpath = files(sourceSets.main.compileClasspath, tasks.jspcLoggingProperties.outputFile.parent)
main = 'org.apache.jasper.JspC'
providers.javaexec {
classpath = files(
sourceSets.main.compileClasspath,
tasks.jspcLoggingProperties.destinationFile.getAsFile().get().parent,
configurations.jspc
)
mainClass = 'org.apache.jasper.JspC'
args = ['-webapp', srcDir.absolutePath,
'-d', file("${destDir}/java").absolutePath,
'-p', javaPackage,
@@ -72,10 +81,11 @@ def jspCompile(File srcDir, File destDir, File mergedWebXml, String javaPackage)
}
}

task jspcAdmin(dependsOn: [jspcLoggingProperties]) {
tasks.register('jspcAdmin') {
dependsOn jspcLoggingProperties
ext.inputDir = file('src/main/webapp-admin')
ext.outputDir = file("${buildDir}/generated/sources/jsp-admin")
ext.webXml = file("$outputDir/web.xml")
ext.outputDir = file("${layout.buildDirectory.get()}/generated/sources/jsp-admin")
ext.webXml = file("${outputDir}/web.xml")
inputs.dir inputDir
outputs.dir outputDir
doFirst {
@@ -87,10 +97,11 @@ tasks.jspcAdmin.onlyIf { !tasks.jspcAdmin.inputs.files.empty }
tasks.compileJava.dependsOn tasks.jspcAdmin
sourceSets.main.java.srcDirs file("${jspcAdmin.outputDir}/java").absolutePath

task jspcClient(dependsOn: [jspcLoggingProperties]) {
tasks.register('jspcClient') {
dependsOn jspcLoggingProperties
ext.inputDir = file('src/main/webapp-client')
ext.outputDir = file("${buildDir}/generated/sources/jsp-client")
ext.webXml = file("$outputDir/web.xml")
ext.outputDir = file("${layout.buildDirectory.get()}/generated/sources/jsp-client")
ext.webXml = file("${outputDir}/web.xml")
inputs.dir inputDir
outputs.dir outputDir
doFirst {
@@ -102,7 +113,10 @@ tasks.jspcClient.onlyIf { !tasks.jspcClient.inputs.files.empty }
tasks.compileJava.dependsOn tasks.jspcClient
sourceSets.main.java.srcDirs file("${jspcClient.outputDir}/java").absolutePath

task openfirePluginAssembly(type: Jar, dependsOn: [jar]) {
tasks.sourcesJar.dependsOn jspcAdmin, jspcClient

tasks.register('openfirePluginAssembly', Jar) {
dependsOn jar
dependsOn configurations.runtimeClasspath
group = 'build'
description = 'Assembles the Openfire-specific plugin JAR file'
@@ -121,12 +135,12 @@ task openfirePluginAssembly(type: Jar, dependsOn: [jar]) {
from('src/plugin') {
filesMatching('plugin.xml') {
filter(ReplaceTokens, tokens: [
name : project.pluginName,
description : project.description,
version : project.version,
name : pluginName,
description : pluginDescription,
version : version,
releaseDate : new Date().format("yyyy-MM-dd"),
minOpenfireVersion: minOpenfireVersion,
javaVersion : java.targetCompatibility as String
javaVersion : java.toolchain.languageVersion.get().toString()
])
}
}
@@ -156,32 +170,35 @@ tasks.processResources.enabled = false
// But ensure runtime resources are added to the test runtime
sourceSets.test.resources.srcDir 'src/main/resources'

task deleteOldPluginInOpenfire(type: Delete) {
tasks.register('deleteOldPluginInOpenfire', Delete) {
group = 'deploy'
description = 'Deletes the current plugin JAR file in the Openfire plugins directory. ' +
'Requires the OPENFIRE_HOME environment variable to bet set appropriately.'
doFirst {
if (System.env.OPENFIRE_HOME == null) {
throw new Exception('Unable to delete existing plugin JAR file; OPENFIRE_HOME environment variable is not set')
}
def pluginDir = new File("${System.env.OPENFIRE_HOME}/plugins")
checkOpenfireHomeExists()
def pluginDir = new File("${System.getenv('OPENFIRE_HOME')}/plugins")
if (!pluginDir.exists() || !pluginDir.isDirectory()) {
throw new Exception('Unable to deploy; OPENFIRE_HOME is not set to an Openfire folder')
}
}
delete "${System.env.OPENFIRE_HOME}/plugins/${canonicalName}.jar"
delete "${System.getenv('OPENFIRE_HOME')}/plugins/${canonicalName}.jar"
}

static def checkOpenfireHomeExists() {
if (System.getenv('OPENFIRE_HOME') == null) {
throw new Exception('Unable to delete existing plugin JAR file; OPENFIRE_HOME environment variable is not set (remember to gradlew --stop)')
}
}

task waitForOpenfireToUnloadPlugin(dependsOn: [deleteOldPluginInOpenfire]) {
tasks.register('waitForOpenfireToUnloadPlugin') {
dependsOn deleteOldPluginInOpenfire
group = 'deploy'
description = 'Waits for Openfire to unload the current plugin. Note that the Jetty bug at ' +
'https://github.com/eclipse/jetty.project/issues/1425 means plugins cannot always be unloaded without restarting Openfire.'
doFirst {
if (System.env.OPENFIRE_HOME == null) {
throw new Exception('Unable to wait for existing plugin to unload; OPENFIRE_HOME environment variable is not set')
}
checkOpenfireHomeExists()
def startTime = Instant.now()
def pluginFolder = new File("${System.env.OPENFIRE_HOME}/plugins/${canonicalName}")
def pluginFolder = new File("${System.getenv('OPENFIRE_HOME')}/plugins/${canonicalName}")
print "Waiting for Openfire to unload old ${canonicalName}.jar "
while (pluginFolder.exists() && (startTime + Duration.ofMinutes(1)) > Instant.now()) {
print '.'
@@ -196,28 +213,26 @@ task waitForOpenfireToUnloadPlugin(dependsOn: [deleteOldPluginInOpenfire]) {
}
tasks.waitForOpenfireToUnloadPlugin.mustRunAfter(tasks.check)

task copyNewPlugin(type: Copy, dependsOn: [openfirePluginAssembly, waitForOpenfireToUnloadPlugin]) {
tasks.register('copyNewPlugin', Copy) {
dependsOn openfirePluginAssembly, waitForOpenfireToUnloadPlugin
group = 'deploy'
description = "Copies the plugin to the Openfire plugins directory."
from openfirePluginAssembly.archiveFile
into "${System.env.OPENFIRE_HOME}/plugins"
into "${System.getenv('OPENFIRE_HOME')}/plugins"
rename ".*", "${canonicalName}.jar"
doFirst {
if (System.env.OPENFIRE_HOME == null) {
throw new Exception('Unable to copy the new plugin; OPENFIRE_HOME environment variable is not set')
}
checkOpenfireHomeExists()
}
}

task deploy(dependsOn: [copyNewPlugin]) {
tasks.register('deploy') {
dependsOn copyNewPlugin
group = 'deploy'
description = 'Waits for Openfire to load the new plugin.'
doFirst {
if (System.env.OPENFIRE_HOME == null) {
throw new Exception('Unable to install new plugin; OPENFIRE_HOME environment variable is not set')
}
checkOpenfireHomeExists()
def startTime = Instant.now()
def pluginFolder = new File("${System.env.OPENFIRE_HOME}/plugins/${canonicalName}")
def pluginFolder = new File("${System.getenv('OPENFIRE_HOME')}/plugins/${canonicalName}")
print "Waiting for Openfire to install new ${canonicalName}.jar "
while (!pluginFolder.exists() && (startTime + Duration.ofMinutes(1)) > Instant.now()) {
print '.'
@@ -233,12 +248,14 @@ task deploy(dependsOn: [copyNewPlugin]) {

publishing {
publications {
mavenJava(MavenPublication) {
plugin(MavenPublication) {
from components.java
artifact source: openfirePluginAssembly
artifact openfirePluginAssembly
pom {
name = project.name
description = project.description
groupId = 'org.igniterealtime.openfire.plugins'
artifactId = canonicalName
name = pluginName
description = pluginDescription
url = 'https://igniterealtime.org/projects/openfire/plugin-archive.jsp?plugin=' + project.name
}
}
@@ -247,10 +264,10 @@ publishing {

maven {
credentials {
username System.getenv("IGNITE_REALTIME_MAVEN_USERNAME")
password System.getenv("IGNITE_REALTIME_MAVEN_PASSWORD")
username = System.getenv("IGNITE_REALTIME_MAVEN_USERNAME")
password = System.getenv("IGNITE_REALTIME_MAVEN_PASSWORD")
}
url 'https://igniterealtime.org/archiva/repository/maven/'
url = 'https://igniterealtime.org/archiva/repository/maven/'
}
}
}
7 changes: 2 additions & 5 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
minOpenfireVersion=4.5.0
version=0.0.1-SNAPSHOT
name=PasswordReset
description=Provides the ability for users to reset their own passwords if they have forgotten them.
pluginName=Password Reset
version=0.0.1-SNAPSHOT
name=PasswordReset
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
4 changes: 3 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
284 changes: 175 additions & 109 deletions gradlew
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh

#
# Copyright 2015 the original author or authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,69 +15,103 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0

# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum

warn () {
echo "$*"
}
} >&2

die () {
echo
echo "$*"
echo
exit 1
}
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,88 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

JAVACMD=`cygpath --unix "$JAVACMD"`

# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )

JAVACMD=$( cygpath --unix "$JAVACMD" )

# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option

if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
i=`expr $i + 1`
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi

# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'

exec "$JAVACMD" "$@"
56 changes: 23 additions & 33 deletions gradlew.bat
Original file line number Diff line number Diff line change
@@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@@ -40,63 +43,50 @@ if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if %ERRORLEVEL% equ 0 goto execute

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal
3 changes: 2 additions & 1 deletion src/lombok.config
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true
lombok.addLombokGeneratedAnnotation = true
lombok.extern.findbugs.addSuppressFBWarnings = true
Original file line number Diff line number Diff line change
@@ -1,76 +1,75 @@
package org.jivesoftware.openfire.plugin.passwordreset;

import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.util.EmailService;

public class PasswordResetMailer {

// Avoid sending emails to domains that are "special"
// https://en.wikipedia.org/wiki/Example.com
// https://en.wikipedia.org/wiki/.local
// https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains
private static final Set<String> IGNORED_DOMAINS = new HashSet<>(
Arrays.asList(
"example.com",
"example.net",
"example.org",
"example.edu",
"local",
"example",
"invalid",
"localhost",
"test"
));

private final EmailService emailService;

public PasswordResetMailer(final EmailService emailService) {
this.emailService = emailService;
}

/**
* Sends a password reset email. N
*
* @param user the user to whom the reset should be sent.
* @param token the token used to identify the request
*/
public void sendEmail(final User user, final String token) {
final String email = user.getEmail();
// Ignore empty email address
if (email == null || email.isEmpty()) {
return;
}

// Ignore email addresses from (English) special domains
final String lowerCaseEmail = email.toLowerCase(Locale.ENGLISH);
for (final String ignoredDomain : IGNORED_DOMAINS) {
if (lowerCaseEmail.endsWith(ignoredDomain)) {
return;
}
}

final URI uri = URI.create(PasswordResetPlugin.SERVER.getValue()
+ "/change-password?token=" + token);
final String subject = substitute(PasswordResetPlugin.SUBJECT.getValue(), user, uri);
final String body = substitute(PasswordResetPlugin.BODY.getValue(), user, uri);

emailService.sendMessage(user.getName(), email,
PasswordResetPlugin.SENDER_NAME.getValue(),
PasswordResetPlugin.SENDER_ADDRESS.getValue(),
subject, body, null);
}

private String substitute(
final String stringToSubstitute, final User user, final URI uri) {
return stringToSubstitute.replace("${url}", uri.toASCIIString())
.replace("${userId}", user.getUsername())
.replace("${userName}", user.getName())
.replace("${userEmail}", user.getEmail());
}

}
package org.jivesoftware.openfire.plugin.passwordreset;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.net.URI;
import java.util.Locale;
import java.util.Set;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.util.EmailService;

@SuppressFBWarnings({"EI_EXPOSE_REP2"})
public class PasswordResetMailer {

// Avoid sending emails to domains that are "special"
// https://en.wikipedia.org/wiki/Example.com
// https://en.wikipedia.org/wiki/.local
// https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains
private static final Set<String> IGNORED_DOMAINS = Set.of(
"example.com",
"example.net",
"example.org",
"example.edu",
"local",
"example",
"invalid",
"localhost",
"test"
);

private final EmailService emailService;

public PasswordResetMailer(final EmailService emailService) {
this.emailService = emailService;
}

/**
* Sends a password reset email. N
*
* @param user the user to whom the reset should be sent.
* @param token the token used to identify the request
*/
public void sendEmail(final User user, final String token) {
final String email = user.getEmail();
// Ignore empty email address
if (email == null || email.isEmpty()) {
return;
}

// Ignore email addresses from (English) special domains
final String lowerCaseEmail = email.toLowerCase(Locale.ENGLISH);
for (final String ignoredDomain : IGNORED_DOMAINS) {
if (lowerCaseEmail.endsWith(ignoredDomain)) {
return;
}
}

final URI uri = URI.create(PasswordResetPlugin.SERVER.getValue()
+ "/change-password?token=" + token);
final String subject = substitute(PasswordResetPlugin.SUBJECT.getValue(), user, uri);
final String body = substitute(PasswordResetPlugin.BODY.getValue(), user, uri);

emailService.sendMessage(user.getName(), email,
PasswordResetPlugin.SENDER_NAME.getValue(),
PasswordResetPlugin.SENDER_ADDRESS.getValue(),
subject, body, null);
}

private String substitute(
final String stringToSubstitute, final User user, final URI uri) {
return stringToSubstitute.replace("${url}", uri.toASCIIString())
.replace("${userId}", user.getUsername())
.replace("${userName}", user.getName())
.replace("${userEmail}", user.getEmail());
}

}
Original file line number Diff line number Diff line change
@@ -1,179 +1,184 @@
package org.jivesoftware.openfire.plugin.passwordreset;

import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.http.HttpBindManager;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.util.EmailService;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.SystemProperty;

@Slf4j
public class PasswordResetPlugin implements Plugin {

public static final String PLUGIN_NAME = "Password Reset"; // Exact match to plugin.xml
public static final SystemProperty<Boolean> ENABLED =
SystemProperty.Builder.ofType(Boolean.class)
.setKey("plugin.passwordreset.enabled")
.setDefaultValue(Boolean.FALSE)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SERVER =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.server")
.setDefaultValue("")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SENDER_NAME =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.sender-name")
.setDefaultValue("Openfire")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SENDER_ADDRESS =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.sender-address")
.setDefaultValue("admin@example.com")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SUBJECT =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.email-subject")
.setDefaultValue("Openfire password reset")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> BODY =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.email-body")
.setDefaultValue("Dear ${userName}\n\n"
+ "To reset the password for your ${userId} Openfire account, simply go to ${url}"
+ " at any time in the next five hours. After this time, you will need to request"
+ " another reset email is sent to you.")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Duration> EXPIRY =
SystemProperty.Builder.ofType(Duration.class)
.setChronoUnit(ChronoUnit.MINUTES)
.setKey("plugin.passwordreset.reset-expiry")
.setDefaultValue(Duration.ofHours(5))
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Integer> MIN_LENGTH =
SystemProperty.Builder.ofType(Integer.class)
.setKey("plugin.passwordreset.min-length")
.setMinValue(1)
.setDefaultValue(8)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Integer> MAX_LENGTH =
SystemProperty.Builder.ofType(Integer.class)
.setKey("plugin.passwordreset.max-length")
.setMinValue(0)
.setDefaultValue(0)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final String CONTEXT_PATH = "/passwordreset";
private static String canonicalName;
private static PasswordResetPlugin plugin;
private final HttpBindManager httpBindManager;
private final PasswordResetMailer passwordResetMailer;
private final PasswordResetTokenManager resetTokenManager;
private WebAppContext webAppContext;

private static void setInstance(final PasswordResetPlugin plugin) {
PasswordResetPlugin.plugin = plugin;
}

private static void setCanonicalName(final String canonicalName) {
PasswordResetPlugin.canonicalName = canonicalName;
}

public static PasswordResetPlugin getInstance() {
return plugin;
}

/**
* Default constructor for the plugin.
*/
public PasswordResetPlugin() {
setInstance(this);
this.httpBindManager = HttpBindManager.getInstance();
this.passwordResetMailer = new PasswordResetMailer(EmailService.getInstance());
this.resetTokenManager = new PasswordResetTokenManager(
DbConnectionManager::getConnection,
UserManager.getInstance());
setBlankServerDetails();
log.debug("Plugin created");
}

public static String localize(final String key, final Object... arguments) {
return LocaleUtils.getLocalizedString(key, canonicalName, Arrays.asList(arguments));
}

private void setBlankServerDetails() {
if (SERVER.getValue().isEmpty()) {
// Set a default value for this as there isn't one already
final String defaultUrl;
if (httpBindManager.isHttpsBindActive()) {
defaultUrl = String.format("https://%s:%d%s",
XMPPServer.getInstance().getServerInfo().getHostname(),
httpBindManager.getHttpBindSecurePort(),
CONTEXT_PATH);
} else {
defaultUrl = String.format("http://%s:%d%s",
XMPPServer.getInstance().getServerInfo().getHostname(),
httpBindManager.getHttpBindUnsecurePort(),
CONTEXT_PATH);
}
SERVER.setValue(defaultUrl);
}
}

@Override
public void initializePlugin(final PluginManager manager, final File pluginDirectory) {
log.debug("Plugin initialisation started");

setCanonicalName(manager.getCanonicalName(this));

webAppContext = new WebAppContext(pluginDirectory.getPath() + "/web-client",
CONTEXT_PATH);
webAppContext.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
httpBindManager.addJettyHandler(webAppContext);

log.debug("Plugin initialisation complete");
}

@Override
public void destroyPlugin() {
log.debug("Plugin destruction started");
httpBindManager.removeJettyHandler(webAppContext);
log.debug("Plugin destruction complete");
}

public PasswordResetMailer getPasswordResetMailer() {
return passwordResetMailer;
}

public PasswordResetTokenManager getResetTokenManager() {
return resetTokenManager;
}
}
package org.jivesoftware.openfire.plugin.passwordreset;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.http.HttpBindManager;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.util.EmailService;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.SystemProperty;

@Slf4j
@SuppressFBWarnings({"EI_EXPOSE_REP", "MS_EXPOSE_REP"})
public class PasswordResetPlugin implements Plugin {

public static final String PLUGIN_NAME = "Password Reset"; // Exact match to plugin.xml
public static final SystemProperty<Boolean> ENABLED =
SystemProperty.Builder.ofType(Boolean.class)
.setKey("plugin.passwordreset.enabled")
.setDefaultValue(Boolean.FALSE)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SERVER =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.server")
.setDefaultValue("")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SENDER_NAME =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.sender-name")
.setDefaultValue("Openfire")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SENDER_ADDRESS =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.sender-address")
.setDefaultValue("admin@example.com")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> SUBJECT =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.email-subject")
.setDefaultValue("Openfire password reset")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<String> BODY =
SystemProperty.Builder.ofType(String.class)
.setKey("plugin.passwordreset.email-body")
.setDefaultValue("Dear ${userName}\n\n"
+ "To reset the password for your ${userId} Openfire account, simply go to ${url}"
+ " at any time in the next five hours. After this time, you will need to request"
+ " another reset email is sent to you.")
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Duration> EXPIRY =
SystemProperty.Builder.ofType(Duration.class)
.setChronoUnit(ChronoUnit.MINUTES)
.setKey("plugin.passwordreset.reset-expiry")
.setDefaultValue(Duration.ofHours(5))
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Integer> MIN_LENGTH =
SystemProperty.Builder.ofType(Integer.class)
.setKey("plugin.passwordreset.min-length")
.setMinValue(1)
.setDefaultValue(8)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final SystemProperty<Integer> MAX_LENGTH =
SystemProperty.Builder.ofType(Integer.class)
.setKey("plugin.passwordreset.max-length")
.setMinValue(0)
.setDefaultValue(0)
.setDynamic(true)
.setPlugin(PLUGIN_NAME)
.build();
public static final String CONTEXT_PATH = "/passwordreset";
private static String canonicalName;
private static PasswordResetPlugin plugin;
private final HttpBindManager httpBindManager;
private final PasswordResetMailer passwordResetMailer;
private final PasswordResetTokenManager resetTokenManager;
private WebAppContext webAppContext;

private static void setInstance(final PasswordResetPlugin plugin) {
PasswordResetPlugin.plugin = plugin;
}

private static void setCanonicalName(final String canonicalName) {
PasswordResetPlugin.canonicalName = canonicalName;
}

public static PasswordResetPlugin getInstance() {
return plugin;
}

/**
* Default constructor for the plugin.
*/
public PasswordResetPlugin() {
setInstance(this);
this.httpBindManager = HttpBindManager.getInstance();
this.passwordResetMailer = new PasswordResetMailer(EmailService.getInstance());
this.resetTokenManager = new PasswordResetTokenManager(
DbConnectionManager::getConnection,
UserManager.getInstance()
);
setBlankServerDetails();
log.debug("Plugin created");
}

public static String localize(final String key, final Object... arguments) {
return LocaleUtils.getLocalizedString(key, canonicalName, Arrays.asList(arguments));
}

private void setBlankServerDetails() {
if (SERVER.getValue().isEmpty()) {
// Set a default value for this as there isn't one already
final String defaultUrl;
if (httpBindManager.isHttpsBindActive()) {
defaultUrl = String.format("https://%s:%d%s",
XMPPServer.getInstance().getServerInfo().getHostname(),
HttpBindManager.HTTP_BIND_SECURE_PORT.getValue(),
CONTEXT_PATH
);
} else {
defaultUrl = String.format("http://%s:%d%s",
XMPPServer.getInstance().getServerInfo().getHostname(),
HttpBindManager.HTTP_BIND_PORT.getValue(),
CONTEXT_PATH
);
}
SERVER.setValue(defaultUrl);
}
}

@Override
public void initializePlugin(final PluginManager manager, final File pluginDirectory) {
log.debug("Plugin initialisation started");

setCanonicalName(manager.getCanonicalName(this));

webAppContext = new WebAppContext(pluginDirectory.getPath() + "/web-client",
CONTEXT_PATH);
webAppContext.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
httpBindManager.addJettyHandler(webAppContext);

log.debug("Plugin initialisation complete");
}

@Override
public void destroyPlugin() {
log.debug("Plugin destruction started");
httpBindManager.removeJettyHandler(webAppContext);
log.debug("Plugin destruction complete");
}

public PasswordResetMailer getPasswordResetMailer() {
return passwordResetMailer;
}

public PasswordResetTokenManager getResetTokenManager() {
return resetTokenManager;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.jivesoftware.openfire.plugin.passwordreset;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -19,6 +20,7 @@
import org.jivesoftware.util.StringUtils;

@Slf4j
@SuppressFBWarnings({"EI_EXPOSE_REP2"})
public class PasswordResetTokenManager {

private static final int TOKEN_LENGTH = 32;

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@
import org.jivesoftware.util.JiveGlobals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.quality.Strictness;
import org.xmpp.packet.JID;

@SuppressWarnings({"WeakerAccess"})
@@ -73,7 +74,10 @@ public static void clearExistingProperties() {
value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT",
justification = "False positive")
public static XMPPServer mockXmppServer() {
final XMPPServer xmppServer = mock(XMPPServer.class, withSettings().lenient());
final XMPPServer xmppServer = mock(
XMPPServer.class,
withSettings().strictness(Strictness.LENIENT)
);
doAnswer(invocationOnMock -> {
final JID jid = invocationOnMock.getArgument(0);
return jid.getDomain().equals(XMPP_DOMAIN);
@@ -92,7 +96,10 @@ public static XMPPServer mockXmppServer() {
* @return a mock XMPPServerInfo
*/
public static XMPPServerInfo mockXmppServerInfo() {
final XMPPServerInfo xmppServerInfo = mock(XMPPServerInfo.class, withSettings().lenient());
final XMPPServerInfo xmppServerInfo = mock(
XMPPServerInfo.class,
withSettings().strictness(Strictness.LENIENT)
);
doReturn(XMPP_DOMAIN).when(xmppServerInfo).getXMPPDomain();
return xmppServerInfo;
}
@@ -103,7 +110,7 @@ public static XMPPServerInfo mockXmppServerInfo() {
* @return a mock IQRouter
*/
public static IQRouter mockIqRouter() {
return mock(IQRouter.class, withSettings().lenient());
return mock(IQRouter.class, withSettings().strictness(Strictness.LENIENT));
}

/**
@@ -112,7 +119,7 @@ public static IQRouter mockIqRouter() {
* @return a mock PluginManager
*/
public static PluginManager mockPluginManager() {
return mock(PluginManager.class, withSettings().lenient());
return mock(PluginManager.class, withSettings().strictness(Strictness.LENIENT));
}

}
Original file line number Diff line number Diff line change
@@ -31,6 +31,7 @@
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.quality.Strictness;

@ExtendWith(MockitoExtension.class)
class PasswordResetSettingsServletTest {
@@ -94,7 +95,10 @@ void willSetAValidForm() throws Exception {
}

private HttpServletRequest blankRequest() {
final HttpServletRequest request = mock(HttpServletRequest.class, withSettings().lenient());
final HttpServletRequest request = mock(
HttpServletRequest.class,
withSettings().strictness(Strictness.LENIENT)
);
doReturn(REQUEST_URI).when(request)
.getRequestURI();
doReturn(requestDispatcher).when(request)

0 comments on commit 4a418fd

Please sign in to comment.