diff --git a/account-ui/src/main/java/de/muehlencord/shared/account/web/EnsurePermissionsBean.java b/account-ui/src/main/java/de/muehlencord/shared/account/web/EnsurePermissionsBean.java index 841ae26..c87bad2 100644 --- a/account-ui/src/main/java/de/muehlencord/shared/account/web/EnsurePermissionsBean.java +++ b/account-ui/src/main/java/de/muehlencord/shared/account/web/EnsurePermissionsBean.java @@ -1,80 +1,80 @@ -/* - * Copyright 2018 Joern Muehlencord . - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.web; - -import de.muehlencord.shared.account.business.account.boundary.AccountPermissions; -import de.muehlencord.shared.account.business.account.entity.AccountException; -import de.muehlencord.shared.account.business.instance.boundary.ApplicationPermissions; -import de.muehlencord.shared.account.business.application.control.ApplicationPermissionControl; -import de.muehlencord.shared.account.business.application.control.ApplicationRoleControl; -import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; -import java.util.Arrays; -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.event.Observes; -import javax.inject.Inject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author Joern Muehlencord - */ -@ApplicationScoped -public class EnsurePermissionsBean { - - @Inject - ApplicationEntity application; - - @Inject - ApplicationPermissionControl applicationPermissionControl; - - @Inject - ApplicationRoleControl applicationRoleControl; - - private static final Logger LOGGER = LoggerFactory.getLogger(EnsurePermissionsBean.class); - - public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Ensure all permissions for {} are available", application.getApplicationName()); - } - applicationPermissionControl.setupPermissions(Arrays.asList(ApplicationPermissions.values())); - applicationPermissionControl.setupPermissions(Arrays.asList(AccountPermissions.values())); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("All permissions added to application", application.getApplicationName()); - } - - // all permissions available - ensure permission is assigned to Admin role - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Ensuring Admin role for {} has all permissions", application.getApplicationName()); - } - try { - applicationRoleControl.setupRolePermission(Arrays.asList(ApplicationPermissions.values()), "Admin"); // NOI18N - applicationRoleControl.setupRolePermission(Arrays.asList(AccountPermissions.values()), "Admin"); // NOI18N - } catch (AccountException ex) { - LOGGER.error("Error adding permission to Admin role. Reason={}", ex.getMessage()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Detailed stacktrace", new Object[]{ex}); - } - - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("All permissions added to Admin role of {}", application.getApplicationName()); - } - - } - -} +/* + * Copyright 2018 Joern Muehlencord . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.web; + +import de.muehlencord.shared.account.business.account.boundary.AccountPermissions; +import de.muehlencord.shared.account.business.account.entity.AccountException; +import de.muehlencord.shared.account.business.application.control.ApplicationPermissionControl; +import de.muehlencord.shared.account.business.application.control.ApplicationRoleControl; +import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; +import de.muehlencord.shared.account.business.instance.boundary.ApplicationPermissions; +import java.util.Arrays; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Observes; +import javax.inject.Inject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author Joern Muehlencord + */ +@ApplicationScoped +public class EnsurePermissionsBean { + + @Inject + ApplicationEntity application; + + @Inject + ApplicationPermissionControl applicationPermissionControl; + + @Inject + ApplicationRoleControl applicationRoleControl; + + private static final Logger LOGGER = LoggerFactory.getLogger(EnsurePermissionsBean.class); + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Ensure all permissions for {} are available", application.getApplicationName()); + } + applicationPermissionControl.setupPermissions(Arrays.asList(ApplicationPermissions.values())); + applicationPermissionControl.setupPermissions(Arrays.asList(AccountPermissions.values())); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("All permissions added to application", application.getApplicationName()); + } + + // all permissions available - ensure permission is assigned to Admin role + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Ensuring Admin role for {} has all permissions", application.getApplicationName()); + } + try { + applicationRoleControl.setupRolePermission(Arrays.asList(ApplicationPermissions.values()), "Admin"); // NOI18N + applicationRoleControl.setupRolePermission(Arrays.asList(AccountPermissions.values()), "Admin"); // NOI18N + } catch (AccountException ex) { + LOGGER.error("Error adding permission to Admin role. Reason={}", ex.getMessage()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Detailed stacktrace", new Object[]{ex}); + } + + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("All permissions added to Admin role of {}", application.getApplicationName()); + } + + } + +} diff --git a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/InstanceView.java b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/InstanceView.java index 5137905..0043097 100644 --- a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/InstanceView.java +++ b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/InstanceView.java @@ -1,55 +1,55 @@ -package de.muehlencord.shared.account.web.presentation; - -import de.muehlencord.shared.account.business.instance.control.ApplicationController; -import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; -import de.muehlencord.shared.account.business.config.boundary.ConfigService; -import de.muehlencord.shared.account.business.config.entity.ConfigException; -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Inject; -import javax.inject.Named; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * TODO - move to shared-account and remove from all applications and archetype - * - * @author Joern Muehlencord - */ -@Named(value = "instanceView") -@ApplicationScoped -public class InstanceView { - - private static final Logger LOGGER = LoggerFactory.getLogger(InstanceView.class); - - @Inject - ConfigService configService; - - @Inject - ApplicationController applicationController; - - public boolean isDevelopmentVersion() { - String instanceName = getInstanceName(); - return !instanceName.equals("Production"); - } - - public String getInstanceName() { - String instanceName; - try { - instanceName = configService.getConfigValue("base.instance"); - } catch (ConfigException ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Detailed stacktrace", new Object[]{ex}); - } - instanceName = "unknown (" + ex.toString() + ")"; - } - if (instanceName == null) { - return "unknown"; - } else { - return instanceName; - } - } - - public ApplicationEntity getInstanceApplication() { - return applicationController.getApplication(); - } -} +package de.muehlencord.shared.account.web.presentation; + +import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; +import de.muehlencord.shared.account.business.config.boundary.ConfigService; +import de.muehlencord.shared.account.business.config.entity.ConfigException; +import de.muehlencord.shared.account.business.instance.control.ApplicationController; +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.inject.Named; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * TODO - move to shared-account and remove from all applications and archetype + * + * @author Joern Muehlencord + */ +@Named(value = "instanceView") +@ApplicationScoped +public class InstanceView { + + private static final Logger LOGGER = LoggerFactory.getLogger(InstanceView.class); + + @Inject + ConfigService configService; + + @Inject + ApplicationController applicationController; + + public boolean isDevelopmentVersion() { + String instanceName = getInstanceName(); + return !instanceName.equals("Production"); + } + + public String getInstanceName() { + String instanceName; + try { + instanceName = configService.getConfigValue("base.instance"); + } catch (ConfigException ex) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Detailed stacktrace", new Object[]{ex}); + } + instanceName = "unknown (" + ex.toString() + ")"; + } + if (instanceName == null) { + return "unknown"; + } else { + return instanceName; + } + } + + public ApplicationEntity getInstanceApplication() { + return applicationController.getApplication(); + } +} diff --git a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationRoleNameValidator.java b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationRoleNameValidator.java index e3c046f..0f977e9 100644 --- a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationRoleNameValidator.java +++ b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationRoleNameValidator.java @@ -1,7 +1,10 @@ package de.muehlencord.shared.account.web.presentation; +import de.muehlencord.shared.account.business.application.control.ApplicationRoleControl; +import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; +import de.muehlencord.shared.account.business.application.entity.ApplicationRoleEntity; +import de.muehlencord.shared.account.util.AccountPU; import java.io.Serializable; - import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; @@ -12,11 +15,6 @@ import javax.faces.validator.ValidatorException; import javax.inject.Inject; import javax.persistence.EntityManager; -import de.muehlencord.shared.account.business.application.control.ApplicationRoleControl; -import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; -import de.muehlencord.shared.account.business.application.entity.ApplicationRoleEntity; -import de.muehlencord.shared.account.util.AccountPU; - /** * * @author Joern Muehlencord diff --git a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationValidator.java b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationValidator.java index 67b53b0..ba0870a 100644 --- a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationValidator.java +++ b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniqueApplicationValidator.java @@ -1,7 +1,8 @@ package de.muehlencord.shared.account.web.presentation; +import de.muehlencord.shared.account.business.application.control.ApplicationControl; +import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import java.io.Serializable; - import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; @@ -10,13 +11,9 @@ import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import javax.inject.Inject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import de.muehlencord.shared.account.business.application.control.ApplicationControl; -import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; - /** * * @author Joern Muehlencord diff --git a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniquePermissionNameValidator.java b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniquePermissionNameValidator.java index 36be332..177edfe 100644 --- a/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniquePermissionNameValidator.java +++ b/account-ui/src/main/java/de/muehlencord/shared/account/web/presentation/UniquePermissionNameValidator.java @@ -1,8 +1,8 @@ package de.muehlencord.shared.account.web.presentation; -import de.muehlencord.shared.account.business.application.entity.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.application.control.ApplicationPermissionControl; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; +import de.muehlencord.shared.account.business.application.entity.ApplicationPermissionEntity; import de.muehlencord.shared.account.util.AccountPU; import java.io.Serializable; import javax.faces.application.FacesMessage; diff --git a/account/pom.xml b/account/pom.xml index 0a73d7a..63885ee 100644 --- a/account/pom.xml +++ b/account/pom.xml @@ -54,15 +54,20 @@ jar - junit - junit + org.junit.jupiter + junit-jupiter-engine test - + org.mockito mockito-core test + + org.mockito + mockito-junit-jupiter + test + org.slf4j slf4j-log4j12 diff --git a/account/src/main/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyService.java b/account/src/main/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyService.java index 0dbe487..8b8e841 100644 --- a/account/src/main/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyService.java +++ b/account/src/main/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyService.java @@ -163,8 +163,9 @@ public class ApiKeyService implements Serializable { @Transactional @Lock(LockType.WRITE) public ApiKeyObject createNewApiKey(String userName, short expirationInMinutes) throws ApiKeyException { - if ((password == null || issuer == null) || (userName == null)) { - LOGGER.error("password, issuer or username not set in, please validate configuration"); + if (password == null || issuer == null || userName == null) { + String hint = "password, issuer or username not set in, please validate configuration"; + throw new ApiKeyException(hint); } Date now = DateUtil.getCurrentTimeInUTC(); ZonedDateTime issuedOn = ZonedDateTime.ofInstant(now.toInstant(), ZoneId.of("UTC")); diff --git a/account/src/main/java/de/muehlencord/shared/account/business/config/boundary/ConfigService.java b/account/src/main/java/de/muehlencord/shared/account/business/config/boundary/ConfigService.java index 2549cb3..2dbd6f2 100644 --- a/account/src/main/java/de/muehlencord/shared/account/business/config/boundary/ConfigService.java +++ b/account/src/main/java/de/muehlencord/shared/account/business/config/boundary/ConfigService.java @@ -15,7 +15,6 @@ */ package de.muehlencord.shared.account.business.config.boundary; -import de.muehlencord.shared.db.ControllerException; import de.muehlencord.shared.account.business.account.entity.Account; import de.muehlencord.shared.account.business.account.entity.AccountEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; @@ -23,6 +22,7 @@ import de.muehlencord.shared.account.business.config.entity.ConfigEntity; import de.muehlencord.shared.account.business.config.entity.ConfigEntityPK; import de.muehlencord.shared.account.business.config.entity.ConfigException; import de.muehlencord.shared.account.util.AccountPU; +import de.muehlencord.shared.db.ControllerException; import java.io.Serializable; import java.util.List; import java.util.Optional; @@ -37,6 +37,7 @@ import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.transaction.Transactional; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -121,7 +122,7 @@ public class ConfigService implements Serializable { // if config value is not found null has been returned // in this case the value to return is the defaultValue - if (configValue == null) { + if (StringUtils.isEmpty(configValue)) { configValue = defaultValue; } diff --git a/account/src/main/java/de/muehlencord/shared/account/business/instance/boundary/StartupBean.java b/account/src/main/java/de/muehlencord/shared/account/business/instance/boundary/StartupBean.java index e3bcc41..0419c8f 100644 --- a/account/src/main/java/de/muehlencord/shared/account/business/instance/boundary/StartupBean.java +++ b/account/src/main/java/de/muehlencord/shared/account/business/instance/boundary/StartupBean.java @@ -15,10 +15,10 @@ */ package de.muehlencord.shared.account.business.instance.boundary; -import de.muehlencord.shared.db.ControllerException; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.config.boundary.ConfigService; import de.muehlencord.shared.account.business.config.entity.ConfigException; +import de.muehlencord.shared.db.ControllerException; import javax.annotation.PreDestroy; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Initialized; diff --git a/account/src/main/java/de/muehlencord/shared/account/presentation/LoginView.java b/account/src/main/java/de/muehlencord/shared/account/presentation/LoginView.java index 3b41cf1..e075040 100644 --- a/account/src/main/java/de/muehlencord/shared/account/presentation/LoginView.java +++ b/account/src/main/java/de/muehlencord/shared/account/presentation/LoginView.java @@ -1,202 +1,201 @@ -/* - * Copyright 2018 joern.muehlencord. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.presentation; - -import de.muehlencord.shared.account.business.account.control.AccountControl; -import de.muehlencord.shared.account.business.account.entity.AccountEntity; -import de.muehlencord.shared.jeeutil.FacesUtil; -import java.io.IOException; -import java.io.Serializable; -import javax.ejb.EJB; -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.faces.view.ViewScoped; -import javax.inject.Named; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.web.util.WebUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author joern.muehlencord - */ -@Named(value = "loginView") -@ViewScoped -public class LoginView implements Serializable { - - private static final long serialVersionUID = -1164860380769648432L; - - @EJB - private AccountControl accountService; - - private String username = null; - private String password = null; - private boolean rememberMe = false; - - private String resetPasswordToken = null; - - private static final Logger LOGGER = LoggerFactory.getLogger(LoginView.class.getName()); - - public void authenticate() { - - // Example using most common scenario of username/password pair: - UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword()); - - // "Remember Me" built-in: - token.setRememberMe(rememberMe); - Subject currentUser = SecurityUtils.getSubject(); - LOGGER.info("Trying to login user {}", username); - - try { - currentUser.login(token); - LOGGER.info("User {} logged in", username); - // user logged in, update account entity - AccountEntity account = accountService.getAccountEntity(username, true); - accountService.updateLogin(account); - - // redirect to home - ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); - ServletResponse servletResponse = (ServletResponse) ec.getResponse(); - String fallbackUrl = "/web/index.xhtml"; // TODO make configurable - // ec.redirect(url); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("redirecting to {}, fallbackUrl={}", servletResponse.toString(), fallbackUrl); - } - - WebUtils.redirectToSavedRequest((ServletRequest) ec.getRequest(), servletResponse, fallbackUrl); - } catch (IOException | AuthenticationException ex) { - // Could catch a subclass of AuthenticationException if you like - String hint = "Error while authenticating user " + username; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(hint, ex); - } - - if (ex.getMessage() != null) { - hint += "Reason: " + ex.getMessage(); - } else { - hint += "Reason: " + ex.toString(); - } - if ((ex.getCause() != null) && (ex.getCause().getMessage() != null)) { - hint += "Rootcause: " + ex.getMessage(); - - LOGGER.error(hint); - } - FacesUtil.addGlobalErrorMessage("Login failed", hint); - - AccountEntity account = accountService.getAccountEntity(username, false); - if (account != null) { - accountService.addLoginError(account); - } - } finally { - token.clear(); - } - } - - public void logout() { - Subject currentUser = SecurityUtils.getSubject(); - try { - currentUser.logout(); - - ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); - - // ensure faces session is invalidated so beans are destroyed - ec.invalidateSession(); - - // check if redirect shall be executed - // default setting is yes to /login.xhtml - // can be overwritten using parameters - // de.muehlencord.shared.account.loginview.executeredirect boolean true/false - // de.muehlencord.shared.account.loginview.redirecttarget path to redirect to (without external context, will be added automatically) - String executeRedirectString = ec.getInitParameter("de.muehlencord.shared.account.loginview.executeredirect"); - boolean executeRedirect = true; - if (executeRedirectString != null) { - executeRedirect = Boolean.parseBoolean(executeRedirectString); - } - - String redirectTarget = ec.getInitParameter("de.muehlencord.shared.account.loginview.redirecttarget"); - if ((redirectTarget == null) || (redirectTarget.equals(""))) { - redirectTarget = "/login.xhtml"; - } - - if (executeRedirect) { - String url = ec.getRequestContextPath() + redirectTarget; - ec.redirect(url); - } - - } catch (Exception e) { - LOGGER.warn(e.toString()); - } - } - - public String executePasswordReset() { - boolean passwordResetted = accountService.resetPassword(username, password, resetPasswordToken); - if (passwordResetted) { - // TODO add email notification on updated user account - FacesUtil.addGlobalInfoMessage("Password resetted", null); - return login(); - } else { - // TODO add email notificaton on failed password reset - FacesUtil.addGlobalErrorMessage("Password reset failed", null); - return login(); - } - } - - /* **** naviation rules **** */ - public String login() { - return "/login.xhtml"; // TODO make configurable - } - - /* *** getter / setter */ - public String getUsername() { - return username; - } - - public void setUsername(String un) { - this.username = un; - } - - public String getPassword() { - return password; - } - - public void setPassword(String pw) { - this.password = pw; - } - - public boolean isRememberMe() { - return rememberMe; - } - - public void setRememberMe(boolean rememberMe) { - this.rememberMe = rememberMe; - } - - public String getResetPasswordToken() { - return resetPasswordToken; - } - - public void setResetPasswordToken(String resetPasswordToken) { - this.resetPasswordToken = resetPasswordToken; - } - -} +/* + * Copyright 2018 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.presentation; + +import de.muehlencord.shared.account.business.account.control.AccountControl; +import de.muehlencord.shared.account.business.account.entity.AccountEntity; +import de.muehlencord.shared.jeeutil.FacesUtil; +import java.io.IOException; +import java.io.Serializable; +import javax.ejb.EJB; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.faces.view.ViewScoped; +import javax.inject.Named; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.util.WebUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author joern.muehlencord + */ +@Named(value = "loginView") +@ViewScoped +public class LoginView implements Serializable { + + private static final long serialVersionUID = -1164860380769648432L; + + @EJB + private AccountControl accountService; + + private String username = null; + private String password = null; + private boolean rememberMe = false; + + private String resetPasswordToken = null; + + private static final Logger LOGGER = LoggerFactory.getLogger(LoginView.class.getName()); + + public void authenticate() { + + // Example using most common scenario of username/password pair: + UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword()); + + // "Remember Me" built-in: + token.setRememberMe(rememberMe); + Subject currentUser = SecurityUtils.getSubject(); + LOGGER.info("Trying to login user {}", username); + + try { + currentUser.login(token); + LOGGER.info("User {} logged in", username); + // user logged in, update account entity + AccountEntity account = accountService.getAccountEntity(username, true); + accountService.updateLogin(account); + + // redirect to home + ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); + ServletResponse servletResponse = (ServletResponse) ec.getResponse(); + String fallbackUrl = "/web/index.xhtml"; // TODO make configurable + // ec.redirect(url); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("redirecting to {}, fallbackUrl={}", servletResponse.toString(), fallbackUrl); + } + + WebUtils.redirectToSavedRequest((ServletRequest) ec.getRequest(), servletResponse, fallbackUrl); + } catch (IOException | AuthenticationException ex) { + // Could catch a subclass of AuthenticationException if you like + String hint = "Error while authenticating user " + username; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(hint, ex); + } + + if (ex.getMessage() != null) { + hint += "Reason: " + ex.getMessage(); + } else { + hint += "Reason: " + ex.toString(); + } + if ((ex.getCause() != null) && (ex.getCause().getMessage() != null)) { + hint += "Rootcause: " + ex.getMessage(); + + LOGGER.error(hint); + } + FacesUtil.addGlobalErrorMessage("Login failed", hint); + + AccountEntity account = accountService.getAccountEntity(username, false); + if (account != null) { + accountService.addLoginError(account); + } + } finally { + token.clear(); + } + } + + public void logout() { + Subject currentUser = SecurityUtils.getSubject(); + try { + currentUser.logout(); + + ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); + + // ensure faces session is invalidated so beans are destroyed + ec.invalidateSession(); + + // check if redirect shall be executed + // default setting is yes to /login.xhtml + // can be overwritten using parameters + // de.muehlencord.shared.account.loginview.executeredirect boolean true/false + // de.muehlencord.shared.account.loginview.redirecttarget path to redirect to (without external context, will be added automatically) + String executeRedirectString = ec.getInitParameter("de.muehlencord.shared.account.loginview.executeredirect"); + boolean executeRedirect = true; + if (executeRedirectString != null) { + executeRedirect = Boolean.parseBoolean(executeRedirectString); + } + + String redirectTarget = ec.getInitParameter("de.muehlencord.shared.account.loginview.redirecttarget"); + if ((redirectTarget == null) || (redirectTarget.equals(""))) { + redirectTarget = "/login.xhtml"; + } + + if (executeRedirect) { + String url = ec.getRequestContextPath() + redirectTarget; + ec.redirect(url); + } + + } catch (Exception e) { + LOGGER.warn(e.toString()); + } + } + + public String executePasswordReset() { + boolean passwordResetted = accountService.resetPassword(username, password, resetPasswordToken); + if (passwordResetted) { + // TODO add email notification on updated user account + FacesUtil.addGlobalInfoMessage("Password resetted", null); + return login(); + } else { + // TODO add email notificaton on failed password reset + FacesUtil.addGlobalErrorMessage("Password reset failed", null); + return login(); + } + } + + /* **** naviation rules **** */ + public String login() { + return "/login.xhtml"; // TODO make configurable + } + + /* *** getter / setter */ + public String getUsername() { + return username; + } + + public void setUsername(String un) { + this.username = un; + } + + public String getPassword() { + return password; + } + + public void setPassword(String pw) { + this.password = pw; + } + + public boolean isRememberMe() { + return rememberMe; + } + + public void setRememberMe(boolean rememberMe) { + this.rememberMe = rememberMe; + } + + public String getResetPasswordToken() { + return resetPasswordToken; + } + + public void setResetPasswordToken(String resetPasswordToken) { + this.resetPasswordToken = resetPasswordToken; + } + +} diff --git a/account/src/main/java/de/muehlencord/shared/account/shiro/filter/JWTAuthenticationFilter.java b/account/src/main/java/de/muehlencord/shared/account/shiro/filter/JWTAuthenticationFilter.java index 845363c..5cc63e4 100644 --- a/account/src/main/java/de/muehlencord/shared/account/shiro/filter/JWTAuthenticationFilter.java +++ b/account/src/main/java/de/muehlencord/shared/account/shiro/filter/JWTAuthenticationFilter.java @@ -1,172 +1,169 @@ -/* - * Copyright 2018 joern.muehlencord. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.shiro.filter; - -import java.io.IOException; -import java.io.StringReader; - -import javax.json.Json; -import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.web.filter.authc.AuthenticatingFilter; -import org.apache.shiro.web.util.WebUtils; -import org.slf4j.LoggerFactory; - -import de.muehlencord.shared.account.business.account.boundary.ApiKeyService; -import de.muehlencord.shared.account.business.account.entity.JWTObject; -import de.muehlencord.shared.account.shiro.token.JWTAuthenticationToken; -import de.muehlencord.shared.account.util.AccountSecurityException; -import de.muehlencord.shared.jeeutil.restexfw.APIException; - -/** - * - * @author Joern Muehlencord - */ -public final class JWTAuthenticationFilter extends AuthenticatingFilter { - - private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(JWTAuthenticationFilter.class); - protected static final String AUTHORIZATION_HEADER = "Authorization"; // NOI18N - protected static final String USERNAME = "username"; // NOI18N - protected static final String PASSWORD = "password"; // NOI18N - - private final ApiKeyService apiKeyService = lookupApiKeyServiceBean(); - - public JWTAuthenticationFilter() { - // FIXME - logging in via JWTAuthenticationFilter does not yet work. Need to set login to anonymous to execute login in rest service - setLoginUrl("/rest/account/login"); - } - - @Override - protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { - boolean loggedIn = false; - - if (isLoginRequest(request, response) || isLoggedAttempt(request, response)) { - loggedIn = executeLogin(request, response); - } - - if (!loggedIn) { - HttpServletResponse httpResponse = WebUtils.toHttp(response); - httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - - return loggedIn; - } - - @Override - protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { - if (isLoginRequest(request, response)) { - String json = IOUtils.toString(request.getInputStream(), "UTF-8"); // FIXME - check charset in request - - if (json != null && !json.isEmpty()) { - try (JsonReader jr = Json.createReader(new StringReader(json))) { - JsonObject object = jr.readObject(); - String username = object.getString(USERNAME); - String password = object.getString(PASSWORD); - return new UsernamePasswordToken(username, password); - } - - } - } - - if (isLoggedAttempt(request, response)) { - String jwtToken = getAuthzHeader(request); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("found jwtToke in header = {}", jwtToken); - } - - if (jwtToken != null) { - JWTObject jwtObject = apiKeyService.getJWTObject(jwtToken); - return new JWTAuthenticationToken(jwtObject.getUserName(), jwtToken); - } - } - - return new UsernamePasswordToken(); - } - - private boolean isLoggedAttempt(ServletRequest request, ServletResponse response) { - String authzHeader = getAuthzHeader(request); - return authzHeader != null; - } - - private String getAuthzHeader(ServletRequest request) { - HttpServletRequest httpRequest = WebUtils.toHttp(request); - return httpRequest.getHeader(AUTHORIZATION_HEADER); - } - - - /** - * Overwrite cleanup to ensure no exception is thrown if an - * AccountSecurityException / APIException is raised during login. As long - * as the user is not logged in JERSEYs ExceptionMapper and intercepor - * classes are overruled by Shiro. - * - * @param request the incoming request - * @param response the response to return - * @param existing the raised exception - * @throws ServletException may be thrown by AuthenticatingFilter.cleanup if - * existing is not a AccountSecurityException - * @throws IOException may be thrown by AuthenticatingFilter.cleanup if - * existing is not a AccountSecurityException - */ - @Override - protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) throws ServletException, IOException { - if ((existing != null) && (existing.getClass().isAssignableFrom(AccountSecurityException.class))) { - HttpServletResponse httpResponse = WebUtils.toHttp(response); - httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } else if ((existing != null) && (existing.getClass().isAssignableFrom(APIException.class))) { - APIException apiException = (APIException) existing; - - HttpServletResponse httpResponse = WebUtils.toHttp(response); - httpResponse.setStatus(apiException.getHttpResponse().getStatus()); - httpResponse.addHeader(APIException.HTTP_HEADER_X_ERROR, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ERROR)); - httpResponse.addHeader(APIException.HTTP_HEADER_X_ERROR_CODE, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ERROR_CODE)); - - if (apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ROOT_CAUSE) != null) { - httpResponse.addHeader(APIException.HTTP_HEADER_X_ROOT_CAUSE, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ROOT_CAUSE)); - } - } else { - super.cleanup(request, response, existing); - } - } - - // TODO - can this be injected? - private ApiKeyService lookupApiKeyServiceBean() { - try { - Context c = new InitialContext(); - return (ApiKeyService) c.lookup("java:module/ApiKeyService"); // NOI18N - } catch (NamingException ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(ex.toString(), ex); - } else { - LOGGER.error(ex.toString()); - } - throw new RuntimeException(ex); - } - } - -} +/* + * Copyright 2018 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.shiro.filter; + +import de.muehlencord.shared.account.business.account.boundary.ApiKeyService; +import de.muehlencord.shared.account.business.account.entity.JWTObject; +import de.muehlencord.shared.account.shiro.token.JWTAuthenticationToken; +import de.muehlencord.shared.account.util.AccountSecurityException; +import de.muehlencord.shared.jeeutil.restexfw.APIException; +import java.io.IOException; +import java.io.StringReader; +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.IOUtils; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.web.filter.authc.AuthenticatingFilter; +import org.apache.shiro.web.util.WebUtils; +import org.slf4j.LoggerFactory; + +/** + * + * @author Joern Muehlencord + */ +public final class JWTAuthenticationFilter extends AuthenticatingFilter { + + private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(JWTAuthenticationFilter.class); + protected static final String AUTHORIZATION_HEADER = "Authorization"; // NOI18N + protected static final String USERNAME = "username"; // NOI18N + protected static final String PASSWORD = "password"; // NOI18N + + private final ApiKeyService apiKeyService = lookupApiKeyServiceBean(); + + public JWTAuthenticationFilter() { + // FIXME - logging in via JWTAuthenticationFilter does not yet work. Need to set login to anonymous to execute login in rest service + setLoginUrl("/rest/account/login"); + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + boolean loggedIn = false; + + if (isLoginRequest(request, response) || isLoggedAttempt(request, response)) { + loggedIn = executeLogin(request, response); + } + + if (!loggedIn) { + HttpServletResponse httpResponse = WebUtils.toHttp(response); + httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + return loggedIn; + } + + @Override + protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { + if (isLoginRequest(request, response)) { + String json = IOUtils.toString(request.getInputStream(), "UTF-8"); // FIXME - check charset in request + + if (json != null && !json.isEmpty()) { + try (JsonReader jr = Json.createReader(new StringReader(json))) { + JsonObject object = jr.readObject(); + String username = object.getString(USERNAME); + String password = object.getString(PASSWORD); + return new UsernamePasswordToken(username, password); + } + + } + } + + if (isLoggedAttempt(request, response)) { + String jwtToken = getAuthzHeader(request); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("found jwtToke in header = {}", jwtToken); + } + + if (jwtToken != null) { + JWTObject jwtObject = apiKeyService.getJWTObject(jwtToken); + return new JWTAuthenticationToken(jwtObject.getUserName(), jwtToken); + } + } + + return new UsernamePasswordToken(); + } + + private boolean isLoggedAttempt(ServletRequest request, ServletResponse response) { + String authzHeader = getAuthzHeader(request); + return authzHeader != null; + } + + private String getAuthzHeader(ServletRequest request) { + HttpServletRequest httpRequest = WebUtils.toHttp(request); + return httpRequest.getHeader(AUTHORIZATION_HEADER); + } + + + /** + * Overwrite cleanup to ensure no exception is thrown if an + * AccountSecurityException / APIException is raised during login. As long + * as the user is not logged in JERSEYs ExceptionMapper and intercepor + * classes are overruled by Shiro. + * + * @param request the incoming request + * @param response the response to return + * @param existing the raised exception + * @throws ServletException may be thrown by AuthenticatingFilter.cleanup if + * existing is not a AccountSecurityException + * @throws IOException may be thrown by AuthenticatingFilter.cleanup if + * existing is not a AccountSecurityException + */ + @Override + protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) throws ServletException, IOException { + if ((existing != null) && (existing.getClass().isAssignableFrom(AccountSecurityException.class))) { + HttpServletResponse httpResponse = WebUtils.toHttp(response); + httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } else if ((existing != null) && (existing.getClass().isAssignableFrom(APIException.class))) { + APIException apiException = (APIException) existing; + + HttpServletResponse httpResponse = WebUtils.toHttp(response); + httpResponse.setStatus(apiException.getHttpResponse().getStatus()); + httpResponse.addHeader(APIException.HTTP_HEADER_X_ERROR, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ERROR)); + httpResponse.addHeader(APIException.HTTP_HEADER_X_ERROR_CODE, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ERROR_CODE)); + + if (apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ROOT_CAUSE) != null) { + httpResponse.addHeader(APIException.HTTP_HEADER_X_ROOT_CAUSE, apiException.getHttpResponse().getHeaderString(APIException.HTTP_HEADER_X_ROOT_CAUSE)); + } + } else { + super.cleanup(request, response, existing); + } + } + + // TODO - can this be injected? + private ApiKeyService lookupApiKeyServiceBean() { + try { + Context c = new InitialContext(); + return (ApiKeyService) c.lookup("java:module/ApiKeyService"); // NOI18N + } catch (NamingException ex) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(ex.toString(), ex); + } else { + LOGGER.error(ex.toString()); + } + throw new RuntimeException(ex); + } + } + +} diff --git a/account/src/test/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyServiceTest.java b/account/src/test/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyServiceTest.java index 3c56ad4..da40019 100644 --- a/account/src/test/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyServiceTest.java +++ b/account/src/test/java/de/muehlencord/shared/account/business/account/boundary/ApiKeyServiceTest.java @@ -1,21 +1,98 @@ package de.muehlencord.shared.account.business.account.boundary; -import org.junit.Test; +import de.muehlencord.shared.account.business.account.control.AccountControl; +import de.muehlencord.shared.account.business.account.entity.AccountEntity; +import de.muehlencord.shared.account.business.application.entity.ApplicationRoleEntity; +import de.muehlencord.shared.account.business.config.boundary.ConfigService; +import de.muehlencord.shared.account.business.config.entity.ConfigException; +import de.muehlencord.shared.account.dao.ApiKeyObject; +import de.muehlencord.shared.db.ControllerException; +import java.util.ArrayList; +import javax.persistence.EntityManager; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; /** * * @author Joern Muehlencord */ +@ExtendWith(MockitoExtension.class) public class ApiKeyServiceTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ApiKeyServiceTest.class); + ApiKeyService apiKeyService; + + @BeforeEach + public void setup() { + apiKeyService = new ApiKeyService(); + apiKeyService.configService = mock(ConfigService.class); + try { + when(apiKeyService.configService.getConfigValue(anyString(), anyString(), anyBoolean())).thenReturn("120"); + when(apiKeyService.configService.getConfigValue(anyString())).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + String configKey = args[0].toString(); + switch (configKey) { + case "rest.password": + return "secret"; + case "rest.issuer": + return "ApiKeyServiceTest"; + default: + return "unknown"; + } + } + }); + } catch (ConfigException | ControllerException ex) { + LOGGER.error(ex.getMessage()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Detailed stacktrace", new Object[]{ex}); + } + fail("An exception occured"); + } + apiKeyService.accountControl = mock(AccountControl.class); + when(apiKeyService.accountControl.getAccountEntity(anyString(), anyBoolean())).thenAnswer(new Answer() { + @Override + public AccountEntity answer(InvocationOnMock iom) throws Throwable { + Object[] args = iom.getArguments(); + String userName = args[0].toString(); + boolean loadRoles = (boolean) args[1]; + AccountEntity account = new AccountEntity(); + account.setUsername(userName); + account.setFirstname("FirstName"); + account.setLastname("LastName"); + if (loadRoles) { + account.setApplicationRoleList(new ArrayList<>()); + ApplicationRoleEntity exampleRoleEntity = new ApplicationRoleEntity(); + exampleRoleEntity.setRoleName("Example Role"); + account.getApplicationRoleList().add(exampleRoleEntity); + } + return account; + } + + }); + apiKeyService.em = mock (EntityManager.class); + apiKeyService.init(); + } + @Test public void testCreateApiKey() { try { - ApiKeyService apiKeyService = new ApiKeyService(); - apiKeyService.createNewApiKey("web", (short) 120); + ApiKeyObject apiKeyObject = apiKeyService.createNewApiKey("web", (short) 120); + assertNotNull(apiKeyObject); + LOGGER.info("authToken: "+apiKeyObject.getAuthToken()); } catch (ApiKeyException ex) { LOGGER.error(ex.getMessage()); if (LOGGER.isDebugEnabled()) { diff --git a/account/src/test/java/de/muehlencord/shared/account/business/config/boundary/ConfigServiceTest.java b/account/src/test/java/de/muehlencord/shared/account/business/config/boundary/ConfigServiceTest.java index c8846ef..7e4d7f1 100644 --- a/account/src/test/java/de/muehlencord/shared/account/business/config/boundary/ConfigServiceTest.java +++ b/account/src/test/java/de/muehlencord/shared/account/business/config/boundary/ConfigServiceTest.java @@ -1,76 +1,76 @@ -/* - * Copyright 2018 joern.muehlencord. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.business.config.boundary; - -import de.muehlencord.shared.account.business.account.entity.AccountEntity; -import de.muehlencord.shared.account.business.account.entity.AccountLoginEntity; -import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; -import de.muehlencord.shared.account.business.config.entity.ConfigEntity; -import de.muehlencord.shared.account.business.config.entity.ConfigEntityPK; -import java.util.UUID; -import javax.persistence.EntityManager; -import org.junit.Test; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import static org.mockito.Mockito.when; -import org.mockito.runners.MockitoJUnitRunner; - -/** - * - * @author joern.muehlencord - */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigServiceTest { - - @InjectMocks - private ConfigService configService; - - @Mock - private EntityManager entityManagerMock; - - @Before - public void init() { - ApplicationEntity application = new ApplicationEntity(); - application.setId(UUID.randomUUID()); - application.setApplicationName("Test App"); - - AccountEntity account = new AccountEntity(); - account.setUsername("system"); - AccountLoginEntity login = new AccountLoginEntity(); - login.setAccount (account); - account.setAccountLogin(login); - - ConfigEntityPK pk = new ConfigEntityPK(application, "account.maxFailedLogins", account); - ConfigEntity configEntity = new ConfigEntity (pk); - configEntity.setConfigValue("7"); - when (entityManagerMock.find(ConfigEntity.class, "account.maxFailedLogins")).thenReturn (configEntity); - } - - @Test - @Ignore - // TODO move to account test - public void testGetMaxFailedLogins() { -// configService.init(); -// assertEquals ("maxFailedLogins", 7, configService.getMaxFailedLogins()); - } - - - - -} +/* + * Copyright 2018 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.business.config.boundary; + +import de.muehlencord.shared.account.business.account.entity.AccountEntity; +import de.muehlencord.shared.account.business.account.entity.AccountLoginEntity; +import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; +import de.muehlencord.shared.account.business.config.entity.ConfigEntity; +import de.muehlencord.shared.account.business.config.entity.ConfigEntityPK; +import java.util.UUID; +import javax.persistence.EntityManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import static org.mockito.Mockito.when; +import org.mockito.junit.jupiter.MockitoExtension; + +/** + * + * @author joern.muehlencord + */ +@ExtendWith(MockitoExtension.class) +public class ConfigServiceTest { + + @InjectMocks + private ConfigService configService; + + @Mock + private EntityManager entityManagerMock; + + @BeforeEach + public void init() { + ApplicationEntity application = new ApplicationEntity(); + application.setId(UUID.randomUUID()); + application.setApplicationName("Test App"); + + AccountEntity account = new AccountEntity(); + account.setUsername("system"); + AccountLoginEntity login = new AccountLoginEntity(); + login.setAccount (account); + account.setAccountLogin(login); + + ConfigEntityPK pk = new ConfigEntityPK(application, "account.maxFailedLogins", account); + ConfigEntity configEntity = new ConfigEntity (pk); + configEntity.setConfigValue("7"); + when (entityManagerMock.find(ConfigEntity.class, "account.maxFailedLogins")).thenReturn (configEntity); + } + + @Test + @Disabled + // TODO move to account test + public void testGetMaxFailedLogins() { +// configService.init(); +// assertEquals ("maxFailedLogins", 7, configService.getMaxFailedLogins()); + } + + + + +} diff --git a/account/src/test/java/de/muehlencord/shared/account/shiro/realm/UserNameActiveDirectoryRealmTest.java b/account/src/test/java/de/muehlencord/shared/account/shiro/realm/UserNameActiveDirectoryRealmTest.java index dabce68..4382f9a 100644 --- a/account/src/test/java/de/muehlencord/shared/account/shiro/realm/UserNameActiveDirectoryRealmTest.java +++ b/account/src/test/java/de/muehlencord/shared/account/shiro/realm/UserNameActiveDirectoryRealmTest.java @@ -1,68 +1,75 @@ -/* - * Copyright 2018 joern.muehlencord. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.shiro.realm; - -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.config.IniSecurityManagerFactory; -import org.apache.shiro.subject.Subject; -import org.junit.Test; -import org.apache.shiro.mgt.SecurityManager; -import static org.junit.Assume.assumeNotNull; - -/** - * - * @author Joern Muehlencord - */ -public class UserNameActiveDirectoryRealmTest { - - @Test - public void testUsernameLogin() { - String userName = "user.name"; - String password = "secret"; - testLogin(userName, password); - } - - @Test - public void testEmailaddressLogin() { - String userName = "user.name@domain.com"; - String password = "secret"; - testLogin(userName, password); - } - - @Test(expected=AuthenticationException.class) - public void testWrongUserNamePassword() { - String userName = "test123"; - String password = "secret"; - testLogin(userName, password); - } - - private void testLogin(String userName, String password) throws AuthenticationException { - assumeNotNull(UserNameActiveDirectoryRealmTest.class.getResource("/shiro.ini")); - - IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini"); - SecurityManager securityManager = factory.getInstance(); - SecurityUtils.setSecurityManager(securityManager); - - UsernamePasswordToken token = new UsernamePasswordToken(userName, password); - Subject currentUser = SecurityUtils.getSubject(); - - currentUser.login(token); - System.out.println("Logged in"); - } - -} +/* + * Copyright 2018 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.shiro.realm; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.subject.Subject; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * + * @author Joern Muehlencord + */ +public class UserNameActiveDirectoryRealmTest { + + @Test + public void testUsernameLogin() { + String userName = "root"; + String password = "secret"; + testLogin(userName, password); + } + + @Test + @Disabled + public void testEmailaddressLogin() { + String userName = "user.name@domain.com"; + String password = "secret"; + Assertions.assertThrows(AuthenticationException.class, () -> { + testLogin(userName, password); + }); + } + + @Test + public void testWrongUserNamePassword() { + String userName = "test123"; + String password = "secret"; + Assertions.assertThrows(AuthenticationException.class, () -> { + testLogin(userName, password); + }); + } + + private void testLogin(String userName, String password) throws AuthenticationException { + assumeFalse(UserNameActiveDirectoryRealmTest.class.getResource("/shiro.ini") == null); + + IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini"); + SecurityManager securityManager = factory.getInstance(); + SecurityUtils.setSecurityManager(securityManager); + + UsernamePasswordToken token = new UsernamePasswordToken(userName, password); + Subject currentUser = SecurityUtils.getSubject(); + + currentUser.login(token); + System.out.println("Logged in"); + } + +} diff --git a/account/src/test/java/de/muehlencord/shared/account/util/SecurityUtilTest.java b/account/src/test/java/de/muehlencord/shared/account/util/SecurityUtilTest.java index 546de73..1c56601 100644 --- a/account/src/test/java/de/muehlencord/shared/account/util/SecurityUtilTest.java +++ b/account/src/test/java/de/muehlencord/shared/account/util/SecurityUtilTest.java @@ -1,32 +1,32 @@ -/* - * Copyright 2018 joern.muehlencord. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.muehlencord.shared.account.util; - -import org.junit.Test; - -/** - * - * @author Joern Muehlencord - */ -public class SecurityUtilTest { - - - @Test - public void testCreatePassword() { - System.out.println (SecurityUtil.createPassword("secret")); - } - -} +/* + * Copyright 2018 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.account.util; + +import org.junit.jupiter.api.Test; + +/** + * + * @author Joern Muehlencord + */ +public class SecurityUtilTest { + + + @Test + public void testCreatePassword() { + System.out.println (SecurityUtil.createPassword("secret")); + } + +} diff --git a/account/src/test/resources/shiro.ini b/account/src/test/resources/shiro.ini new file mode 100644 index 0000000..436c465 --- /dev/null +++ b/account/src/test/resources/shiro.ini @@ -0,0 +1,25 @@ +# ============================================================================= +# Tutorial INI configuration +# +# Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Users and their (optional) assigned roles +# username = password, role1, role2, ..., roleN +# ----------------------------------------------------------------------------- +[users] +root = secret, admin +guest = guest, guest +presidentskroob = 12345, president +darkhelmet = ludicrousspeed, darklord, schwartz +lonestarr = vespa, goodguy, schwartz + +# ----------------------------------------------------------------------------- +# Roles with assigned permissions +# roleName = perm1, perm2, ..., permN +# ----------------------------------------------------------------------------- +[roles] +admin = * +schwartz = lightsaber:* +goodguy = winnebago:drive:eagle5 \ No newline at end of file diff --git a/configuration/pom.xml b/configuration/pom.xml index 409f053..89da5a1 100644 --- a/configuration/pom.xml +++ b/configuration/pom.xml @@ -19,10 +19,10 @@ - junit - junit + org.junit.jupiter + junit-jupiter-engine test - + org.slf4j diff --git a/network/pom.xml b/network/pom.xml index 7bd425c..11aedd2 100644 --- a/network/pom.xml +++ b/network/pom.xml @@ -25,11 +25,10 @@ - junit - junit - jar + org.junit.jupiter + junit-jupiter-engine test - + com.enterprisedt edtFTPj diff --git a/network/src/test/java/de/muehlencord/shared/network/CidrToolTest.java b/network/src/test/java/de/muehlencord/shared/network/CidrToolTest.java index 4789ae3..42baaff 100644 --- a/network/src/test/java/de/muehlencord/shared/network/CidrToolTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/CidrToolTest.java @@ -5,8 +5,8 @@ package de.muehlencord.shared.network; import static de.muehlencord.shared.network.CidrTool.rangeToCidrList; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -18,7 +18,7 @@ public class CidrToolTest { } @Test - @Ignore + @Disabled public void testCidrConversion() { System.out.println (rangeToCidrList("213.55.64.0", "213.55.127.255")); } diff --git a/network/src/test/java/de/muehlencord/shared/network/NetworkScannerTest.java b/network/src/test/java/de/muehlencord/shared/network/NetworkScannerTest.java index 58657da..c476ab3 100644 --- a/network/src/test/java/de/muehlencord/shared/network/NetworkScannerTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/NetworkScannerTest.java @@ -3,9 +3,9 @@ package de.muehlencord.shared.network; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.net.util.SubnetUtils; -import static org.junit.Assert.assertFalse; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -17,7 +17,7 @@ public class NetworkScannerTest { } @Test - @Ignore // takes very long + @Disabled // takes very long public void testScan() throws UnknownHostException { String ipAddress = InetAddress.getLocalHost().getHostAddress(); SubnetUtils utils = new SubnetUtils(ipAddress, "255.255.255.0"); diff --git a/network/src/test/java/de/muehlencord/shared/network/PortScannerTest.java b/network/src/test/java/de/muehlencord/shared/network/PortScannerTest.java index 5858f2b..eff3d86 100644 --- a/network/src/test/java/de/muehlencord/shared/network/PortScannerTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/PortScannerTest.java @@ -1,8 +1,8 @@ package de.muehlencord.shared.network; import java.util.List; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -14,7 +14,7 @@ public class PortScannerTest { } @Test - @Ignore // takes very long + @Disabled // takes very long public void testMain() { PortScanner portScanner = new PortScanner(); List resultList = portScanner.scan("127.0.0.1"); diff --git a/network/src/test/java/de/muehlencord/shared/network/RangeToCidrTest.java b/network/src/test/java/de/muehlencord/shared/network/RangeToCidrTest.java index 169946c..1c6f4a9 100644 --- a/network/src/test/java/de/muehlencord/shared/network/RangeToCidrTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/RangeToCidrTest.java @@ -1,7 +1,7 @@ package de.muehlencord.shared.network; import static de.muehlencord.shared.network.CidrTool.rangeToCidrList; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/network/src/test/java/de/muehlencord/shared/network/ftp/FTPConnectionTest.java b/network/src/test/java/de/muehlencord/shared/network/ftp/FTPConnectionTest.java index 005fbfd..105d439 100644 --- a/network/src/test/java/de/muehlencord/shared/network/ftp/FTPConnectionTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/ftp/FTPConnectionTest.java @@ -7,10 +7,11 @@ import java.net.URL; import java.util.List; import java.util.Locale; import java.util.Properties; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,8 +28,8 @@ public class FTPConnectionTest { /** true, if init is complete to execute test */ boolean initDone = false; - @Before - public void initClass() { + @BeforeEach + public void setup() { System.out.println("\n[FTPConnectionTest]"); URL testConfigURL = FTPConnectionTest.class.getResource("/test.properties"); FileInputStream fin = null; @@ -80,7 +81,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testList() throws FTPConnectionException { System.out.println("list"); String dir = ""; @@ -92,7 +93,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testListDirsOnly() throws FTPConnectionException { System.out.println("listDirsOnly"); String dir = ""; @@ -104,7 +105,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testListFilesOnly() throws FTPConnectionException { System.out.println("listFilesOnly"); String dir = ""; @@ -116,7 +117,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testListLinksOnly() throws FTPConnectionException { System.out.println("listLinksOnly"); String dir = ""; @@ -128,7 +129,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testUploadFile() throws FTPConnectionException { System.out.println("uploadFile"); String localFilename = ""; @@ -138,7 +139,7 @@ public class FTPConnectionTest { } @Test - @Ignore + @Disabled public void testRename() throws FTPConnectionException { System.out.println("rename"); String remoteOldName = ""; diff --git a/network/src/test/java/de/muehlencord/shared/network/http/HttpLayerTest.java b/network/src/test/java/de/muehlencord/shared/network/http/HttpLayerTest.java index 5755f31..b869893 100644 --- a/network/src/test/java/de/muehlencord/shared/network/http/HttpLayerTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/http/HttpLayerTest.java @@ -9,8 +9,9 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -19,7 +20,7 @@ import org.junit.Test; public class HttpLayerTest extends BaseTest { @Test - @Ignore + @Disabled public void testPostByMap() throws Exception { System.out.println("testPostByMap"); Map map = new HashMap<>(); @@ -32,7 +33,7 @@ public class HttpLayerTest extends BaseTest { } @Test - @Ignore + @Disabled public void testPostByMapList() throws Exception { System.out.println("testPostByMapList"); List> list = new LinkedList<>(); @@ -45,41 +46,43 @@ public class HttpLayerTest extends BaseTest { map.put("url", urlValue); list.add(map); - - HttpLayer httpLayer = new HttpLayer("http://localhost:8080/HttpPostListener/HttpPostListener"); httpLayer.post(list); } @Test - @Ignore + @Disabled public void testByValue() throws Exception { System.out.println("testByValue"); - HttpLayer httpLayer = new HttpLayer( - "http://localhost:8080/HttpPostListener/HttpPostListener"); + HttpLayer httpLayer = new HttpLayer("http://localhost:8080/HttpPostListener/HttpPostListener"); httpLayer.post("message", "Hello World by single parameter"); } - @Test(expected = MessageNotSendException.class) + @Test public void testWithUnknownURL() throws MessageNotSendException { System.out.println("testWithUnknownURL"); - HttpLayer httpLayer = new HttpLayer( - "http://localhost/thisURLDoesNotExist"); - httpLayer.post("message", "Hello World by single parameter"); + HttpLayer httpLayer = new HttpLayer("http://localhost/thisURLDoesNotExist"); + Assertions.assertThrows(MessageNotSendException.class, () -> { + httpLayer.post("message", "Hello World by single parameter"); + }); } - @Test(expected = MessageNotSendException.class) + @Test public void testInvalidURL() throws MessageNotSendException { System.out.println("testInvalidURL"); HttpLayer httpLayer = new HttpLayer("joern@muehlencord.de"); - httpLayer.post("message", "Hello World by single parameter"); + Assertions.assertThrows(MessageNotSendException.class, () -> { + httpLayer.post("message", "Hello World by single parameter"); + }); } - @Test(expected = MessageNotSendException.class) + @Test public void testUnsupportedURL() throws MessageNotSendException { System.out.println("testUnsupportedURL"); HttpLayer httpLayer = new HttpLayer("ftp://localhost"); - httpLayer.post("message", "Hello World by single parameter"); + Assertions.assertThrows(MessageNotSendException.class, () -> { + httpLayer.post("message", "Hello World by single parameter"); + }); } } diff --git a/network/src/test/java/de/muehlencord/shared/network/mail/MailMessageUtilsTest.java b/network/src/test/java/de/muehlencord/shared/network/mail/MailMessageUtilsTest.java index 1a5caed..c894f7c 100644 --- a/network/src/test/java/de/muehlencord/shared/network/mail/MailMessageUtilsTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/mail/MailMessageUtilsTest.java @@ -6,11 +6,11 @@ import de.muehlencord.shared.network.mail.imap.ImapMailReader; import java.io.File; import java.net.URL; import java.util.List; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -18,13 +18,13 @@ import org.junit.Test; */ public class MailMessageUtilsTest extends BaseTest { - @Before + @BeforeEach public void setup() { System.out.println ("\n[MailMessageUtilsTest]"); } @Test - @Ignore // depends on environment + @Disabled // depends on environment public void testGetInstance() throws Exception { System.out.println("testGetInstance"); URL testConfigURL = MailMessageUtilsTest.class.getResource("/test.properties"); diff --git a/network/src/test/java/de/muehlencord/shared/network/mail/TestSendMail.java b/network/src/test/java/de/muehlencord/shared/network/mail/TestSendMail.java index 9183f25..c6ecca2 100644 --- a/network/src/test/java/de/muehlencord/shared/network/mail/TestSendMail.java +++ b/network/src/test/java/de/muehlencord/shared/network/mail/TestSendMail.java @@ -1,8 +1,3 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ package de.muehlencord.shared.network.mail; import java.io.File; @@ -23,8 +18,8 @@ import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; -import org.junit.Assume; -import org.junit.Test; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,8 +37,8 @@ public class TestSendMail { @Test public void testSendEmail() throws AddressException, MessagingException, IOException { - Assume.assumeFalse(RECEIVER == null); - Assume.assumeFalse(PASSWORD == null); + assumeFalse(RECEIVER == null); + assumeFalse(PASSWORD == null); Properties props = new Properties(); props.put("mail.smtp.host", "jomu.timelord.de"); diff --git a/network/src/test/java/de/muehlencord/shared/network/mail/exchange/ExchangeMailReaderTest.java b/network/src/test/java/de/muehlencord/shared/network/mail/exchange/ExchangeMailReaderTest.java index 85510dd..de7de55 100644 --- a/network/src/test/java/de/muehlencord/shared/network/mail/exchange/ExchangeMailReaderTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/mail/exchange/ExchangeMailReaderTest.java @@ -6,9 +6,9 @@ import de.muehlencord.shared.network.mail.MailReaderConfiguration; import de.muehlencord.shared.network.mail.MailReaderConnectionException; import de.muehlencord.shared.network.mail.MailReaderException; import java.util.List; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNotNull; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,12 +33,12 @@ public class ExchangeMailReaderTest { String emailaddress = null; // disable tests if not all values are set - assumeNotNull(smtpHost); - assumeNotNull(folder); - assumeNotNull(testFolder); - assumeNotNull(userName); - assumeNotNull(emailaddress); - assumeNotNull(password); + assumeFalse(smtpHost == null); + assumeFalse(folder == null); + assumeFalse(testFolder == null); + assumeFalse(userName == null); + assumeFalse(emailaddress == null); + assumeFalse(password == null); MailReaderConfiguration config = new MailReaderConfiguration(smtpHost, imapHost, userName, password, emailaddress); MailReader instance = new ExchangeMailReader(config); diff --git a/network/src/test/java/de/muehlencord/shared/network/mail/imap/ImapMailReaderTest.java b/network/src/test/java/de/muehlencord/shared/network/mail/imap/ImapMailReaderTest.java index 3ef1fa0..de365a3 100644 --- a/network/src/test/java/de/muehlencord/shared/network/mail/imap/ImapMailReaderTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/mail/imap/ImapMailReaderTest.java @@ -1,7 +1,3 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ package de.muehlencord.shared.network.mail.imap; import de.muehlencord.shared.network.BaseTest; @@ -10,10 +6,10 @@ import de.muehlencord.shared.network.mail.MailReaderConfiguration; import de.muehlencord.shared.network.mail.MailReaderConnectionException; import de.muehlencord.shared.network.mail.MailReaderException; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -28,7 +24,7 @@ public class ImapMailReaderTest extends BaseTest { * @throws Exception if the tests fails */ @Test - @Ignore // depends on environment + @Disabled // depends on environment public void testConnect() throws Exception { System.out.println("connect"); String meta = "meta.muehlencord.intra"; @@ -40,7 +36,7 @@ public class ImapMailReaderTest extends BaseTest { } @Test - @Ignore // depends on environment + @Disabled // depends on environment public void testGetFolder() throws Exception { System.out.println("getFolder"); String meta = "meta.muehlencord.intra"; @@ -54,7 +50,7 @@ public class ImapMailReaderTest extends BaseTest { } @Test - @Ignore // depends on environment + @Disabled // depends on environment public void testGetMessageCount() throws MailReaderConnectionException, MailReaderException { System.out.println("testGetMessageCount"); String meta = "meta.muehlencord.intra"; @@ -67,7 +63,7 @@ public class ImapMailReaderTest extends BaseTest { } @Test - @Ignore // depends on environment + @Disabled // depends on environment public void testGetSubFolder() throws MailReaderConnectionException, MailReaderException { System.out.println("getSubFolder"); String meta = "meta.muehlencord.intra"; diff --git a/network/src/test/java/de/muehlencord/shared/network/whois/ArinWhoisParserTest.java b/network/src/test/java/de/muehlencord/shared/network/whois/ArinWhoisParserTest.java index 1c9d5cb..4a096d5 100644 --- a/network/src/test/java/de/muehlencord/shared/network/whois/ArinWhoisParserTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/whois/ArinWhoisParserTest.java @@ -2,9 +2,9 @@ package de.muehlencord.shared.network.whois; import de.muehlencord.shared.network.BaseTest; import java.io.IOException; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -14,7 +14,7 @@ public class ArinWhoisParserTest extends BaseTest { @Test - @Ignore + @Disabled public void testParseArinIp() throws IOException, WhoisException { String whoisInformation = this.readContentFromFile("204.232.209.184.txt"); ArinWhoisParser parser = new ArinWhoisParser(); @@ -28,7 +28,7 @@ public class ArinWhoisParserTest extends BaseTest { } @Test - @Ignore + @Disabled public void testParseArinDoubleIp() throws IOException, WhoisException { String whoisInformation = this.readContentFromFile("108.166.92.167.txt"); ArinWhoisParser parser = new ArinWhoisParser(); @@ -42,7 +42,7 @@ public class ArinWhoisParserTest extends BaseTest { } @Test - @Ignore // FIXME test broken + @Disabled // FIXME test broken public void testParseArinUnknown() throws IOException, WhoisException { String whoisInformation = this.readContentFromFile("74.95.241.217.txt"); ArinWhoisParser parser = new ArinWhoisParser(); diff --git a/network/src/test/java/de/muehlencord/shared/network/whois/WhoisTest.java b/network/src/test/java/de/muehlencord/shared/network/whois/WhoisTest.java index d035b7f..6f1aaac 100644 --- a/network/src/test/java/de/muehlencord/shared/network/whois/WhoisTest.java +++ b/network/src/test/java/de/muehlencord/shared/network/whois/WhoisTest.java @@ -1,69 +1,68 @@ package de.muehlencord.shared.network.whois; import de.muehlencord.shared.network.BaseTest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * * @author jomu */ public class WhoisTest extends BaseTest { - @Test - @Ignore + @Disabled public void testDenicWhoIs() throws WhoisException { - Whois whoIsClient = new Whois(); + Whois whoIsClient = new Whois(); // Denic answers "status: connect" only - whoIsClient.execute ("whois.denic.de", "-T dn,ace muehlencord.de"); + whoIsClient.execute("whois.denic.de", "-T dn,ace muehlencord.de"); } - - @Test - @Ignore - public void testInternic() throws WhoisException { - Whois whoIsClient = new Whois(); - whoIsClient.execute ("whois.1api.net", "egameladder.com"); - } - + @Test - @Ignore + @Disabled + public void testInternic() throws WhoisException { + Whois whoIsClient = new Whois(); + whoIsClient.execute("whois.1api.net", "egameladder.com"); + } + + @Test + @Disabled // TODO 184.173.67.10 whois with referal public void testArin() throws WhoisException { - Whois whoIsClient = new Whois(); + Whois whoIsClient = new Whois(); // WhoisInformation whoisInformation = whoIsClient.execute ("whois.arin.net", "204.232.209.184"); - WhoisInformation whoisInformation = whoIsClient.execute ("whois.arin.net", "74.95.241.217"); - assertNotNull (whoisInformation); + WhoisInformation whoisInformation = whoIsClient.execute("whois.arin.net", "74.95.241.217"); + assertNotNull(whoisInformation); whoisInformation.validate(); - assertEquals ("Country", "US", whoisInformation.getNetworkInformation().getCountry()); - System.out.println ("Network: "+whoisInformation.getNetwork()); - assertTrue ("Network", whoisInformation.getNetwork().contains("74.95.224.0/19")); + assertEquals("Country", "US", whoisInformation.getNetworkInformation().getCountry()); + System.out.println("Network: " + whoisInformation.getNetwork()); + assertTrue(whoisInformation.getNetwork().contains("74.95.224.0/19"), "Network"); } - + @Test - @Ignore + @Disabled public void testApnic() throws WhoisException { - Whois whoIsClient = new Whois(); - whoIsClient.execute ("whois.apnic.net", "60.247.69.45"); + Whois whoIsClient = new Whois(); + whoIsClient.execute("whois.apnic.net", "60.247.69.45"); } - + @Test - @Ignore + @Disabled public void testLacnic() throws WhoisException { - Whois whoIsClient = new Whois(); - WhoisInformation whoisInformation = whoIsClient.execute ("whois.lacnic.net", "200.29.132.82"); - assertNotNull (whoisInformation); - assertEquals ("Country", "CL", whoisInformation.getNetworkInformation().getCountry()); - assertTrue ("Network", whoisInformation.getNetwork().contains("200.29.132.80/29")); + Whois whoIsClient = new Whois(); + WhoisInformation whoisInformation = whoIsClient.execute("whois.lacnic.net", "200.29.132.82"); + assertNotNull(whoisInformation); + assertEquals("Country", "CL", whoisInformation.getNetworkInformation().getCountry()); + assertTrue(whoisInformation.getNetwork().contains("200.29.132.80/29"), "Network"); } - - @Test - @Ignore - public void testUnkown() throws WhoisException { + + @Test + @Disabled + public void testUnkown() throws WhoisException { Whois whoIsClient = new Whois(); // whoIsClient.execute("whois.arin.net", "174.139.180.10"); // whoIsClient.execute("whois.twnic.net", "60.250.38.39"); @@ -72,32 +71,31 @@ public class WhoisTest extends BaseTest { // whoIsClient.execute("whois.apnic.net", "182.72.111.26"); // whoIsClient.execute("whois.ripe.net", "213.55.95.62"); // Transferred to Afrinic // whoIsClient.execute("whois.afrinic.net", "213.55.95.62"); - whoIsClient.execute("whois.arin.net", "32.64.68.229"); + whoIsClient.execute("whois.arin.net", "32.64.68.229"); } - + @Test - @Ignore + @Disabled public void testGeneric() throws WhoisException { Whois whoIsClient = new Whois(); - WhoisInformation info = whoIsClient.execute( "85.185.91.5"); - assertNotNull (info); - assertNotNull (info.getNetwork()); - assertFalse (info.getNetwork().isEmpty()); - System.out.println (info.getNetwork().toString()); - System.out.println (info.getRootNetwork().toString()); - System.out.println (info.getNetworkInformation().getDescription()); - + WhoisInformation info = whoIsClient.execute("85.185.91.5"); + assertNotNull(info); + assertNotNull(info.getNetwork()); + assertFalse(info.getNetwork().isEmpty()); + System.out.println(info.getNetwork().toString()); + System.out.println(info.getRootNetwork().toString()); + System.out.println(info.getNetworkInformation().getDescription()); + } - - + @Test - @Ignore + @Disabled public void testStepWise() throws WhoisException { - Whois whoIsClient = new Whois(); + Whois whoIsClient = new Whois(); // whoIsClient.execute ("whois.ripe.net", "88.198.181.181"); - WhoisInformation whoisInformation = whoIsClient.execute ("212.204.60.1"); - assertTrue ("network", whoisInformation.getNetwork().contains("212.204.60.0/24")); + WhoisInformation whoisInformation = whoIsClient.execute("212.204.60.1"); + assertTrue(whoisInformation.getNetwork().contains("212.204.60.0/24"), "network"); // whoIsClient.execute ("whois.ripe.net", "212.204.60.0"); // whoIsClient.execute ("whois.ripe.net", "212.0.0.0/8"); } -} \ No newline at end of file +} diff --git a/pdf/pom.xml b/pdf/pom.xml index 91d9add..cfb6add 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -17,10 +17,10 @@ freemarker - junit - junit + org.junit.jupiter + junit-jupiter-engine test - + org.slf4j slf4j-api diff --git a/pdf/src/main/java/de/muehlencord/shared/pdf/InterfaceAdapter.java b/pdf/src/main/java/de/muehlencord/shared/pdf/InterfaceAdapter.java index 30678eb..14a45a1 100644 --- a/pdf/src/main/java/de/muehlencord/shared/pdf/InterfaceAdapter.java +++ b/pdf/src/main/java/de/muehlencord/shared/pdf/InterfaceAdapter.java @@ -2,12 +2,12 @@ package de.muehlencord.shared.pdf; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; -import java.lang.reflect.Type; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; /** * diff --git a/pdf/src/main/java/de/muehlencord/shared/pdf/PDFDocument.java b/pdf/src/main/java/de/muehlencord/shared/pdf/PDFDocument.java index bc2eaa4..545b99a 100644 --- a/pdf/src/main/java/de/muehlencord/shared/pdf/PDFDocument.java +++ b/pdf/src/main/java/de/muehlencord/shared/pdf/PDFDocument.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedDeque; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/DefaultTableRowTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/DefaultTableRowTest.java index 0151f43..6688de3 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/DefaultTableRowTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/DefaultTableRowTest.java @@ -1,35 +1,35 @@ package de.muehlencord.shared.pdf; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.Test; /** * * @author joern.muehlencord */ public class DefaultTableRowTest { - + @Test public void testFromJson() { - String jsonString = "{\n" + -" \"type\": \"de.muehlencord.shared.pdf.DefaultTableRow\",\n" + -" \"data\": {\n" + -" \"row\": [\n" + -" {\n" + -" \"text\": \"Rechnungs-Nr.:\"\n" + -" },\n" + -" {\n" + -" \"text\": \"${invoiceNumber}\"\n" + -" }\n" + -" ],\n" + -" \"isList\": false\n" + -" }\n" + -" }"; - - - TableRow tableRow = GsonUtil.getInstance().fromJson(jsonString, TableRow.class); - assertNotNull ("tableRowObject", tableRow); - assertEquals ("column count", 2, tableRow.getColumnCount()); - assertFalse ("isList", tableRow.isList()); + String jsonString = "{\n" + + " \"type\": \"de.muehlencord.shared.pdf.DefaultTableRow\",\n" + + " \"data\": {\n" + + " \"row\": [\n" + + " {\n" + + " \"text\": \"Rechnungs-Nr.:\"\n" + + " },\n" + + " {\n" + + " \"text\": \"${invoiceNumber}\"\n" + + " }\n" + + " ],\n" + + " \"isList\": false\n" + + " }\n" + + " }"; + + TableRow tableRow = GsonUtil.getInstance().fromJson(jsonString, TableRow.class); + assertFalse(tableRow == null, "tableRowObject"); + assertEquals(2, tableRow.getColumnCount(), "column count"); + assertFalse(tableRow.isList(), "isList"); } } diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFFontTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFFontTest.java index a54f401..e692808 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFFontTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFFontTest.java @@ -1,7 +1,7 @@ package de.muehlencord.shared.pdf; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFImageContentTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFImageContentTest.java index a8d1d64..7177fbe 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFImageContentTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFImageContentTest.java @@ -4,7 +4,7 @@ import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFTextContentTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFTextContentTest.java index 8f89617..3cb5feb 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/PDFTextContentTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/PDFTextContentTest.java @@ -2,7 +2,7 @@ package de.muehlencord.shared.pdf; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/TextTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/TextTest.java index c715a02..8663e5c 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/TextTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/TextTest.java @@ -1,7 +1,8 @@ package de.muehlencord.shared.pdf; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.Test; /** * @@ -17,10 +18,10 @@ public class TextTest { String jsonString = "{\n" + "\"text\": \"Rechnungs-Nr.:\"\n" + "}"; - + TextElement text = GsonUtil.getInstance().fromJson(jsonString, TextElement.class); - assertNotNull ("text object", text); - assertEquals ("text value", "Rechnungs-Nr.:", text.getText()); + assertFalse(text == null, "text object"); + assertEquals("Rechnungs-Nr.:", text.getText(), "text value"); } diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/test/GsonSerialisation.java b/pdf/src/test/java/de/muehlencord/shared/pdf/test/GsonSerialisation.java index 2282075..0610aa4 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/test/GsonSerialisation.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/test/GsonSerialisation.java @@ -14,7 +14,7 @@ import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.io.FileUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/test/PDFDocumentTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/test/PDFDocumentTest.java index 98f7434..807b910 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/test/PDFDocumentTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/test/PDFDocumentTest.java @@ -25,14 +25,15 @@ import java.net.URL; import java.util.Date; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * * @author jomu */ -@FixMethodOrder +@TestMethodOrder(OrderAnnotation.class) public class PDFDocumentTest { private String jsonString = null; diff --git a/pdf/src/test/java/de/muehlencord/shared/pdf/util/ImageUtilTest.java b/pdf/src/test/java/de/muehlencord/shared/pdf/util/ImageUtilTest.java index e2ea918..c6fe41e 100644 --- a/pdf/src/test/java/de/muehlencord/shared/pdf/util/ImageUtilTest.java +++ b/pdf/src/test/java/de/muehlencord/shared/pdf/util/ImageUtilTest.java @@ -1,11 +1,12 @@ + package de.muehlencord.shared.pdf.util; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -32,7 +33,7 @@ public class ImageUtilTest { } @Test - @Ignore + @Disabled public void testFromFile() throws IOException { System.out.println ("testFromFile"); BufferedImage img = ImageIO.read(new File ("c:/temp/dn_logo_smartteller_transparent.png")); diff --git a/pom.xml b/pom.xml index f60d9ea..31facc2 100644 --- a/pom.xml +++ b/pom.xml @@ -72,41 +72,11 @@ de.muehlencord.sf filter 1.1-SNAPSHOT - - - junit - junit - 4.12 - test - - - org.junit.jupiter - junit-jupiter-api - 5.3.1 - test - - - org.junit.jupiter - junit-jupiter-params - 5.3.1 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.3.1 - test - - - org.mockito - mockito-core - 2.23.0 - test - + commons-codec commons-codec - 1.11 + 1.12 commons-net @@ -116,7 +86,7 @@ org.apache.commons commons-lang3 - 3.8.1 + 3.9 commons-io @@ -157,24 +127,24 @@ com.fasterxml.jackson.core jackson-annotations - 2.9.8 + 2.9.9 jar com.fasterxml.jackson.core jackson-databind - 2.9.8 + 2.9.9.1 jar org.apache.shiro shiro-core - 1.4.0 + 1.4.1 org.apache.shiro shiro-web - 1.4.0 + 1.4.1 javax @@ -259,6 +229,38 @@ prime-jwt 1.3.1 + + + + org.junit.jupiter + junit-jupiter-api + 5.5.0 + test + + + org.junit.jupiter + junit-jupiter-params + 5.5.0 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.5.0 + test + + + org.mockito + mockito-core + 2.28.2 + test + + + org.mockito + mockito-junit-jupiter + 2.23.0 + test + @@ -295,7 +297,13 @@ maven-release-plugin 2.5.3 - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + @@ -309,7 +317,11 @@ v@{project.version} - + + + org.apache.maven.plugins + maven-surefire-plugin + diff --git a/security/pom.xml b/security/pom.xml index ae03967..acd596c 100644 --- a/security/pom.xml +++ b/security/pom.xml @@ -21,8 +21,9 @@ - junit - junit + org.junit.jupiter + junit-jupiter-engine + test commons-codec diff --git a/security/src/test/java/de/muehlencord/shared/security/LuhnTest.java b/security/src/test/java/de/muehlencord/shared/security/LuhnTest.java index 687405e..2096e6b 100644 --- a/security/src/test/java/de/muehlencord/shared/security/LuhnTest.java +++ b/security/src/test/java/de/muehlencord/shared/security/LuhnTest.java @@ -15,8 +15,9 @@ package de.muehlencord.shared.security; import static de.muehlencord.shared.security.Luhn.computeCheckDigit; import static de.muehlencord.shared.security.Luhn.validateNumber; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * diff --git a/security/src/test/java/de/muehlencord/shared/security/OldPasswordUtilTest.java b/security/src/test/java/de/muehlencord/shared/security/OldPasswordUtilTest.java index 4fd8128..dd956f4 100644 --- a/security/src/test/java/de/muehlencord/shared/security/OldPasswordUtilTest.java +++ b/security/src/test/java/de/muehlencord/shared/security/OldPasswordUtilTest.java @@ -2,153 +2,153 @@ package de.muehlencord.shared.security; import static de.muehlencord.shared.security.OldPasswordUtil.getScryptHash; import static de.muehlencord.shared.security.OldPasswordUtil.validateScryptHash; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * * @author jomu */ public class OldPasswordUtilTest { - - /** - * Test of createSaltString method, of class PasswordUtil. - */ - @Test - public void createSaltString() throws Exception { - System.out.println("createSaltString"); - int saltLength = 40; - String result = OldPasswordUtil.createSaltString(saltLength); - assertNotNull(result); - } - /** - * Test of getMD5Password method, of class PasswordUtil. - */ - @Test - public void getMD5Password() throws Exception { - System.out.println("getMD5Password"); - String plainTextPassword = ""; - int saltLength = 40; - String[] result1 = OldPasswordUtil.getMD5Password(plainTextPassword, saltLength); - String password1 = result1[0]; - String salt1 = result1[1]; - assertNotNull(result1); - assertNotNull(password1); - assertNotNull(salt1); - - String[] result2 = OldPasswordUtil.getMD5Password(plainTextPassword, saltLength); - String password2 = result2[0]; - String salt2 = result2[1]; - assertNotNull(result2); - assertNotNull(password2); - assertNotNull(salt2); - - assertNotSame(result1, result2); - assertNotSame(password1, password2); - assertNotSame(salt1, salt2); - } + /** + * Test of createSaltString method, of class PasswordUtil. + */ + @Test + public void createSaltString() throws Exception { + System.out.println("createSaltString"); + int saltLength = 40; + String result = OldPasswordUtil.createSaltString(saltLength); + assertNotNull(result); + } + /** + * Test of getMD5Password method, of class PasswordUtil. + */ + @Test + public void getMD5Password() throws Exception { + System.out.println("getMD5Password"); + String plainTextPassword = ""; + int saltLength = 40; + String[] result1 = OldPasswordUtil.getMD5Password(plainTextPassword, saltLength); + String password1 = result1[0]; + String salt1 = result1[1]; + assertNotNull(result1); + assertNotNull(password1); + assertNotNull(salt1); - + String[] result2 = OldPasswordUtil.getMD5Password(plainTextPassword, saltLength); + String password2 = result2[0]; + String salt2 = result2[1]; + assertNotNull(result2); + assertNotNull(password2); + assertNotNull(salt2); + + assertNotSame(result1, result2); + assertNotSame(password1, password2); + assertNotSame(salt1, salt2); + } + + /** + * Test of checkPassword method, of class PasswordUtil. + */ + @Test + public void checkPassword() throws Exception { + System.out.println("checkPassword"); + String plainTextPassword = "welcome"; + String plainTextPassword2 = "this is not the correct password"; + + String[] data = OldPasswordUtil.getMD5Password(plainTextPassword, 40); + String cryptedPassword = data[0]; + String salt = data[1]; + + String salt2 = OldPasswordUtil.createSaltString(40); + String salt3 = OldPasswordUtil.createSaltString(10); + + boolean expResult = true; + boolean result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt); + assertTrue(expResult == result); + + expResult = false; + result = OldPasswordUtil.checkPassword(plainTextPassword2, cryptedPassword, salt); + assertTrue(expResult == result); + + expResult = false; + result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt2); + assertTrue(expResult == result); + + expResult = false; + result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt3); + assertTrue(expResult == result); + } - /** - * Test of checkPassword method, of class PasswordUtil. - */ - @Test - public void checkPassword() throws Exception { - System.out.println("checkPassword"); - String plainTextPassword = "welcome"; - String plainTextPassword2 = "this is not the correct password"; - - String[] data = OldPasswordUtil.getMD5Password(plainTextPassword, 40); - String cryptedPassword = data[0]; - String salt = data[1]; - - String salt2 = OldPasswordUtil.createSaltString(40); - String salt3 = OldPasswordUtil.createSaltString(10); - - boolean expResult = true; - boolean result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt); - assertEquals(expResult, result); - - expResult = false; - result = OldPasswordUtil.checkPassword(plainTextPassword2, cryptedPassword, salt); - assertEquals(expResult, result); - - expResult = false; - result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt2); - assertEquals(expResult, result); - - expResult = false; - result = OldPasswordUtil.checkPassword(plainTextPassword, cryptedPassword, salt3); - assertEquals(expResult, result); - } - @Test public void getRandomString() throws SecurityException { - System.out.println ("getRandomString"); + System.out.println("getRandomString"); String randomString = OldPasswordUtil.getRandomString("test-", 32); System.out.println(randomString); assertNotNull(randomString); - assertTrue("string must start with prefix", randomString.startsWith("test")); - assertEquals("string length check", 32, randomString.length()); - + assertTrue(randomString.startsWith("test"), "string must start with prefix"); + assertTrue(32 == randomString.length(), "string length check"); + String randomString2 = OldPasswordUtil.getRandomString("test-", 32); System.out.println(randomString2); assertNotNull(randomString2); - assertTrue("string must start with prefix", randomString2.startsWith("test")); - assertEquals("string length check", 32, randomString2.length()); - + assertTrue(randomString2.startsWith("test"), "string must start with prefix"); + assertTrue(32 == randomString2.length(), "string length check"); + assertNotSame(randomString, randomString2); } @Test public void getRandomStringBlankPrefix() throws SecurityException { - System.out.println ("getRandomStringBlankPrefix"); + System.out.println("getRandomStringBlankPrefix"); String randomString = OldPasswordUtil.getRandomString("", 32); System.out.println(randomString); assertNotNull(randomString); - assertEquals("string length check", 32, randomString.length()); + assertTrue(32 == randomString.length(), "string length check"); } @Test public void getRandomStringNullPrefix() throws SecurityException { - System.out.println ("getRandomStringNullPrefix"); + System.out.println("getRandomStringNullPrefix"); String randomString = OldPasswordUtil.getRandomString(null, 32); System.out.println(randomString); assertNotNull(randomString); - assertEquals("string length check", 32, randomString.length()); - } - + assertTrue(32 == randomString.length(), "string length check"); + } + /** * test the hashPassword method */ @Test public void testGetScryptHash() { - String hash1 = getScryptHash("secret"); + String hash1 = getScryptHash("secret"); String hash2 = getScryptHash("secret"); - System.out.println (hash1); - System.out.println (hash2); - assertNotNull (hash1); - assertNotNull (hash2); + System.out.println(hash1); + System.out.println(hash2); + assertNotNull(hash1); + assertNotNull(hash2); // even if password is the same, the has must not be the same due to correct usage of salts - assertFalse (hash1.equals (hash2)); - - assertTrue (hash1.length() == 79); - assertTrue (hash2.length() == 79); + assertFalse(hash1.equals(hash2)); + + assertTrue(hash1.length() == 79); + assertTrue(hash2.length() == 79); } - + /** * test for validating passwords */ @Test public void testValidateScryptHash() { - String hash1 = getScryptHash("secret"); + String hash1 = getScryptHash("secret"); String hash2 = getScryptHash("secret"); - assertTrue ("hash must match if correct password is given",validateScryptHash("secret", hash1)); - assertTrue ("hash must match if correct password is given", validateScryptHash("secret", hash2)); - assertFalse ("hash must not match if wrong password is given", validateScryptHash("secret2", hash1)); - } + assertTrue(validateScryptHash("secret", hash1), "hash must match if correct password is given"); + assertTrue(validateScryptHash("secret", hash2), "hash must match if correct password is given"); + assertFalse(validateScryptHash("secret2", hash1), "hash must not match if wrong password is given"); + } -} \ No newline at end of file +} diff --git a/security/src/test/java/de/muehlencord/shared/security/PasswordUtilTest.java b/security/src/test/java/de/muehlencord/shared/security/PasswordUtilTest.java index d4dbc79..9585872 100644 --- a/security/src/test/java/de/muehlencord/shared/security/PasswordUtilTest.java +++ b/security/src/test/java/de/muehlencord/shared/security/PasswordUtilTest.java @@ -1,12 +1,11 @@ package de.muehlencord.shared.security; -import de.muehlencord.shared.security.PasswordUtil; import java.security.SecureRandom; import org.bouncycastle.util.encoders.Base64; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.junit.BeforeClass; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @@ -18,7 +17,7 @@ public class PasswordUtilTest { private static String systemSalt64Coded; private static byte[] systemSaltBytes; - @BeforeClass + @BeforeAll public static void init() { secureRandom = new SecureRandom(); diff --git a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/NtlmAuthenticatorTest.java b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/NtlmAuthenticatorTest.java index 6509b38..c52cedc 100644 --- a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/NtlmAuthenticatorTest.java +++ b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/NtlmAuthenticatorTest.java @@ -15,7 +15,7 @@ public class NtlmAuthenticatorTest extends BaseTest { @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testAuthentication() throws MalformedURLException, NoSuchAlgorithmException, KeyManagementException { SPSite instance = new SPSite(getContext()); // instance.getRootWeb(); diff --git a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/SharepointConfigTest.java b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/SharepointConfigTest.java index 63d09d1..9909b3f 100644 --- a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/SharepointConfigTest.java +++ b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/SharepointConfigTest.java @@ -14,7 +14,7 @@ public class SharepointConfigTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testLoadFromFile() throws Exception { SharepointConfig c = new SharepointConfig(); c.loadFromFile(); diff --git a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListTest.java b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListTest.java index 4e3da93..0da310a 100644 --- a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListTest.java +++ b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListTest.java @@ -23,7 +23,7 @@ import org.xml.sax.SAXException; public class SPListTest extends BaseTest { @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testFromXML() throws Exception { String xmlString = readFileContentFromTest("lists/testlist.xml", "UTF-8"); SPList list = new SPList(getContext(), "{924883B9-41B7-430C-8206-151786A67319}"); @@ -32,7 +32,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void addListItemByTitle() throws NoSuchAlgorithmException, KeyManagementException, JAXBException, SAXException, ParserConfigurationException, IOException { @@ -58,7 +58,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void addListItemBigList() throws NoSuchAlgorithmException, KeyManagementException, JAXBException, SAXException, ParserConfigurationException, IOException { @@ -93,7 +93,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetListItems() throws Exception { SPLists instance = new SPLists(getContext()); SPList list = instance.getSpListByTitle("Questionnaire_Countries"); @@ -111,7 +111,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetListItemsQuery() throws Exception { SPLists instance = new SPLists(getContext()); SPList list = instance.getSpListByTitle("Questionnaire_Countries"); @@ -135,7 +135,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetLookupValueMap() throws Exception { SPLists instance = new SPLists(getContext()); SPList list = instance.getSpListByTitle("Questionnaire_Countries"); @@ -145,7 +145,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetColumnNameByDisplayName() throws Exception { SPLists instance = new SPLists(getContext()); SPList list = instance.getSpListByTitle("Questionnaire"); @@ -153,7 +153,7 @@ public class SPListTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetItemCount() throws Exception { SPLists instance = new SPLists(getContext()); SPList list = instance.getSpListByTitle("Questionnaire"); diff --git a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListsTest.java b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListsTest.java index 9a87b8b..c6f4263 100644 --- a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListsTest.java +++ b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/lists/SPListsTest.java @@ -18,7 +18,7 @@ public class SPListsTest extends BaseTest { @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testFromXML() throws IOException, JAXBException, SAXException { String xmlString = readFileContentFromTest("lists/testlists.xml", "UTF-8"); SPLists lists = new SPLists(getContext()); @@ -27,7 +27,7 @@ public class SPListsTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetListName() throws Exception { SPLists instance = new SPLists(getContext()); String listName = instance.getListNameByTitle("Questionnaire"); diff --git a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/usergroup/SPUserGroupTest.java b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/usergroup/SPUserGroupTest.java index 16912d9..378fc2c 100644 --- a/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/usergroup/SPUserGroupTest.java +++ b/sharepoint/api/src/test/java/de/muehlencord/shared/sharepoint/api/usergroup/SPUserGroupTest.java @@ -18,7 +18,7 @@ public class SPUserGroupTest extends BaseTest { private final static Logger LOGGER = LoggerFactory.getLogger(SPUserGroupTest.class.getName()); @Test - @Ignore + @Disabled public void testFromXML() throws Exception { String xmlString = readFileContentFromTest("usergroups/user.xml", "UTF-8"); SPUser user = new SPUser(getContext()); @@ -27,7 +27,7 @@ public class SPUserGroupTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testGetUserInfo() throws Exception { SPUserGroup ug = new SPUserGroup(getContext()); String userId = ug.getUserId("wincor-nixdorf\\joern.muehlencord"); @@ -35,14 +35,14 @@ public class SPUserGroupTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testAddUserToGroup() throws Exception { SPUserGroup ug = new SPUserGroup(getContext()); ug.addUserToGroup("wincor-nixdorf\\joern.muehlencord", "Test Group"); } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void testIsUserMemberOfGroup() throws Exception { SPUserGroup ug = new SPUserGroup(getContext()); boolean result = ug.isUserMemberOfGroup("wincor-nixdorf\\joern.muehlencord", "HQ All Members"); @@ -50,7 +50,7 @@ public class SPUserGroupTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void getUserLoginNameFromEmail() throws Exception { SPUserGroup ug = new SPUserGroup(getContext()); SPUser user = ug.getUserFromEmail("joern.muehlencord@wincor-nixdorf.com"); @@ -58,7 +58,7 @@ public class SPUserGroupTest extends BaseTest { } @Test - @Ignore // Depends on available sharepoint currently + @Disabled // Depends on available sharepoint currently public void getUserFromEmail() throws Exception { SPUserGroup ug = new SPUserGroup(getContext()); String user1Email = "nicole.cravo@wincor-nixdorf.com"; diff --git a/util/pom.xml b/util/pom.xml index 7e75872..4e110cf 100644 --- a/util/pom.xml +++ b/util/pom.xml @@ -22,8 +22,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter-engine test diff --git a/util/src/main/java/de/muehlencord/shared/util/StringUtil.java b/util/src/main/java/de/muehlencord/shared/util/StringUtil.java index 46897a1..a208608 100644 --- a/util/src/main/java/de/muehlencord/shared/util/StringUtil.java +++ b/util/src/main/java/de/muehlencord/shared/util/StringUtil.java @@ -2,8 +2,6 @@ package de.muehlencord.shared.util; import java.io.UnsupportedEncodingException; import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/util/src/test/java/de/muehlencord/shared/util/OSUtilTest.java b/util/src/test/java/de/muehlencord/shared/util/OSUtilTest.java index 24c49c6..7151a5a 100644 --- a/util/src/test/java/de/muehlencord/shared/util/OSUtilTest.java +++ b/util/src/test/java/de/muehlencord/shared/util/OSUtilTest.java @@ -7,8 +7,9 @@ package de.muehlencord.shared.util; import static de.muehlencord.shared.util.OSUtil.getOperationSystem; import static java.lang.System.getProperties; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; /** * diff --git a/util/src/test/java/de/muehlencord/shared/util/StringEncodingExceptionTest.java b/util/src/test/java/de/muehlencord/shared/util/StringEncodingExceptionTest.java index b06cafa..91107a6 100644 --- a/util/src/test/java/de/muehlencord/shared/util/StringEncodingExceptionTest.java +++ b/util/src/test/java/de/muehlencord/shared/util/StringEncodingExceptionTest.java @@ -6,8 +6,8 @@ package de.muehlencord.shared.util; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * diff --git a/util/src/test/java/de/muehlencord/shared/util/StringUtilTest.java b/util/src/test/java/de/muehlencord/shared/util/StringUtilTest.java index 7eb3207..284a3ee 100644 --- a/util/src/test/java/de/muehlencord/shared/util/StringUtilTest.java +++ b/util/src/test/java/de/muehlencord/shared/util/StringUtilTest.java @@ -3,8 +3,8 @@ package de.muehlencord.shared.util; import static de.muehlencord.shared.util.StringUtil.getValueBetweenKeywords; import java.io.IOException; import java.text.ParseException; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Basic StringUtilTests @@ -18,6 +18,6 @@ public class StringUtilTest extends DefaultTest { String content = readContentFromFile("test.txt"); String ipAddress = getValueBetweenKeywords(content, "The IP", "has just"); - assertEquals("ipAddress", "222.184.230.118", ipAddress); + assertEquals("222.184.230.118", ipAddress, "ipAddress"); } } diff --git a/util/src/test/java/de/muehlencord/shared/util/file/FileUtilTest.java b/util/src/test/java/de/muehlencord/shared/util/file/FileUtilTest.java index 33b090c..f82d0eb 100644 --- a/util/src/test/java/de/muehlencord/shared/util/file/FileUtilTest.java +++ b/util/src/test/java/de/muehlencord/shared/util/file/FileUtilTest.java @@ -7,8 +7,8 @@ import java.net.URISyntaxException; import java.net.URL; import java.util.Iterator; import java.util.List; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @@ -22,7 +22,7 @@ public class FileUtilTest { * @throws URISyntaxException if the testfile specification is wrong */ @Test - @Ignore + @Disabled public void testGetFilesFromDirecotry() throws FileHandlingException, URISyntaxException { System.out.println("testGetFilesFromDirectory");