maxkey-entity & maxkey-commons 拆分

maxkey-cache
maxkey-core
maxkey-crypto
maxkey-ldap
This commit is contained in:
MaxKey
2025-07-27 08:36:33 +08:00
parent c6224f9f9d
commit ca90c0ba93
208 changed files with 608 additions and 274 deletions

View File

@@ -1,287 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration;
import org.dromara.maxkey.constants.ConstsDatabase;
import org.dromara.maxkey.constants.ConstsPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* 全局应用程序配置 包含 1、数据源配置 dataSoruceConfig 2、字符集转换配置 characterEncodingConfig
* 3、webseal认证集成配置 webSealConfig 4、系统的配置 sysConfig 5、所有用户可访问地址配置 allAccessUrl
*
* 其中1、2、3项在applicationContext.xml中配置配置文件applicationConfig.properties
* 4项根据dynamic的属性判断是否动态从sysConfigService动态读取
*
* @author Crystal.Sea
*
*/
@Component
@Configuration
public class ApplicationConfig {
@Value("${maxkey.server.basedomain}")
String baseDomainName;
@Value("${maxkey.server.domain}")
String domainName;
@Value("${maxkey.server.name}")
String serverName;
@Value("${maxkey.server.uri}")
String serverPrefix;
@Value("${maxkey.server.default.uri}")
String defaultUri;
@Value("${maxkey.server.mgt.uri}")
String mgtUri;
@Value("${maxkey.server.authz.uri}")
private String authzUri;
@Value("${maxkey.server.frontend.uri:http://sso.maxkey.top:4200}")
private String frontendUri;
@Value("${server.port:8080}")
private int port;
@Value("${maxkey.server.provision:false}")
private boolean provision;
@Value("${maxkey.server.persistence}")
int persistence;
@Value("${maxkey.notices.visible:false}")
private boolean noticesVisible;
static String databaseProduct = ConstsDatabase.MYSQL;
@Autowired
EmailConfig emailConfig;
@Autowired
CharacterEncodingConfig characterEncodingConfig;
@Autowired
LoginConfig loginConfig;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ApplicationConfig() {
super();
}
/**
* @return the characterEncodingConfig
*/
public CharacterEncodingConfig getCharacterEncodingConfig() {
return characterEncodingConfig;
}
/**
* @param characterEncodingConfig the characterEncodingConfig to set
*/
public void setCharacterEncodingConfig(CharacterEncodingConfig characterEncodingConfig) {
this.characterEncodingConfig = characterEncodingConfig;
}
public LoginConfig getLoginConfig() {
return loginConfig;
}
public void setLoginConfig(LoginConfig loginConfig) {
this.loginConfig = loginConfig;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getServerPrefix() {
return serverPrefix;
}
public void setServerPrefix(String serverPrefix) {
this.serverPrefix = serverPrefix;
}
public String getFrontendUri() {
return frontendUri;
}
public void setFrontendUri(String frontendUri) {
this.frontendUri = frontendUri;
}
/**
* @return the domainName
*/
public String getDomainName() {
return domainName;
}
/**
* @param domainName the domainName to set
*/
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getBaseDomainName() {
return baseDomainName;
}
public void setBaseDomainName(String baseDomainName) {
this.baseDomainName = baseDomainName;
}
/**
* @return the emailConfig
*/
public EmailConfig getEmailConfig() {
return emailConfig;
}
/**
* @param emailConfig the emailConfig to set
*/
public void setEmailConfig(EmailConfig emailConfig) {
this.emailConfig = emailConfig;
}
public String getDefaultUri() {
return defaultUri;
}
public void setDefaultUri(String defaultUri) {
this.defaultUri = defaultUri;
}
public boolean isProvision() {
return provision;
}
public void setProvision(boolean provision) {
this.provision = provision;
}
public boolean isProvisionSupport() {
return provision;
}
public int getPersistence() {
return persistence;
}
public void setPersistence(int persistence) {
this.persistence = persistence;
}
public boolean isPersistenceRedis() {
return persistence == ConstsPersistence.REDIS;
}
public boolean isPersistenceInmemory() {
return persistence == ConstsPersistence.INMEMORY;
}
public String getMgtUri() {
return mgtUri;
}
public void setMgtUri(String mgtUri) {
this.mgtUri = mgtUri;
}
public String getAuthzUri() {
return authzUri;
}
public void setAuthzUri(String authzUri) {
this.authzUri = authzUri;
}
public boolean isNoticesVisible() {
return noticesVisible;
}
public void setNoticesVisible(boolean noticesVisible) {
this.noticesVisible = noticesVisible;
}
public static String getDatabaseProduct() {
return databaseProduct;
}
public static void setDatabaseProduct(String databaseProduct) {
ApplicationConfig.databaseProduct = databaseProduct;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ApplicationConfig [emailConfig=");
builder.append(emailConfig);
builder.append(", characterEncodingConfig=");
builder.append(characterEncodingConfig);
builder.append(", loginConfig=");
builder.append(loginConfig);
builder.append(", baseDomainName=");
builder.append(baseDomainName);
builder.append(", domainName=");
builder.append(domainName);
builder.append(", serverName=");
builder.append(serverName);
builder.append(", serverPrefix=");
builder.append(serverPrefix);
builder.append(", defaultUri=");
builder.append(defaultUri);
builder.append(", managementUri=");
builder.append(mgtUri);
builder.append(", port=");
builder.append(port);
builder.append(", provision=");
builder.append(provision);
builder.append(", maxKeyUri=");
builder.append(authzUri);
builder.append("]");
return builder.toString();
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@Configuration
public class AuthJwkConfig {
@Value("${maxkey.auth.jwt.expires:28800}")
int expires;
@Value("${maxkey.auth.jwt.secret}")
String secret;
@Value("${maxkey.auth.jwt.refresh.expires:86400}")
int refreshExpires;
@Value("${maxkey.auth.jwt.refresh.secret}")
String refreshSecret;
@Value("${maxkey.auth.jwt.issuer:https://sso.maxkey.top/}")
String issuer;
public AuthJwkConfig() {
super();
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public int getExpires() {
return expires;
}
public void setExpires(int expires) {
this.expires = expires;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getRefreshExpires() {
return refreshExpires;
}
public void setRefreshExpires(int refreshExpires) {
this.refreshExpires = refreshExpires;
}
public String getRefreshSecret() {
return refreshSecret;
}
public void setRefreshSecret(String refreshSecret) {
this.refreshSecret = refreshSecret;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AuthJwkConfig [issuer=");
builder.append(issuer);
builder.append(", expires=");
builder.append(expires);
builder.append(", secret=");
builder.append(secret);
builder.append("]");
return builder.toString();
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration;
import java.io.UnsupportedEncodingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* 字符集转换及转换配置.
*
* @author Crystal.Sea
*
*/
@Configuration
public class CharacterEncodingConfig {
/**
* 源字符集.
*/
@Value("${server.servlet.encoding.charset.from:UTF-8}")
String fromCharSet;
/**
* 目标字符集.
*/
@Value("${server.servlet.encoding.charset:UTF-8}")
String toCharSet;
/**
* 转换标志.
*/
@Value("${server.servlet.encoding.enabled:false}")
boolean encoding = false;
public CharacterEncodingConfig() {
}
public String getFromCharSet() {
return fromCharSet;
}
public void setFromCharSet(String fromCharSet) {
this.fromCharSet = fromCharSet;
}
public String getToCharSet() {
return toCharSet;
}
public void setToCharSet(String toCharSet) {
this.toCharSet = toCharSet;
}
public boolean isEncoding() {
return encoding;
}
public void setEncoding(boolean encoding) {
this.encoding = encoding;
}
/**
* 字符集转换.
*
* @param encodingString 源字符串
* @return encoded目标字符串
*/
public String encoding(String encodingString) {
if (!this.encoding || encodingString == null) {
return encodingString;
}
try {
return new String(encodingString.getBytes(this.fromCharSet), this.toCharSet);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CharacterEncodingConfig [fromCharSet=");
builder.append(fromCharSet);
builder.append(", toCharSet=");
builder.append(toCharSet);
builder.append(", encoding=");
builder.append(encoding);
builder.append("]");
return builder.toString();
}
}

View File

@@ -1,156 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmailConfig {
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Value("${spring.mail.host}")
private String smtpHost;
@Value("${spring.mail.port:465}")
private Integer port;
@Value("${spring.mail.properties.ssl:false}")
private boolean ssl;
@Value("${spring.mail.properties.sender}")
private String sender;
public EmailConfig() {
}
public EmailConfig(String username, String password, String smtpHost, Integer port, boolean ssl, String sender) {
super();
this.username = username;
this.password = password;
this.smtpHost = smtpHost;
this.port = port;
this.ssl = ssl;
this.sender = sender;
}
/*
* @return the username
*/
public String getUsername() {
return username;
}
/*
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/*
* @return the password
*/
public String getPassword() {
return password;
}
/*
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/*
* @return the smtpHost
*/
public String getSmtpHost() {
return smtpHost;
}
/*
* @param smtpHost the smtpHost to set
*/
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
/*
* @return the port
*/
public Integer getPort() {
return port;
}
/*
* @param port the port to set
*/
public void setPort(Integer port) {
this.port = port;
}
/*
* @return the ssl
*/
public boolean isSsl() {
return ssl;
}
/*
* @param ssl the ssl to set
*/
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("EmailConfig [username=");
builder.append(username);
builder.append(", password=");
builder.append(password);
builder.append(", smtpHost=");
builder.append(smtpHost);
builder.append(", port=");
builder.append(port);
builder.append(", ssl=");
builder.append(ssl);
builder.append(", sender=");
builder.append(sender);
builder.append("]");
return builder.toString();
}
}

View File

@@ -1,137 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LoginConfig {
@Value("${maxkey.login.captcha:true}")
boolean captcha;
@Value("${maxkey.login.captcha.type:TEXT}")
String captchaType;
@Value("${maxkey.login.mfa:false}")
boolean mfa;
@Value("${maxkey.login.kerberos:false}")
boolean kerberos;
@Value("${maxkey.login.remeberme:false}")
boolean remeberMe;
@Value("${maxkey.login.wsfederation:false}")
boolean wsFederation;
@Value("${maxkey.login.cas.serverUrlPrefix:http://sso.maxkey.top/sign/authz/cas}")
String casServerUrlPrefix;
@Value("${maxkey.login.cas.service:http://mgt.maxkey.top/maxkey-mgt/passport/trust/auth}")
String casService;
/**
* .
*/
public LoginConfig() {
}
public boolean isCaptcha() {
return captcha;
}
public void setCaptcha(boolean captcha) {
this.captcha = captcha;
}
public boolean isKerberos() {
return kerberos;
}
public void setKerberos(boolean kerberos) {
this.kerberos = kerberos;
}
public boolean isMfa() {
return mfa;
}
public void setMfa(boolean mfa) {
this.mfa = mfa;
}
public boolean isRemeberMe() {
return remeberMe;
}
public void setRemeberMe(boolean remeberMe) {
this.remeberMe = remeberMe;
}
public boolean isWsFederation() {
return wsFederation;
}
public void setWsFederation(boolean wsFederation) {
this.wsFederation = wsFederation;
}
public String getCasServerUrlPrefix() {
return casServerUrlPrefix;
}
public void setCasServerUrlPrefix(String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
}
public String getCasService() {
return casService;
}
public void setCasService(String casService) {
this.casService = casService;
}
public String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
this.captchaType = captchaType;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("LoginConfig [mfa=");
builder.append(mfa);
builder.append(", kerberos=");
builder.append(kerberos);
builder.append(", remeberMe=");
builder.append(remeberMe);
builder.append(", wsFederation=");
builder.append(wsFederation);
builder.append("]");
return builder.toString();
}
}

View File

@@ -1,57 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration.oidc;
import java.net.URI;
import java.util.Set;
public interface OIDCProviderMetadata {
public String getIssuer();
public void setIssuer(String issuer);
public URI getAuthorizationEndpoint();
public void setAuthorizationEndpoint(URI authorizationEndpoint);
public URI getTokenEndpoint();
public void setTokenEndpoint(URI tokenEndpoint);
public URI getUserinfoEndpoint();
public void setUserinfoEndpoint(URI userinfoEndpoint);
public URI getJwksUri();
public void setJwksUri(URI jwksUri);
public URI getRegistrationEndpoint();
public void setRegistrationEndpoint(URI registrationEndpoint);
public Set<String> getScopesSupported();
public void setScopesSupported(Set<String> scopesSupported);
public Set<String> getResponseTypesSupported();
public void setResponseTypesSupported(Set<String> responseTypesSupported);
}

View File

@@ -1,152 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.configuration.oidc;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* OIDCProviderMetadataDetails.
* @author cm
*
*/
public class OIDCProviderMetadataDetails implements OIDCProviderMetadata {
protected String issuer;
protected URI authorizationEndpoint;
protected URI tokenEndpoint;
protected URI userinfoEndpoint;
protected URI jwksUri;
protected URI registrationEndpoint;
protected Set<String> scopesSupported;
protected Set<String> responseTypesSupported;
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public URI getAuthorizationEndpoint() {
return authorizationEndpoint;
}
public void setAuthorizationEndpoint(URI authorizationEndpoint) {
this.authorizationEndpoint = authorizationEndpoint;
}
public URI getTokenEndpoint() {
return tokenEndpoint;
}
public void setTokenEndpoint(URI tokenEndpoint) {
this.tokenEndpoint = tokenEndpoint;
}
public URI getUserinfoEndpoint() {
return userinfoEndpoint;
}
public void setUserinfoEndpoint(URI userinfoEndpoint) {
this.userinfoEndpoint = userinfoEndpoint;
}
public URI getJwksUri() {
return jwksUri;
}
public void setJwksUri(URI jwksUri) {
this.jwksUri = jwksUri;
}
public URI getRegistrationEndpoint() {
return registrationEndpoint;
}
public void setRegistrationEndpoint(URI registrationEndpoint) {
this.registrationEndpoint = registrationEndpoint;
}
public Set<String> getScopesSupported() {
return scopesSupported;
}
public void setScopesSupported(Set<String> scopesSupported) {
this.scopesSupported = scopesSupported;
}
public Set<String> getResponseTypesSupported() {
return responseTypesSupported;
}
public void setResponseTypesSupported(Set<String> responseTypesSupported) {
this.responseTypesSupported = responseTypesSupported;
}
@Override
public String toString() {
final int maxLen = 4;
StringBuilder builder = new StringBuilder();
builder.append("OIDCProviderMetadataDetails [issuer=");
builder.append(issuer);
builder.append(", authorizationEndpoint=");
builder.append(authorizationEndpoint);
builder.append(", tokenEndpoint=");
builder.append(tokenEndpoint);
builder.append(", userinfoEndpoint=");
builder.append(userinfoEndpoint);
builder.append(", jwksUri=");
builder.append(jwksUri);
builder.append(", registrationEndpoint=");
builder.append(registrationEndpoint);
builder.append(", scopesSupported=");
builder.append(scopesSupported != null ? toString(scopesSupported, maxLen) : null);
builder.append(", responseTypesSupported=");
builder.append(responseTypesSupported != null ? toString(responseTypesSupported, maxLen) : null);
builder.append("]");
return builder.toString();
}
private String toString(Collection<?> collection, int maxLen) {
StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {
if (i > 0) {
builder.append(", ");
}
builder.append(iterator.next());
}
builder.append("]");
return builder.toString();
}
// Complete remaining properties from
// http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
}

View File

@@ -1,63 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class ConstsAct {
public static final String CREATE = "create";
public static final String DELETE = "delete";
public static final String UPDATE = "update";
public static final String CHANGE_PASSWORD = "change_password";
public static final String FORGOT_PASSWORD = "forgot_password";
public static final String ADD_MEMBER = "add_member";
public static final String DELETE_MEMBER = "delete_member";
public static final String ENABLE = "enable";
public static final String DISABLE = "disable";
public static final String INACTIVE = "inactive";
public static final String LOCK = "lock";
public static final String UNLOCK = "unlock";
public static final String VIEW = "view";
public static final ConcurrentMap<Integer,String> statusActon ;
static {
statusActon = new ConcurrentHashMap<>();
statusActon.put(ConstsStatus.ACTIVE, ENABLE);
statusActon.put(ConstsStatus.INACTIVE, INACTIVE);
statusActon.put(ConstsStatus.DISABLED, DISABLE);
statusActon.put(ConstsStatus.LOCK, LOCK);
statusActon.put(ConstsStatus.UNLOCK, UNLOCK);
statusActon.put(ConstsStatus.DELETE, DELETE);
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public final class ConstsActResult {
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String FAIL = "fail";
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
/**
* Define int for boolean 0 false 1 true.
*
* @author Crystal.Sea
*
*/
public class ConstsBoolean {
public static final int FALSE = 0;
public static final int TRUE = 1;
private int value = FALSE;
public ConstsBoolean() {
}
public int getValue() {
return value;
}
public boolean isValue() {
return TRUE == value;
}
public void setValue(int value) {
this.value = value;
}
public static boolean isTrue(int value) {
return TRUE == value;
}
public static boolean isYes(String value) {
return "YES".equalsIgnoreCase(value);
}
public static boolean isFalse(int value) {
return FALSE == value;
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
import org.dromara.maxkey.configuration.ApplicationConfig;
public class ConstsDatabase {
public static final String MYSQL = "MySQL";
public static final String POSTGRESQL = "PostgreSQL";
public static final String ORACLE = "Oracle";
public static final String MSSQLSERVER = "SQL Server";
public static final String DB2 = "db2";
public static boolean compare(String databaseProduct) {
return databaseProduct.equalsIgnoreCase(ApplicationConfig.getDatabaseProduct());
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public class ConstsEntryType {
public static String USERINFO = "user";
public static String ORGANIZATION = "organization";
public static String APPLICATION = "application";
public static String ACCOUNT = "account";
public static String ROLE = "role";
public static String PASSWORD = "password";
public static String RESOURCE = "resource";
public static String PERMISSION = "permission";
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public class ConstsLoginType {
public static final String LOCAL = "Local Login";
public static final String BASIC = "Basic";
public static final String SOCIALSIGNON = "Social Sign On";
public static final String REMEBER_ME = "RemeberMe";
public static final String DESKTOP = "Desktop";
public static final String KERBEROS = "Kerberos";
public static final String SAMLTRUST = "SAML v2.0 Trust";
public static final String MSADTRUST = "MS AD Trust";
public static final String CAS = "CAS";
public static final String WSFEDERATION = "WsFederation";
public static final String JWT = "Jwt";
public static final String HTTPHEADER = "HttpHeader";
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
/**
* PASSWORDSETTYPE.
* @author Crystal.Sea
*
*/
public final class ConstsPasswordSetType {
public static final int PASSWORD_NORMAL = 0;
public static final int INITIAL_PASSWORD = 1;
public static final int PASSWORD_EXPIRED = 3;
public static final int MANAGER_CHANGED_PASSWORD = 2;
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
/**
* PROTOCOLS.
* @author Crystal.Sea
*
*/
public final class ConstsPersistence {
public static final int INMEMORY = 0;
public static final int JDBC = 1;
public static final int REDIS = 2;
}

View File

@@ -1,27 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public final class ConstsPlatformRole {
public static final String PLATFORM_ADMIN = "PLATFORM_ADMIN";
public static final String TANANT_ADMIN = "TANANT_ADMIN";
public static final String ORDINARY_USER = "ORDINARY_USER";
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public class ConstsProperties {
public static String classPathResource(String propertySource) {
return propertySource.replaceAll("classpath:","");
}
public static String classPathResource(String propertySource,String active) {
if(active == null || active.equals("")) {
return propertySource.replaceAll("classpath:","");
}
return propertySource.replace(".", "-"+active+".").replaceAll("classpath:","");
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
/**
* PROTOCOLS.
* @author Crystal.Sea
*
*/
public final class ConstsProtocols {
public static final String BASIC = "Basic";
public static final String EXTEND_API = "Extend_API";
public static final String FORMBASED = "Form_Based";
public static final String TOKENBASED = "Token_Based";
// SAML
public static final String SAML20 = "SAML_v2.0";
public static final String CAS = "CAS";
public static final String JWT = "JWT";
// OAuth
public static final String OAUTH20 = "OAuth_v2.0";
public static final String OAUTH21 = "OAuth_v2.1";
public static final String OPEN_ID_CONNECT10 = "OpenID_Connect_v1.0";
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
import java.util.regex.Pattern;
/**
* Regex for email , mobile and etc.
*/
public class ConstsRegex {
public static final Pattern EMAIL_PATTERN = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
public static final Pattern MOBILE_PATTERN = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
public static final Pattern IPADDRESS_REGEX = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
public static final Pattern WHITESPACE_REGEX = Pattern.compile("\\s");
public static final Pattern CHINESE_REGEX = Pattern.compile("[\\u4e00-\\u9fa5]");
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
/**
* PROTOCOLS.
* @author Crystal.Sea
*
*/
public final class ConstsRoles {
public static final SimpleGrantedAuthority ROLE_ADMINISTRATORS = new SimpleGrantedAuthority("ROLE_ADMINISTRATORS");
public static final SimpleGrantedAuthority ROLE_MANAGERS = new SimpleGrantedAuthority("ROLE_MANAGERS");
public static final SimpleGrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER");
public static final SimpleGrantedAuthority ROLE_ALL_USER = new SimpleGrantedAuthority("ROLE_ALL_USER");
public static final SimpleGrantedAuthority ROLE_ORDINARY_USER = new SimpleGrantedAuthority("ROLE_ORDINARY_USER");
}

View File

@@ -1,137 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public final class ConstsServiceMessage {
public static final class EMPLOYEES {
public static final String SERVICE_NAME = "employees";
public static final String XE00000001 = "XE00000001";
public static final String XE00000002 = "XE00000002";
public static final String XE00000003 = "XE00000003";
public static final String XE00000004 = "XE00000004";
public static final String XE00000005 = "XE00000005";
public static final String XE00000006 = "XE00000006";
public static final String XE00000007 = "XE00000007";
public static final String XE00000008 = "XE00000008";
public static final String XW00000001 = "XW00000001";
public static final String XW00000002 = "XW00000002";
public static final String XS00000001 = "XS00000001";
public static final String XS00000002 = "XS00000002";
public static final String XS00000003 = "XS00000003";
}
public static final class ENTERPRISES {
public static final String SERVICE_NAME = "enterprises";
public static final String XE00000001 = "XE00000001";
public static final String XE00000002 = "XE00000002";
public static final String XE00000003 = "XE00000003";
public static final String XE00000004 = "XE00000004";
public static final String XE00000005 = "XE00000005";
public static final String XE00000006 = "XE00000006";
public static final String XE00000007 = "XE00000007";
public static final String XE00000008 = "XE00000008";
public static final String XS00000001 = "XS00000001";
public static final String XS00000002 = "XS00000002";
public static final String XS00000003 = "XS00000003";
public static final String XS00000004 = "XS00000004";
}
public static final class RETRIEVEPASSWORD {
public static final String SERVICE_NAME = "retrievepassword";
public static final String XS00000001 = "XS00000001";
public static final String XS00000002 = "XS00000002";
public static final String XE00000001 = "XE00000001";
public static final String XE00000002 = "XE00000002";
public static final String XE00000003 = "XE00000003";
}
public static final class USERCENTER {
public static final String SERVICE_NAME = "usercenter";
public static final String XS00000001 = "XS00000001";
public static final String XS00000002 = "XS00000002";
public static final String XS00000003 = "XS00000003";
public static final String XE00000001 = "XE00000001";
public static final String XE00000002 = "XE00000002";
public static final String XE00000003 = "XE00000003";
}
public static final class APPLICATIONS {
public static final String SERVICE_NAME = "applications";
public static final String XS00000001 = "XS00000001";
public static final String XS00000002 = "XS00000002";
public static final String XS00000003 = "XS00000003";
public static final String XS00000004 = "XS00000004";
public static final String XE00000001 = "XE00000001";
public static final String XE00000002 = "XE00000002";
public static final String XE00000003 = "XE00000003";
public static final String XE00000004 = "XE00000004";
}
public static final class APPROLES {
public static final String SERVICE_NAME = "approles";
public static final String XE00000002 = "XE00000002";
public static final String XS00000002 = "XS00000002";
public static final String XE00000001 = "XE00000001";
public static final String XS00000001 = "XS00000001";
public static final String XE00000003 = "XE00000003";
public static final String XS00000003 = "XS00000003";
public static final String XE00000004 = "XE00000004";
public static final String XS00000004 = "XS00000004";
public static final String XS00000005 = "XS00000005";
public static final String XE00000005 = "XE00000005";
public static final String XE00000006 = "XE00000006";
public static final String XS00000006 = "XS00000006";
public static final String XE00000007 = "XE00000007";
public static final String XS00000007 = "XS00000007";
public static final String XS00000008 = "XS00000008";
public static final String XE00000008 = "XE00000008";
public static final String XE00000009 = "XE00000009";
public static final String XS00000009 = "XS00000009";
}
public static final class APIUSERS {
public static final String SERVICE_NAME = "apiusers";
public static final String XS00000003 = "XS00000003";
public static final String XE00000003 = "XE00000003";
public static final String XW00000001 = "XW00000001";
public static final String XW00000002 = "XW00000002";
public static final String XS00000001 = "XS00000001";
public static final String XE00000001 = "XE00000001";
}
public static final class PASSWORDPOLICY {
public static final String SERVICE_NAME = "passwordpolicy";
public static final String XW00000002 = "XW00000002";
public static final String XW00000001 = "XW00000001";
public static final String XW00000003 = "XW00000003";
public static final String XW00000004 = "XW00000004";
public static final String XW00000005 = "XW00000005";
public static final String XW00000006 = "XW00000006";
public static final String XW00000007 = "XW00000007";
public static final String XW00000008 = "XW00000008";
}
}

View File

@@ -1,58 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public final class ConstsStatus {
public static final int ACTIVE = 1;
public static final int INACTIVE = 2;
public static final int ENABLED = 3;
public static final int DISABLED = 4;
public static final int LOCK = 5;
public static final int UNLOCK = 6;
public static final int INVALID = 7;
public static final int EXPIRED = 8;
public static final int DELETE = 9;
public static final int VALIDATED = 10;
public static final int START = 11;
public static final int STOP = 12;
public static final int APPLY = 13;
public static final int APPROVED = 14;
public static final int QUITED = 15;
public static final String NONE = "NONE";
public static final String YES = "YES";
public static final String NO = "NO";
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public final class ConstsTimeInterval {
public static final Integer ONE_MINUTE = 60; // 1 minutes
public static final Integer ONE_HOUR = 60 * 60; // 1 hour
public static final Integer ONE_DAY = 60 * 60 * 24; // 1 day
public static final Integer ONE_WEEK = ONE_DAY * 7; // 1 week
public static final Integer TWO_WEEK = ONE_DAY * 14; // 2 week
public static final Integer ONE_MONTH = ONE_DAY * 30; // 1 month
public static final Integer TWO_MONTH = ONE_DAY * 60; // 2 month
/**
* The number of seconds in one year (= 60 * 60 * 24 * 365).
*/
public static final Integer ONE_YEAR = 60 * 60 * 24 * 365;
}

View File

@@ -1,54 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.constants;
public class ContentType {
public static final String TEXT_PLAIN = "text/plain";
public static final String TEXT_PLAIN_UTF8 = "text/plain;charset=UTF-8";
public static final String TEXT_XML = "text/xml";
public static final String TEXT_XML_UTF8 = "text/xml;charset=UTF-8";
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8";
public static final String APPLICATION_JWT = "application/jwt";
public static final String APPLICATION_JWT_UTF8 = "application/jwt;charset=UTF-8";
public static final String APPLICATION_XML = "application/xml";
public static final String APPLICATION_XML_UTF8 = "application/xml;charset=UTF-8";
public static final String APPLICATION_FORM = "application/x-www-form-urlencoded";
public static final String IMAGE_GIF = "image/gif";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_PNG = "image/png";
public static final String JSON = "json";
public static final String XML = "xml";
}

View File

@@ -26,11 +26,6 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import org.dromara.maxkey.constants.ConstsServiceMessage;
import org.dromara.maxkey.exception.PasswordPolicyException;
import org.dromara.maxkey.web.WebContext;
import java.util.ArrayList;
import java.util.List;
/**
@@ -132,60 +127,6 @@ public class CnfPasswordPolicy extends JpaEntity implements java.io.Serializable
List<String> policMessageList;
public void buildMessage(){
if(policMessageList==null){
policMessageList = new ArrayList<>();
}
String msg;
if (minLength != 0) {
// msg = "新密码长度为"+minLength+"-"+maxLength+"位";
msg = WebContext.getI18nValue("PasswordPolicy.TOO_SHORT",
new Object[]{minLength});
policMessageList.add(msg);
}
if (maxLength != 0) {
// msg = "新密码长度为"+minLength+"-"+maxLength+"位";
msg = WebContext.getI18nValue("PasswordPolicy.TOO_LONG",
new Object[]{maxLength});
policMessageList.add(msg);
}
if (lowerCase > 0) {
//msg = "新密码至少需要包含"+lowerCase+"位【a-z】小写字母";
msg = WebContext.getI18nValue("PasswordPolicy.INSUFFICIENT_LOWERCASE",
new Object[]{lowerCase});
policMessageList.add(msg);
}
if (upperCase > 0) {
//msg = "新密码至少需要包含"+upperCase+"位【A-Z】大写字母";
msg = WebContext.getI18nValue("PasswordPolicy.INSUFFICIENT_UPPERCASE",
new Object[]{upperCase});
policMessageList.add(msg);
}
if (digits > 0) {
//msg = "新密码至少需要包含"+digits+"位【0-9】阿拉伯数字";
msg = WebContext.getI18nValue("PasswordPolicy.INSUFFICIENT_DIGIT",
new Object[]{digits});
policMessageList.add(msg);
}
if (specialChar > 0) {
//msg = "新密码至少需要包含"+specialChar+"位特殊字符";
msg = WebContext.getI18nValue("PasswordPolicy.INSUFFICIENT_SPECIAL",
new Object[]{specialChar});
policMessageList.add(msg);
}
if (expiration > 0) {
//msg = "新密码有效期为"+expiration+"天";
msg = WebContext.getI18nValue("PasswordPolicy.INSUFFICIENT_EXPIRES_DAY",
new Object[]{expiration});
policMessageList.add(msg);
}
}
public List<String> getPolicMessageList() {
return policMessageList;
}
@@ -409,51 +350,6 @@ public class CnfPasswordPolicy extends JpaEntity implements java.io.Serializable
this.randomPasswordLength = randomPasswordLength;
}
public void check(String username, String newPassword, String oldPassword) throws PasswordPolicyException {
if ((1 == this.getUsername()) && newPassword.toLowerCase().contains(username.toLowerCase())) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000001);
}
if (oldPassword != null && newPassword.equalsIgnoreCase(oldPassword)) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000002);
}
if (newPassword.length() < this.getMinLength()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000003, this.getMinLength());
}
if (newPassword.length() > this.getMaxLength()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000004, this.getMaxLength());
}
int numCount = 0, upperCount = 0, lowerCount = 0, spacil = 0;
char[] chPwd = newPassword.toCharArray();
for (int i = 0; i < chPwd.length; i++) {
char ch = chPwd[i];
if (Character.isDigit(ch)) {
numCount++;
continue;
}
if (Character.isLowerCase(ch)) {
lowerCount++;
continue;
}
if (Character.isUpperCase(ch)) {
upperCount++;
continue;
}
spacil++;
}
if (numCount < this.getDigits()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000005, this.getDigits());
}
if (lowerCount < this.getLowerCase()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000006, this.getLowerCase());
}
if (upperCount < this.getUpperCase()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000007, this.getUpperCase());
}
if (spacil < this.getSpecialChar()) {
throw new PasswordPolicyException(ConstsServiceMessage.PASSWORDPOLICY.XW00000008, this.getSpecialChar());
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();

View File

@@ -26,7 +26,6 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.web.WebContext;
@Entity
@Table(name = "MXK_PERMISSION")
@@ -65,8 +64,8 @@ public class Permission extends JpaEntity implements Serializable {
* @param groupId String
* @param resourceId String
*/
public Permission(String appId, String groupId, String resourceId , String instId) {
this.id = WebContext.genId();
public Permission(String id,String appId, String groupId, String resourceId , String instId) {
this.id = id;
this.appId = appId;
this.groupId = groupId;
this.resourceId = resourceId;

View File

@@ -22,7 +22,6 @@ package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.web.WebContext;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
@@ -71,8 +70,8 @@ public class PermissionRole extends JpaEntity implements Serializable {
* @param roleId String
* @param resourceId String
*/
public PermissionRole(String appId, String roleId, String resourceId , String createdBy,String instId) {
this.id = WebContext.genId();
public PermissionRole(String id,String appId, String roleId, String resourceId , String createdBy,String instId) {
this.id = id;
this.appId = appId;
this.roleId = roleId;
this.resourceId = resourceId;

View File

@@ -1,62 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.exception;
/**
* @description:
* @author: orangeBabu
* @time: 16/8/2024 PM3:03
*/
public class BusinessException extends RuntimeException {
/**
* 异常编码
*/
private Integer code;
/**
* 异常消息
*/
private String message;
public BusinessException() {
super();
}
public BusinessException(Integer code, String message) {
this.message = message;
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.exception;
import org.dromara.maxkey.web.WebContext;
/**
* 定义自定义异常
* 异常包括三个属性分别是对应在异常中出现异常的属性field和对于提示错误消息对应的属性文件的KEY。以及属性的错误数据value
* 主要作用在于验证企业的“简称”和“全称”是否有重复
* @author Crystal.Sea
*
*/
public class NameException extends Exception {
public NameException(String field, String key, String value) {
super();
this.field = field;
this.key = key;
this.value = value;
}
private static final long serialVersionUID = -5425015701816705662L;
private String field;
private String key;
private String value;
/**
* @return 返回异常属性
*/
public String getField() {
return field;
}
/**
* @return 返回属性文件的key对应值
*/
public String getKey() {
return WebContext
.getI18nValue("ui.enterprises.enterprises.message."
+ key);
}
/**
* @return 错误数据
*/
public String getValue() {
return value;
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.exception;
public class OperaterSqlException extends Exception {
private static final long serialVersionUID = -5596610890188994830L;
public OperaterSqlException() {
super();
}
public OperaterSqlException(String message) {
super(message);
}
}

View File

@@ -1,58 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.exception;
import org.dromara.maxkey.web.WebContext;
public class PasswordPolicyException extends Exception {
/**
*
*/
private static final long serialVersionUID = -253274228039876768L;
private String errorCode;
private Object filedValue;
public PasswordPolicyException(String errorCode,Object filedValue) {
super();
this.errorCode = errorCode;
this.filedValue = filedValue;
}
public PasswordPolicyException(String errorCode) {
super();
this.errorCode = errorCode;
}
public Object getFiledValue() {
return filedValue;
}
public String getKey() {
return "message.passwordpolicy."+errorCode.toLowerCase();
}
public String getErrorCode() {
return errorCode;
}
@Override
public String getMessage() {
if(filedValue!=null)
return WebContext.getI18nValue(getKey(), new Object[]{filedValue});
else
return WebContext.getI18nValue(getKey());
}
}

View File

@@ -1,65 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.persistence.cache;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryMomentaryService implements MomentaryService{
private static final Logger _logger = LoggerFactory.getLogger(InMemoryMomentaryService.class);
protected static Cache<String, Object> momentaryStore =
Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryMomentaryService() {
super();
}
@Override
public void put(String sessionId , String name, Object value){
_logger.trace("key {}, value {}",getSessionKey(sessionId , name),value);
momentaryStore.put(getSessionKey(sessionId,name), value);
}
@Override
public Object remove(String sessionId , String name) {
Object value = momentaryStore.getIfPresent(getSessionKey(sessionId,name));
momentaryStore.invalidate(getSessionKey(sessionId,name));
_logger.trace("key {}, value {}",getSessionKey(sessionId , name),value);
return value;
}
@Override
public Object get(String sessionId , String name) {
_logger.trace("key {}",getSessionKey(sessionId , name));
return momentaryStore.getIfPresent(getSessionKey(sessionId,name));
}
private String getSessionKey(String sessionId , String name) {
return sessionId + "_" + name;
}
}

View File

@@ -1,28 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.persistence.cache;
public interface MomentaryService {
public void put(String sessionId , String name, Object value);
public Object get(String sessionId , String name);
public Object remove(String sessionId , String name);
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.persistence.cache;
import org.dromara.maxkey.persistence.redis.RedisConnection;
import org.dromara.maxkey.persistence.redis.RedisConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RedisMomentaryService implements MomentaryService {
private static final Logger _logger = LoggerFactory.getLogger(RedisMomentaryService.class);
protected int validitySeconds = 60 * 5; //default 5 minutes.
RedisConnectionFactory connectionFactory;
public static String PREFIX="MXK_MOMENTARY_";
/**
* @param connectionFactory
*/
public RedisMomentaryService(
RedisConnectionFactory connectionFactory) {
super();
this.connectionFactory = connectionFactory;
}
/**
*
*/
public RedisMomentaryService() {
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
@Override
public void put(String sessionId , String name, Object value){
RedisConnection conn = connectionFactory.getConnection();
conn.setexObject(getSessionKey(sessionId , name), validitySeconds, value);
_logger.trace("key {}, validitySeconds {}, value {}",getSessionKey(sessionId , name),validitySeconds,value);
conn.close();
}
@Override
public Object get(String sessionId , String name) {
RedisConnection conn = connectionFactory.getConnection();
Object value = conn.getObject(getSessionKey(sessionId , name));
_logger.trace("key {}, value {}",getSessionKey(sessionId , name),value);
conn.close();
return value;
}
@Override
public Object remove(String sessionId, String name) {
RedisConnection conn = connectionFactory.getConnection();
Object value = conn.getObject(getSessionKey(sessionId , name));
conn.delete(getSessionKey(sessionId , name));
conn.close();
_logger.trace("key {}, value {}",getSessionKey(sessionId , name),value);
return value;
}
private String getSessionKey(String sessionId , String name) {
return PREFIX + sessionId + name;
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.dromara.maxkey.persistence.cache;

View File

@@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.dromara.maxkey.persistence;

View File

@@ -1,173 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.persistence.redis;
import java.io.Serializable;
import java.util.List;
import org.dromara.maxkey.util.ObjectTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
public class RedisConnection {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class);
Jedis conn ;
RedisConnectionFactory connectionFactory;
Pipeline pipeline ;
public RedisConnection() {
}
public RedisConnection(RedisConnectionFactory connectionFactory) {
this.conn=connectionFactory.open();
this.connectionFactory=connectionFactory;
}
/**
* @param key
* @param value
*/
public void set(String key, String value){
conn.set(key, value);
}
/**
* @param key
* @param value
*/
public void setObject(String key, Object value){
if(value instanceof Serializable) {
set(key, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
public void setexObject(String key,int seconds, Object value){
if(value instanceof Serializable) {
setex(key, seconds, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
/**
* @param key
* @param seconds
* @param value
*/
public void setex(String key,long seconds, String value){
_logger.trace("setex key {} ..." , key);
if(seconds==0){
conn.setex(key, RedisConnectionFactory.DEFAULT_CONFIG.DEFAULT_LIFETIME, value);
}else{
conn.setex(key, seconds, value);
}
_logger.trace("setex successful .");
}
/**
* @param key
* @return String
*/
public String get(String key){
_logger.trace("get key {} ..." , key);
String value = null;
if(key != null){
value = conn.get(key);
}
return value;
}
/**
* @param key
* @return String
*/
public <T> T getObject(String key){
String value = null;
if(key != null){
value = get(key);
if(value!=null){
return ObjectTransformer.deserialize(value);
}
}
return null;
}
public void expire(String key,long seconds){
_logger.trace("expire key {} , {}" , key , seconds);
conn.expire(key, seconds);
}
public void delete(String key){
_logger.trace("del key {}" , key);
conn.del(key);
}
public void rPush(String key, Serializable object){
conn.rpush(key, ObjectTransformer.serialize(object));
}
public long lRem(String key,int count,String value){
return conn.lrem(key, count, value);
}
public List<String> lRange(String key,int start,int end){
return conn.lrange(key, start, end);
}
public void openPipeline(){
this.pipeline=conn.pipelined();
}
public List<Object> closePipeline(){
return pipeline.syncAndReturnAll();
}
/**
* 释放jedis资源
* @param jedis
*/
public void close() {
if (conn != null) {
connectionFactory.close(conn);
}
}
public Jedis getConn() {
return conn;
}
public void setConn(Jedis conn) {
this.conn = conn;
}
public Pipeline getPipeline() {
return pipeline;
}
}

View File

@@ -1,174 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.persistence.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisConnectionFactory {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class);
public static class DEFAULT_CONFIG {
/**
* Redis默认服务器IP
*/
public static String DEFAULT_ADDRESS = "127.0.0.1";
/**
* Redis默认端口号
*/
public static int DEFAULT_PORT = 6379;
/**
* 访问密码
*/
public static String DEFAULT_AUTH = "admin";
/**
* 可用连接实例的最大数目默认值为8<br>
* 如果赋值为-1则表示不限制如果pool已经分配了maxActive个jedis实例则此时pool的状态为exhausted(耗尽)。
**/
public static int DEFAULT_MAX_ACTIVE = 5000;
/**
* 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例默认值也是8。
*/
public static int DEFAULT_MAX_IDLE = 5000;
/**
* 等待可用连接的最大时间,单位毫秒,默认值为-1表示永不超时。如果超过等待时间则直接抛出JedisConnectionException
*/
public static int DEFAULT_MAX_WAIT_MILLIS = 10000;
public static int DEFAULT_TIMEOUT = 10000;
/**
* 在borrow一个jedis实例时是否提前进行validate操作如果为true则得到的jedis实例均是可用的
*/
public static boolean DEFAULT_TEST_ON_BORROW = true;
/**
* 默认过期时间
*/
public static long DEFAULT_LIFETIME = 600;
}
JedisPoolConfig poolConfig;
private JedisPool jedisPool = null;
private String hostName;
private int port;
private String password;
private int timeOut;
public RedisConnectionFactory() {
}
public void initConnectionFactory() {
if (jedisPool == null) {
_logger.debug("init Jedis Pool .");
try {
if (this.hostName == null || hostName.equals("")) {
hostName = DEFAULT_CONFIG.DEFAULT_ADDRESS;
}
if (port == 0) {
port = DEFAULT_CONFIG.DEFAULT_PORT;
}
if (timeOut == 0) {
timeOut = DEFAULT_CONFIG.DEFAULT_TIMEOUT;
}
if (this.password == null || this.password.equals("")) {
this.password = null;
}
jedisPool = new JedisPool(poolConfig, hostName, port, timeOut, password);
_logger.debug("init Jedis Pool successful .");
} catch (Exception e) {
e.printStackTrace();
_logger.error("Exception", e);
}
}
}
public synchronized RedisConnection getConnection() {
initConnectionFactory();
_logger.trace("get connection .");
RedisConnection redisConnection = new RedisConnection(this);
_logger.trace("return connection .");
return redisConnection;
}
public Jedis open() {
_logger.trace("get jedisPool Resource ...");
Jedis jedis = jedisPool.getResource();
_logger.trace("return jedisPool Resource .");
return jedis;
}
public void close(Jedis conn) {
// jedisPool.returnResource(conn);
_logger.trace("close conn .");
conn.close();
_logger.trace("closed conn .");
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public void setPoolConfig(JedisPoolConfig poolConfig) {
this.poolConfig = poolConfig;
}
public JedisPoolConfig getPoolConfig() {
return poolConfig;
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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.
*/
/**
*
*/
/**
* @author redis
*
*/
package org.dromara.maxkey.persistence.redis;

View File

@@ -1,47 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.schedule;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScheduleAdapter {
private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapter.class);
JobExecutionContext context;
protected int jobStatus = JOBSTATUS.STOP;
public static final class JOBSTATUS{
public static final int STOP = 0;
public static final int RUNNING = 1;
public static final int ERROR = 2;
public static final int FINISHED = 3;
}
protected void init(JobExecutionContext context){
this.context = context;
}
@SuppressWarnings("unchecked")
public <T> T getParameter(String name, Class<T> requiredType) {
_logger.trace("requiredType {}",requiredType);
return (T) context.getMergedJobDataMap().get(name);
}
}

View File

@@ -1,115 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.schedule;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScheduleAdapterBuilder {
private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapterBuilder.class);
Scheduler scheduler ;
String cron;
Class <? extends Job> jobClass;
JobDataMap jobDataMap;
String identity ;
public void addListener(
Scheduler scheduler ,
Class <? extends Job> jobClass,
String cronSchedule,
JobDataMap jobDataMap
) throws SchedulerException {
this.cron = cronSchedule;
this.scheduler = scheduler;
this.jobClass = jobClass;
this.jobDataMap = jobDataMap;
this.build();
}
public ScheduleAdapterBuilder setIdentity(String identity) {
this.identity = identity;
return this;
}
public ScheduleAdapterBuilder setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
public ScheduleAdapterBuilder setJobDataMap(JobDataMap jobDataMap) {
this.jobDataMap = jobDataMap;
return this;
}
public ScheduleAdapterBuilder setJobData(String key,Object data) {
if(this.jobDataMap == null) {
jobDataMap = new JobDataMap();
}
this.jobDataMap.put(key, data);
return this;
}
public ScheduleAdapterBuilder setCron(String cron) {
this.cron = cron;
return this;
}
public ScheduleAdapterBuilder setJobClass(Class <? extends Job> jobClass) {
this.jobClass = jobClass;
return this;
}
public void build() throws SchedulerException {
if(StringUtils.isBlank(identity)) {
identity = jobClass.getSimpleName();
}
_logger.debug("Job schedule {} ,Cron {} ", identity ,cron);
JobDetail jobDetail =
JobBuilder.newJob(jobClass)
.withIdentity(identity, identity + "Group")
.build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
CronTrigger cronTrigger =
TriggerBuilder.newTrigger()
.withIdentity("trigger" + identity, identity + "TriggerGroup")
.usingJobData(jobDataMap)
.withSchedule(scheduleBuilder)
.build();
scheduler.scheduleJob(jobDetail,cronTrigger);
}
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.util.Map;
import org.dromara.maxkey.web.tag.FreemarkerTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import jakarta.annotation.PostConstruct;
@Component
public class ConfigurerFreeMarker implements ApplicationContextAware {
private static final Logger _logger = LoggerFactory.getLogger(ConfigurerFreeMarker.class);
ApplicationContext applicationContext ;
@Autowired
Configuration configuration;
@PostConstruct // 在项目启动时执行方法
public void setSharedVariable() throws TemplateException {
// 根据注解FreemarkerTag获取bean ,key is bean name ,value is bean object
Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(FreemarkerTag.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
configuration.setSharedVariable(entry.getKey(), entry.getValue());
_logger.trace("FreeMarker Template {}" , entry.getKey());
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Exception.
*
* @author Crystal.Sea
*
*/
@Controller
public class ExceptionEndpoint {
private static final Logger _logger = LoggerFactory.getLogger(ExceptionEndpoint.class);
@GetMapping({ "/exception/error/400" })
public ModelAndView error400(
HttpServletRequest request, HttpServletResponse response) {
_logger.debug("Exception BAD_REQUEST");
return new ModelAndView("exception/400");
}
/**
* //查看浏览器中的报错信息.
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return
*/
@GetMapping({ "/exception/error/404" })
public ModelAndView error404(
HttpServletRequest request, HttpServletResponse response) {
_logger.debug("Exception PAGE NOT_FOUND ");
return new ModelAndView("exception/404");
}
@GetMapping({ "/exception/error/500" })
public ModelAndView error500(HttpServletRequest request, HttpServletResponse response) {
_logger.debug("Exception INTERNAL_SERVER_ERROR ");
return new ModelAndView("exception/500");
}
@GetMapping({ "/exception/accessdeny" })
public ModelAndView accessdeny(HttpServletRequest request, HttpServletResponse response) {
_logger.debug("exception/accessdeny ");
return new ModelAndView("exception/accessdeny");
}
}

View File

@@ -1,220 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.UnexpectedTypeException;
import org.dromara.maxkey.entity.Message;
import org.dromara.maxkey.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.List;
import java.util.Objects;
/**
* @description:
* @author: orangeBabu
* @time: 16/8/2024 PM3:02
*/
/**
* 全局异常处理器
*
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 缺少请求体异常处理器
* @param e 缺少请求体异常 使用get方式请求 而实体使用@RequestBody修饰
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public Message<Void> parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.error("请求地址'{}',请求体缺失'{}'", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, "缺少请求体");
}
// get请求的对象参数校验异常
@ExceptionHandler({MissingServletRequestParameterException.class})
public Message<Void> bindExceptionHandler(MissingServletRequestParameterException e,HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.error("请求地址'{}',get方式请求参数'{}'必传", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, "请求的对象参数校验异常");
}
/**
* 请求方式不支持
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Message<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.error("请求地址 '{}',不支持'{}' 请求", requestURI, e.getMethod(),e);
return new Message<>(HttpStatus.METHOD_NOT_ALLOWED.value(),HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
}
/**
* 参数不正确
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public Message<Void> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
String error = String.format("%s 应该是 %s 类型", e.getName(), e.getRequiredType().getSimpleName());
logger.error("请求地址'{}',{},参数类型不正确", requestURI,error,e);
return new Message<>(Message.FAIL, "参数类型不正确");
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public Message<Void> handleException(Exception e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.info("Request IpAddress : {} " , WebContext.getRequestIpAddress(request));
if(e instanceof NoHandlerFoundException) {
//NoHandlerFoundException
}else {
logger.error("请求地址'{}',发生系统异常.", requestURI, e);
}
return new Message<>(Message.FAIL, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
/**
* 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(UnexpectedTypeException.class)
public Message<String> unexpectedTypeHandler(UnexpectedTypeException e)
{
logger.error("类型转换错误:{}",e.getMessage(), e);
return new Message<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),e.getMessage());
}
/**
* 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Message<String> methodArgumentNotValidException(MethodArgumentNotValidException e)
{
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
logger.error("参数验证异常:{}",e.getMessage(), e);
if (!errors.isEmpty()) {
// 只显示第一个错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(), errors.get(0).getDefaultMessage());
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"MethodArgumentNotValid");
}
// 运行时异常
@ExceptionHandler(RuntimeException.class)
public Message<String> runtimeExceptionHandler(RuntimeException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.error("请求地址'{}',捕获运行时异常'{}'", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, e.getMessage());
}
// 系统级别异常
@ExceptionHandler(Throwable.class)
public Message<String> throwableExceptionHandler(Throwable e,HttpServletRequest request) {
String requestURI = request.getRequestURI();
logger.error("请求地址'{}',捕获系统级别异常'{}'", requestURI,e.getMessage(),e);
return new Message<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
/**
* IllegalArgumentException 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(IllegalArgumentException.class)
public Message<String> illegalArgumentException(IllegalArgumentException e)
{
String message = e.getMessage();
logger.error("IllegalArgumentException{}",e.getMessage(),e);
if (Objects.nonNull(message)) {
//错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(),message);
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"error");
}
/**
* InvalidFormatException 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(InvalidFormatException.class)
public Message<String> invalidFormatException(InvalidFormatException e)
{
String message = e.getMessage();
logger.error("InvalidFormatException{}",e.getMessage(),e);
if (Objects.nonNull(message)) {
//错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(),message);
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"error");
}
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public Message<Void> handleBindException(BindException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
logger.error("参数验证异常:{}",e.getMessage(), e);
if (!errors.isEmpty()) {
// 只显示第一个错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(), errors.get(0).getDefaultMessage());
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"MethodArgumentNotValid");
}
/**
* 业务异常处理
* 业务自定义code 与 message
*
*/
@ExceptionHandler(BusinessException.class)
public Message<String> handleBusinessException(BusinessException e) {
logger.error("业务自定义异常:{},{}",e.getCode(),e.getMessage(),e);
return new Message<>(e.getCode(),e.getMessage());
}
}

View File

@@ -1,326 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dromara.maxkey.constants.ContentType;
import org.dromara.maxkey.util.AuthorizationHeaderUtils;
import org.dromara.maxkey.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class HttpRequestAdapter {
private static final Logger _logger = LoggerFactory.getLogger(HttpRequestAdapter.class);
private String mediaType = ContentType.APPLICATION_FORM;
HashMap<String,String> headers = new HashMap<String,String>();
public HttpRequestAdapter(){}
public HttpRequestAdapter(String mediaType){
this.mediaType = mediaType;
}
public String post(String url,Map<String, Object> parameterMap) {
setContentType(ContentType.APPLICATION_FORM);
return post(url , parameterMap , headers);
}
public HttpRequestAdapter addHeaderAuthorizationBearer(String token ) {
headers.put("Authorization", AuthorizationHeaderUtils.createBearer(token));
return this;
}
public HttpRequestAdapter addHeaderAuthorizationBasic(String username, String password) {
headers.put("Authorization", AuthorizationHeaderUtils.createBasic(username,password));
return this;
}
public HttpRequestAdapter setContentType(String contentType) {
headers.put("Content-Type", contentType);
return this;
}
public HttpRequestAdapter addHeader(String name , String value ) {
headers.put(name, value);
return this;
}
public String post(String url,Map<String, Object> parameterMap,HashMap<String,String> headers) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
// 创建httpPost远程连接实例
HttpPost httpMethod = new HttpPost(url);
// 配置请求参数实例
setRequestConfig(httpMethod);
// 设置请求头
buildHeader(httpMethod,headers);
// 封装post请求参数
if (null != parameterMap && parameterMap.size() > 0) {
if(mediaType.equals(ContentType.APPLICATION_FORM)) {
// 为httpPost设置封装好的请求参数
try {
httpMethod.setEntity(buildFormEntity(parameterMap));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else if(mediaType.equals(ContentType.APPLICATION_JSON)) {
String jsonString = JsonUtils.gsonToString(parameterMap);
StringEntity stringEntity =new StringEntity(jsonString, "UTF-8");
stringEntity.setContentType(ContentType.APPLICATION_JSON);
httpMethod.setEntity(stringEntity);
}
_logger.trace("Post Message \n{} ", httpMethod.getEntity().toString());
}
try {
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpMethod);
// 从响应对象中获取响应内容
return resolveHttpResponse(httpResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient,httpResponse);// 关闭资源
}
return null;
}
public String post(String url,Object data) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
// 创建httpPost远程连接实例
HttpPost httpMethod = new HttpPost(url);
// 配置请求参数实例
setRequestConfig(httpMethod);
// 设置请求头
buildHeader(httpMethod,headers);
// 封装put请求参数
String jsonString = JsonUtils.gsonToString(data);
StringEntity stringEntity =new StringEntity(jsonString, "UTF-8");
stringEntity.setContentType(ContentType.APPLICATION_JSON);
httpMethod.setEntity(stringEntity);
_logger.debug("Post Message \n{} ", httpMethod.getEntity().toString());
try {
// httpClient对象执行put请求,并返回响应参数对象
httpResponse = httpClient.execute(httpMethod);
// 从响应对象中获取响应内容
return resolveHttpResponse(httpResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient,httpResponse);// 关闭资源
}
return null;
}
public String put(String url,Object data) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
// 创建httpPost远程连接实例
HttpPut httpMethod = new HttpPut(url);
// 配置请求参数实例
setRequestConfig(httpMethod);
// 设置请求头
buildHeader(httpMethod,headers);
// 封装put请求参数
String jsonString = JsonUtils.gsonToString(data);
StringEntity stringEntity =new StringEntity(jsonString, "UTF-8");
stringEntity.setContentType(ContentType.APPLICATION_JSON);
httpMethod.setEntity(stringEntity);
_logger.debug("Put Message \n{} ", httpMethod.getEntity().toString());
try {
// httpClient对象执行put请求,并返回响应参数对象
httpResponse = httpClient.execute(httpMethod);
// 从响应对象中获取响应内容
return resolveHttpResponse(httpResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient,httpResponse);// 关闭资源
}
return null;
}
public String get(String url) {
headers.put("Content-Type", ContentType.APPLICATION_FORM);
return get(url , headers);
}
public String get(String url,HashMap<String,String> headers) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
// 创建httpPost远程连接实例
HttpGet httpMethod = new HttpGet(url);
// 配置请求参数实例
setRequestConfig(httpMethod);
// 设置请求头
buildHeader(httpMethod,headers);
try {
// httpClient对象执行get请求,并返回响应参数对象
httpResponse = httpClient.execute(httpMethod);
// 从响应对象中获取响应内容
return resolveHttpResponse(httpResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient,httpResponse);// 关闭资源
}
return null;
}
public String delete(String url) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
// 创建HttpDelete远程连接实例
HttpDelete httpMethod = new HttpDelete(url);
// 配置请求参数实例
setRequestConfig(httpMethod);
// 设置请求头
buildHeader(httpMethod,headers);
try {
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpMethod);
// 从响应对象中获取响应内容
return resolveHttpResponse(httpResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient,httpResponse);// 关闭资源
}
return null;
}
String resolveHttpResponse(CloseableHttpResponse httpResponse) throws ParseException, IOException {
HttpEntity entity = httpResponse.getEntity();
String content = EntityUtils.toString(entity);
HttpStatus httpStatus = HttpStatus.valueOf(httpResponse.getStatusLine().getStatusCode());
_logger.debug("Http Response HttpStatus {} " , httpStatus);
_logger.trace("Http Response Content {} " , content );
return content;
}
/**
* @param HttpRequest
* @param headers
*/
void buildHeader(HttpRequestBase httpRequest,HashMap<String,String> headers) {
// 设置请求头
if (null != headers && headers.size() > 0) {
Set<Entry<String, String>> entrySet = headers.entrySet();
// 循环遍历,获取迭代器
Iterator<Entry<String, String>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, String> mapEntry = iterator.next();
_logger.trace("Name " + mapEntry.getKey() + " , Value " +mapEntry.getValue());
httpRequest.addHeader(mapEntry.getKey(), mapEntry.getValue());
}
}
}
UrlEncodedFormEntity buildFormEntity(Map<String, Object> parameterMap)
throws UnsupportedEncodingException {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 通过map集成entrySet方法获取entity
Set<Entry<String, Object>> entrySet = parameterMap.entrySet();
// 循环遍历,获取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, Object> mapEntry = iterator.next();
_logger.debug("Name " + mapEntry.getKey() + " , Value " +mapEntry.getValue());
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
// 为httpPost设置封装好的请求参数
return new UrlEncodedFormEntity(nvps, "UTF-8");
}
void setRequestConfig(HttpRequestBase httpMethod){
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
.setSocketTimeout(60000)// 设置读取数据连接超时时间
.build();
// 为httpMethod实例设置配置
httpMethod.setConfig(requestConfig);
}
/**
* 关闭资源
* @param httpClient
* @param httpResponse
*/
void close(CloseableHttpClient httpClient,CloseableHttpResponse httpResponse) {
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -1,72 +0,0 @@
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.io.IOException;
import org.dromara.maxkey.constants.ContentType;
import org.springframework.stereotype.Component;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
@Component
public class HttpResponseAdapter {
public void setContentType(
HttpServletResponse response,
String format) {
if(format == null || format.equalsIgnoreCase("") || format.equalsIgnoreCase(HttpResponseConstants.FORMAT_TYPE.XML)) {
response.setContentType(ContentType.APPLICATION_XML_UTF8);
}else {
response.setContentType(ContentType.APPLICATION_JSON_UTF8);
}
}
public void write(HttpServletResponse response,String content, String format) {
setContentType(response , format);
// Set to expire far in the past.
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
ServletOutputStream out = null;
try {
out = response.getOutputStream();
// write the data out
out.write(content.getBytes());
out.flush();
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
public class HttpResponseConstants {
public static final class FORMAT_TYPE {
/**
* Default XML response.
*/
public static final String XML="xml";
/**
* Render response in JSON.
*/
public static final String JSON="json";
}
}

View File

@@ -1,157 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import org.dromara.maxkey.configuration.ApplicationConfig;
import org.dromara.mybatis.jpa.spring.MybatisJpaContext;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import jakarta.servlet.http.HttpServlet;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Iterator;
/**
* InitApplicationContext .
* @author Crystal.Sea
*
*/
public class InitializeContext extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(InitializeContext.class);
private static final long serialVersionUID = -797399138268601444L;
private static final String LOCALE_RESOLVER_BEAN= "localeResolver";
private static final String COOKIE_LOCALE_RESOLVER_BEAN = "cookieLocaleResolver";
final ApplicationContext applicationContext;
@Override
public void init() {
WebContext.init(applicationContext);
MybatisJpaContext.init(applicationContext);
listProperties();
// List DatabaseMetaData Variables
listDataBaseVariables();
// Show License
showLicense();
}
/**
* InitApplicationContext.
*/
public InitializeContext(ConfigurableApplicationContext applicationContext) {
if(applicationContext.containsBean(LOCALE_RESOLVER_BEAN) &&
applicationContext.containsBean(COOKIE_LOCALE_RESOLVER_BEAN)) {
BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)applicationContext.getBeanFactory();
beanFactory.removeBeanDefinition(LOCALE_RESOLVER_BEAN);
beanFactory.registerBeanDefinition(LOCALE_RESOLVER_BEAN,
beanFactory.getBeanDefinition(COOKIE_LOCALE_RESOLVER_BEAN));
logger.debug("cookieLocaleResolver replaced localeResolver.");
}
this.applicationContext = applicationContext;
}
/**
* listDataBaseVariables.
*/
public void listDataBaseVariables() {
if (!applicationContext.containsBean("dataSource")) {return;}
try {
logger.info(WebConstants.DELIMITER);
logger.info("List DatabaseMetaData Variables ");
Connection connection = ((javax.sql.DataSource) applicationContext.getBean("dataSource")).getConnection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
ApplicationConfig.setDatabaseProduct(databaseMetaData.getDatabaseProductName());
logger.info("DatabaseProductName : {}", databaseMetaData.getDatabaseProductName());
logger.info("DatabaseProductVersion : {}" ,databaseMetaData.getDatabaseProductVersion());
logger.trace("DatabaseMajorVersion : {}" , databaseMetaData.getDatabaseMajorVersion());
logger.trace("DatabaseMinorVersion : {}" ,databaseMetaData.getDatabaseMinorVersion());
logger.trace("supportsTransactions : {}" , databaseMetaData.supportsTransactions());
logger.trace("DefaultTransaction : {}" ,databaseMetaData.getDefaultTransactionIsolation());
logger.trace("MaxConnections : {}" ,databaseMetaData.getMaxConnections());
logger.trace("");
logger.trace("JDBCMajorVersion : {}" ,databaseMetaData.getJDBCMajorVersion());
logger.trace("JDBCMinorVersion : {}" ,databaseMetaData.getJDBCMinorVersion());
logger.trace("DriverName : {}" ,databaseMetaData.getDriverName());
logger.trace("DriverVersion : {}" ,databaseMetaData.getDriverVersion());
logger.info("");
logger.info("DBMS URL : {}" ,databaseMetaData.getURL());
logger.info("UserName : {}" ,databaseMetaData.getUserName());
logger.info(WebConstants.DELIMITER);
} catch (SQLException e) {
logger.error("DatabaseMetaData Variables Error .",e);
}
}
/**
* propertySourcesPlaceholderConfigurer.
*/
public void listProperties() {
if (!applicationContext.containsBean("propertySourcesPlaceholderConfigurer")) {return ;}
logger.trace(WebConstants.DELIMITER);
logger.trace("List Properties Variables ");
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer =
((PropertySourcesPlaceholderConfigurer) applicationContext
.getBean("propertySourcesPlaceholderConfigurer"));
WebContext.initProperties((StandardEnvironment) propertySourcesPlaceholderConfigurer
.getAppliedPropertySources()
.get(PropertySourcesPlaceholderConfigurer.ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME)
.getSource());
Iterator<PropertySource<?>> it =WebContext.properties.getPropertySources().iterator();
while(it.hasNext()) {
logger.debug("propertySource {}" , it.next());
}
logger.trace(WebConstants.DELIMITER);
}
/**
* showLicense.
*/
public void showLicense() {
logger.info(WebConstants.DELIMITER);
logger.info(" MaxKey Community Edition ");
logger.info(" Single Sign On ( SSO ) ");
logger.info(" Version {}",
WebContext.properties.getProperty("application.formatted-version"));
logger.info("");
logger.info(" {}Copyright 2018 - {} https://www.maxkey.top/",
(char)0xA9 , new DateTime().getYear()
);
logger.info("+ Licensed under the Apache License, Version 2.0 ");
logger.info(WebConstants.DELIMITER);
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import org.dromara.maxkey.constants.ContentType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Controller
public class MetadataEndpoint {
@GetMapping(value = "/metadata/version",produces = ContentType.TEXT_PLAIN_UTF8)
@ResponseBody
public String metadata(HttpServletRequest request,HttpServletResponse response) {
return WebContext.version();
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang3.ArchUtils;
import org.apache.commons.lang3.arch.Processor;
import org.dromara.maxkey.util.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProductEnvironment {
private static final Logger logger = LoggerFactory.getLogger(ProductEnvironment.class);
ProductEnvironment(){}
/**
* List Environment Variables.
*/
public static void listEnvVars() {
logger.info(WebConstants.DELIMITER);
logger.info("List Environment Variables ");
Map<String, String> map = System.getenv();
SortedSet<String> keyValueSet = new TreeSet<>();
for (Iterator<String> itr = map.keySet().iterator(); itr.hasNext();) {
String key = itr.next();
keyValueSet.add(key);
}
// out
for (Iterator<String> it = keyValueSet.iterator(); it.hasNext();) {
String key = it.next();
logger.trace("{} = {}" , key , map.get(key));
}
logger.info("APP_HOME" + " = {}" , PathUtils.getInstance().getAppPath());
Processor processor = ArchUtils.getProcessor();
if (Objects.isNull(processor)){
processor = new Processor(Processor.Arch.UNKNOWN, Processor.Type.UNKNOWN);
}
logger.info("OS : {}({} {}), version {}",
SystemUtils.OS_NAME,
SystemUtils.OS_ARCH,
processor.getType(),
SystemUtils.OS_VERSION
);
logger.info("COMPUTER: {}, USERNAME : {}",
map.get("COMPUTERNAME") ,
map.get("USERNAME")
);
logger.info("JAVA :");
logger.info("{} java version {}, class {}",
SystemUtils.JAVA_VENDOR,
SystemUtils.JAVA_VERSION,
SystemUtils.JAVA_CLASS_VERSION
);
logger.info("{} (build {}, {})",
SystemUtils.JAVA_VM_NAME,
SystemUtils.JAVA_VM_VERSION,
SystemUtils.JAVA_VM_INFO
);
logger.info(WebConstants.DELIMITER);
//WARN No Root logger was configured, creating default ERROR-level Root logger with Console appender
System.setProperty("nacos.logging.default.config.enabled", "false");
}
}

View File

@@ -1,96 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.io.IOException;
import org.apache.commons.lang.SystemUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* ProductVersion
* @author Crystal.Sea
*
*/
@Controller
public class ProductVersionEndpoint {
private static final Logger _logger = LoggerFactory.getLogger(ProductVersionEndpoint.class);
static final String VERSION_STRING ="""
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="shortcut icon" type="image/x-icon" href="%s/static/favicon.ico"/>
<base href='%s'/>
<title>MaxKey Single Sign-On</title>
</head>
<body>
<center>
<hr>
Maxkey Community Edition <br>
Single Sign On ( SSO ) <br>
Version %s <br>
<br>
&copy; Copyright 2018 - %d https://www.maxkey.top/<br>
Licensed under the Apache License, Version 2.0 <br>
.&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
All rights reserved
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp.<br>
<hr>
JAVA &nbsp&nbsp : &nbsp&nbsp %s java version %s, class %s<br>
%s (build %s, %s)<br>
<hr>
</center>
</body>
</html>
""";
@GetMapping(value={"/"})
public void version(HttpServletRequest request,HttpServletResponse response) throws IOException {
_logger.debug("ProductVersion /");
ServletOutputStream out = response.getOutputStream();
String contextPath = request.getContextPath();
out.println(
String.format(
VERSION_STRING,
contextPath,
contextPath,
WebContext.getProperty("application.formatted-version"),
new DateTime().getYear(),
SystemUtils.JAVA_VENDOR,
SystemUtils.JAVA_VERSION,
SystemUtils.JAVA_CLASS_VERSION,
SystemUtils.JAVA_VM_NAME,
SystemUtils.JAVA_VM_VERSION,
SystemUtils.JAVA_VM_INFO));
out.close();
}
}

View File

@@ -1,90 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
/**
* Web Application Constants define.
*
* @author Crystal.Sea
*
*/
public class WebConstants {
public static final String CURRENT_USER_PASSWORD_SET_TYPE
= "current_user_password_set_type";
public static final String CURRENT_MESSAGE = "current_message";
public static final String CURRENT_INST = "current_inst";
public static final String INST_COOKIE_NAME = "mxk_inst";
// SPRING_SECURITY_SAVED_REQUEST
public static final String FIRST_SAVED_REQUEST_PARAMETER
= "SPRING_SECURITY_SAVED_REQUEST";
public static final String KAPTCHA_SESSION_KEY = "kaptcha_session_key";
public static final String SINGLE_SIGN_ON_APP_ID = "single_sign_on_app_id";
public static final String AUTHORIZE_SIGN_ON_APP = "authorize_sign_on_app";
public static final String AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER
= "authorize_sign_on_app_samlv20_adapter";
public static final String KERBEROS_TOKEN_PARAMETER = "kerberosToken";
public static final String CAS_SERVICE_PARAMETER = "service";
public static final String KERBEROS_USERDOMAIN_PARAMETER = "kerberosUserDomain";
public static final String REMEBER_ME_COOKIE = "sign_remeber_me";
public static final String JWT_TOKEN_PARAMETER = "jwt";
public static final String CAS_TICKET_PARAMETER = "ticket";
public static final String CURRENT_SINGLESIGNON_URI = "current_singlesignon_uri";
public static final String AUTHENTICATION = "current_authentication";
public static final String SESSION = "current_session";
public static final String THEME_COOKIE_NAME = "mxk_theme_value";
public static final String LOGIN_ERROR_SESSION_MESSAGE
= "login_error_session_message_key";
public static final String ONLINE_TICKET_PREFIX = "OT";
public static final String ONLINE_TICKET_NAME = "online_ticket";
public static final String MXK_METADATA_PREFIX = "mxk_metadata_";
public static final class LOGIN_RESULT{
public static final String SUCCESS = "success";
public static final String FAIL = "fail";
public static final String PASSWORD_ERROE = "password error";
public static final String USER_NOT_EXIST = "user not exist";
public static final String USER_LOCKED = "locked";
public static final String USER_INACTIVE = "inactive";
}
public static final String DELIMITER = "-----------------------------------------------------------";
}

View File

@@ -1,555 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.logging.LogFactory;
import org.dromara.maxkey.configuration.ApplicationConfig;
import org.dromara.maxkey.entity.Institutions;
import org.dromara.maxkey.util.DateUtils;
import org.dromara.maxkey.util.IdGenerator;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* Application is common class for Web Application Context.
*
* @author Crystal.Sea
* @since 1.5
*/
/**
* @author shimi
*
*/
public final class WebContext {
static final Logger _logger = LoggerFactory.getLogger(WebContext.class);
public static StandardEnvironment properties;
public static ApplicationContext applicationContext;
public static final String ipAddressRegex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
public static ArrayList<String> sessionAttributeNameList = new ArrayList<String>();
public static ArrayList<String> logoutAttributeNameList = new ArrayList<String>();
public static IdGenerator idGenerator;
static {
sessionAttributeNameList.add(WebConstants.AUTHENTICATION);
sessionAttributeNameList.add(WebConstants.AUTHORIZE_SIGN_ON_APP);
sessionAttributeNameList.add(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER);
sessionAttributeNameList.add(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE);
sessionAttributeNameList.add(WebConstants.CURRENT_INST);
sessionAttributeNameList.add(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
//logout
logoutAttributeNameList.add(WebConstants.AUTHENTICATION);
logoutAttributeNameList.add(WebConstants.AUTHORIZE_SIGN_ON_APP);
logoutAttributeNameList.add(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER);
logoutAttributeNameList.add(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE);
logoutAttributeNameList.add(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
}
public static void init(ApplicationContext context) {
applicationContext = context;
}
public static void initProperties(StandardEnvironment standardEnvironment) {
properties = standardEnvironment;
}
/**
* clear session Message ,session id is Constants.MESSAGE
*
* @see WebConstants.MESSAGE
*/
public static void clearMessage() {
removeAttribute(WebConstants.CURRENT_MESSAGE);
}
/**
* get ApplicationContext from web ServletContext configuration
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext(){
return WebApplicationContextUtils.getWebApplicationContext(getSession().getServletContext());
}
/**
* get bean from spring configuration by bean id
* @param id
* @return Object
*/
public static Object getBean(String name){
if(applicationContext == null) {
return getApplicationContext().getBean(name);
}else {
return applicationContext.getBean(name);
}
}
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException{
if(applicationContext==null) {
return getApplicationContext().getBean(name,requiredType);
}else {
return applicationContext.getBean(name,requiredType);
}
}
public static String getProperty(String key) {
return properties.getProperty(key);
}
public static String getServerPort() {
return getProperty("server.port");
}
// below method is common HttpServlet method
/**
* get Spring HttpServletRequest.
*
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
/**
* get Http Context full Path.
*
* @return String HttpContextPath
*/
public static String getContextPath(boolean isContextPath) {
HttpServletRequest httpServletRequest = WebContext.getRequest();
return getContextPath(httpServletRequest,isContextPath);
}
/**
* get Http Context full Path,if port equals 80 or 443 is omitted.
*
* @return String eg:http://192.168.1.20:9080/webcontext or
* http://www.website.com/webcontext
*/
public static String getContextPath(HttpServletRequest request,boolean isContextPath) {
String fullRequestUrl = UrlUtils.buildFullRequestUrl(request);
StringBuilder url = new StringBuilder(fullRequestUrl.substring(0, fullRequestUrl.indexOf(request.getContextPath())));
if(isContextPath) {
url.append(request.getContextPath());
}
_logger.trace("http ContextPath {}" , url);
return url.toString();
}
/**
* isTraceEnabled print request headers and parameters<br>
* see WebInstRequestFilter
* @param request
*/
public static void printRequest(final HttpServletRequest request) {
_logger.info("getContextPath : {}" , request.getContextPath());
_logger.info("getRequestURL : {} " , request.getRequestURL());
_logger.info("URL : {}" , request.getRequestURI().substring(request.getContextPath().length()));
_logger.info("getMethod : {} " , request.getMethod());
_logger.info("Request IpAddress : {} " , getRequestIpAddress(request));
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = headerNames.nextElement();
String value = request.getHeader(key);
_logger.info("Header key {} , value {}" , key, value);
}
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = parameterNames.nextElement();
String value = request.getParameter(key);
_logger.info("Parameter {} , value {}",key , value);
}
}
/**
* get current Session.
*
* @return HttpSession
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
/**
* get current Session,if no session ,new Session created.
*
* @return HttpSession
*/
public static HttpSession getSession(boolean create) {
_logger.info("new Session created");
return getRequest().getSession(create);
}
/**
* set Attribute to session ,Attribute name is name,value is value.
*
* @param name String
* @param value String
*/
public static void setAttribute(String name, Object value) {
getSession().setAttribute(name, value);
}
/**
* get Attribute from session by name.
*
* @param name String
* @return
*/
public static Object getAttribute(String name) {
return getSession().getAttribute(name);
}
/**
* remove Attribute from session by name.
*
* @param name String
*/
public static void removeAttribute(String name) {
getSession().removeAttribute(name);
}
/**
* get Request Parameter by name.
*
* @param name String
* @return String
*/
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
public static Institutions getInst() {
return (Institutions)getAttribute(WebConstants.CURRENT_INST);
}
/**
* encoding encodingString by ApplicationConfig.
*
* @param encodingString String
* @return encoded String
*/
public static String encoding(String encodingString) {
ApplicationConfig applicationConfig = getBean("applicationConfig",ApplicationConfig.class);
return applicationConfig.getCharacterEncodingConfig().encoding(encodingString);
}
/**
* get locale from Spring Resolver,if locale is null,get locale from Spring.
* SessionLocaleResolver this is from internationalization
*
* @return Locale
*/
public static Locale getLocale() {
Locale locale = null;
try {
CookieLocaleResolver cookieLocaleResolver =
getBean("localeResolver",CookieLocaleResolver.class);
locale = cookieLocaleResolver.resolveLocale(getRequest());
} catch (Exception e) {
LogFactory.getLog(WebContext.class).debug("getLocale() error . ");
e.printStackTrace();
locale = RequestContextUtils.getLocale(getRequest());
}
return locale;
}
public static Map<String, String> getRequestParameterMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<>();
Map<String, String[]> parameters = request.getParameterMap();
for (String key : parameters.keySet()) {
String[] values = parameters.get(key);
map.put(key, values != null && values.length > 0 ? values[0] : null);
}
return map;
}
/**
* 根据名字获取cookie.
*
* @param request HttpServletRequest
* @param name cookie名字
* @return Cookie
*/
public static Cookie getCookie(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = getCookieAll(request);
if (cookieMap.containsKey(name)) {
return cookieMap.get(name);
} else {
return null;
}
}
/**
* 将cookie封装到Map里面.
*
* @param request HttpServletRequest
* @return Map
*/
private static Map<String, Cookie> getCookieAll(HttpServletRequest request) {
Map<String, Cookie> cookieMap = new HashMap<>();
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
/**
* 保存Cookies.
*
* @param response response响应
* @param name cookie的名字
* @param value cookie的值
* @param time cookie的存在时间
*/
public static HttpServletResponse setCookie(
HttpServletResponse response, String domain ,String name, String value, int time) {
// new一个Cookie对象,键值对为参数
Cookie cookie = new Cookie(name, value);
// tomcat下多应用共享
cookie.setPath("/");
if(domain != null) {
cookie.setDomain(domain);
}
// 如果cookie的值中含有中文时需要对cookie进行编码不然会产生乱码
try {
URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 单位:秒
if(time >= 0) {
cookie.setMaxAge(time);
}
// 将Cookie添加到Response中,使之生效
response.addCookie(cookie); // addCookie后如果已经存在相同名字的cookie则最新的覆盖旧的cookie
return response;
}
public static HttpServletResponse expiryCookie(
HttpServletResponse response, String domain ,String name, String value) {
WebContext.setCookie(response,domain,name, value,0);
return response;
}
public static HttpServletResponse setCookie(
HttpServletResponse response, String domain ,String name, String value) {
WebContext.setCookie(response,domain,name, value,-1);
return response;
}
/**
* get Current Date,eg 2012-07-10.
*
* @return String
*/
public static String getCurrentDate() {
return DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_YYYY_MM_DD);
}
/**
* get System Menu RootId,root id is constant.
*
* @return String
*/
public static String getSystemNavRootId() {
return "100000000000";
}
/**
* get Request IpAddress,for current Request.
*
* @return String,100.167.216.100
*/
public static final String getRequestIpAddress() {
return getRequestIpAddress(getRequest());
}
/**
* get Request IpAddress by request.
*
* @param request HttpServletRequest
* @return String
*/
public static final String getRequestIpAddress(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
LogFactory.getLog(WebContext.class).trace(
"getRequestIpAddress() RequestIpAddress:" + ipAddress);
return ipAddress;
}
/**
* captchaValid.
* @param captcha String
* @return
*/
public static boolean captchaValid(String captcha) {
return (captcha != null &&
captcha.equals(WebContext.getSession().getAttribute(
WebConstants.KAPTCHA_SESSION_KEY).toString()));
}
/**
* getI18nValue.
* @param code String
* @return
*/
public static String getI18nValue(String code) {
String message = code;
try {
message = getApplicationContext().getMessage(
code.toString(),
null,
getLocale());
} catch (Exception e) {
//
e.printStackTrace();
}
return message;
}
/**
* getI18nValue.
* @param code String
* @param filedValues Object
* @return
*/
public static String getI18nValue(String code, Object[] filedValues) {
String message = code;
try {
message = getApplicationContext().getMessage(
code,
filedValues,
getLocale());
} catch (Exception e) {
//
e.printStackTrace();
}
return message;
}
/**
* getRequestLocale.
* @return
*/
public static String getRequestLocale() {
return "";
}
/**
* generate random Universally Unique Identifier,delete -.
*
* @return String
*/
public static String genId() {
if(idGenerator == null) {
idGenerator = new IdGenerator();
}
return idGenerator.generate();
}
public static void setIdGenerator(IdGenerator idGenerator) {
WebContext.idGenerator = idGenerator;
}
public static ModelAndView redirect(String redirectUrl) {
return new ModelAndView("redirect:" + redirectUrl);
}
public static ModelAndView forward(String forwardUrl) {
return new ModelAndView("forward:" + forwardUrl);
}
public static String version() {
StringBuffer version = new StringBuffer();
version.append("-----------------------------------------------------------");
version.append("+ MaxKey Community Edition ");
version.append("+ Single Sign On ( SSO ) ");
version.append("+ Version %s".formatted(
WebContext.properties.getProperty("application.formatted-version")));
version.append("+");
version.append("+ {}Copyright 2018 - {} https://www.maxkey.top/",
(char)0xA9 , new DateTime().getYear()
);
version.append("+ . All rights reserved . ");
version.append("-----------------------------------------------------------");
return version.toString();
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web.tag;
import java.io.IOException;
import java.util.Map;
import org.dromara.maxkey.web.WebContext;
import org.springframework.beans.factory.annotation.Autowired;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import jakarta.servlet.http.HttpServletRequest;
/**
* <@basePath/>
* 获取请求地址及应用上下文标签
* @author Crystal.Sea
*
*/
@FreemarkerTag("basePath")
public class BasePathTagDirective implements TemplateDirectiveModel {
@Autowired
private HttpServletRequest request;
@Override
@SuppressWarnings("rawtypes")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
env.getOut().append(WebContext.getContextPath(request,true));
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web.tag;
import java.io.IOException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import jakarta.servlet.http.HttpServletRequest;
/**
* 获取应用上下文标签
* <@base/>
* @author Crystal.Sea
*
*/
@FreemarkerTag("base")
public class BaseTagDirective implements TemplateDirectiveModel {
@Autowired
private HttpServletRequest request;
@Override
@SuppressWarnings("rawtypes")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
//String url = params.get(URL).toString();
String base=request.getContextPath();
env.getOut().append(base);
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web.tag;
import java.io.IOException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import jakarta.servlet.http.HttpServletRequest;
/**
* 获取应用上下文标签
* <@browser name=""></@browser>
* @author Crystal.Sea
*
*/
@FreemarkerTag("browser")
public class BrowserTagDirective implements TemplateDirectiveModel {
@Autowired
private HttpServletRequest request;
@Override
@SuppressWarnings("rawtypes")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
String browser = params.get("name").toString();
String userAgent = request.getHeader("User-Agent");
env.getOut().append("<!--<div style='display:none'>"+userAgent+"</div>-->");
if(userAgent.indexOf(browser)>0){
body.render(env.getOut());
}
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web.tag;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface FreemarkerTag {
String value() default "";
}

View File

@@ -1,91 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.dromara.maxkey.web.tag;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import org.dromara.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* 获取应用上下文标签 .<@locale/>
*
* @author Crystal.Sea
*
*/
@FreemarkerTag("locale")
public class LocaleTagDirective implements TemplateDirectiveModel {
private static final Logger _logger = LoggerFactory.getLogger(LocaleTagDirective.class);
@Autowired
private HttpServletRequest request;
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env,
Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
WebApplicationContext webApplicationContext =
RequestContextUtils.findWebApplicationContext(request);
String message = "";
String code = params.get("code") == null? null : params.get("code").toString();
String htmlTag = params.get("htmltag")==null ? null : params.get("htmltag").toString();
_logger.trace("message code {} , htmltag {}" , code , htmlTag);
if (code == null) {
message = RequestContextUtils.getLocale(request).getLanguage();
} else if (code.equals("global.application.version")
|| code.equals("application.version")) {
message = WebContext.properties.getProperty("application.formatted-version");
} else if (code.equals("global.logo")) {
if(!message.startsWith("http")) {
message = request.getContextPath() + message;
}
}else if (code.equals("global.title")
||code.equals("global.consoleTitle")) {
} else {
try {
message = webApplicationContext.getMessage(
code,
null,
RequestContextUtils.getLocale(request));
} catch (Exception e) {
_logger.error("message code " + code, e);
}
}
env.getOut().append(message);
}
}