Merge remote-tracking branch 'origin/master' into feature/crm
# Conflicts: # yudao-module-crm/yudao-module-crm-biz/src/test/java/cn/iocoder/yudao/module/crm/service/contract/ContractServiceImplTest.java # yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.javaplp
commit
73e76ab453
@ -0,0 +1,598 @@
|
||||
package liquibase.database.core;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import liquibase.CatalogAndSchema;
|
||||
import liquibase.Scope;
|
||||
import liquibase.database.AbstractJdbcDatabase;
|
||||
import liquibase.database.DatabaseConnection;
|
||||
import liquibase.database.OfflineConnection;
|
||||
import liquibase.database.jvm.JdbcConnection;
|
||||
import liquibase.exception.DatabaseException;
|
||||
import liquibase.exception.UnexpectedLiquibaseException;
|
||||
import liquibase.exception.ValidationErrors;
|
||||
import liquibase.executor.ExecutorService;
|
||||
import liquibase.statement.DatabaseFunction;
|
||||
import liquibase.statement.SequenceCurrentValueFunction;
|
||||
import liquibase.statement.SequenceNextValueFunction;
|
||||
import liquibase.statement.core.RawCallStatement;
|
||||
import liquibase.statement.core.RawSqlStatement;
|
||||
import liquibase.structure.DatabaseObject;
|
||||
import liquibase.structure.core.Catalog;
|
||||
import liquibase.structure.core.Index;
|
||||
import liquibase.structure.core.PrimaryKey;
|
||||
import liquibase.structure.core.Schema;
|
||||
import liquibase.util.JdbcUtils;
|
||||
import liquibase.util.StringUtil;
|
||||
|
||||
public class DmDatabase extends AbstractJdbcDatabase {
|
||||
private static final String PRODUCT_NAME = "DM DBMS";
|
||||
|
||||
@Override
|
||||
protected String getDefaultDatabaseProductName() {
|
||||
return PRODUCT_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this AbstractDatabase subclass the correct one to use for the given connection.
|
||||
*
|
||||
* @param conn
|
||||
*/
|
||||
@Override
|
||||
public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException {
|
||||
return PRODUCT_NAME.equalsIgnoreCase(conn.getDatabaseProductName());
|
||||
}
|
||||
|
||||
/**
|
||||
* If this database understands the given url, return the default driver class name. Otherwise return null.
|
||||
*
|
||||
* @param url
|
||||
*/
|
||||
@Override
|
||||
public String getDefaultDriver(String url) {
|
||||
if(url.startsWith("jdbc:dm")) {
|
||||
return "dm.jdbc.driver.DmDriver";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an all-lower-case short name of the product. Used for end-user selecting of database type
|
||||
* such as the DBMS precondition.
|
||||
*/
|
||||
@Override
|
||||
public String getShortName() {
|
||||
return "dm";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getDefaultPort() {
|
||||
return 5236;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this database support initially deferrable columns.
|
||||
*/
|
||||
@Override
|
||||
public boolean supportsInitiallyDeferrableColumns() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsTablespaces() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return PRIORITY_DEFAULT;
|
||||
}
|
||||
|
||||
private static final Pattern PROXY_USER = Pattern.compile(".*(?:thin|oci)\\:(.+)/@.*");
|
||||
|
||||
protected final int SHORT_IDENTIFIERS_LENGTH = 30;
|
||||
protected final int LONG_IDENTIFIERS_LEGNTH = 128;
|
||||
public static final int ORACLE_12C_MAJOR_VERSION = 12;
|
||||
|
||||
private Set<String> reservedWords = new HashSet<>();
|
||||
private Set<String> userDefinedTypes;
|
||||
private Map<String, String> savedSessionNlsSettings;
|
||||
|
||||
private Boolean canAccessDbaRecycleBin;
|
||||
private Integer databaseMajorVersion;
|
||||
private Integer databaseMinorVersion;
|
||||
|
||||
/**
|
||||
* Default constructor for an object that represents the Oracle Database DBMS.
|
||||
*/
|
||||
public DmDatabase() {
|
||||
super.unquotedObjectsAreUppercased = true;
|
||||
//noinspection HardCodedStringLiteral
|
||||
super.setCurrentDateTimeFunction("SYSTIMESTAMP");
|
||||
// Setting list of Oracle's native functions
|
||||
//noinspection HardCodedStringLiteral
|
||||
dateFunctions.add(new DatabaseFunction("SYSDATE"));
|
||||
//noinspection HardCodedStringLiteral
|
||||
dateFunctions.add(new DatabaseFunction("SYSTIMESTAMP"));
|
||||
//noinspection HardCodedStringLiteral
|
||||
dateFunctions.add(new DatabaseFunction("CURRENT_TIMESTAMP"));
|
||||
//noinspection HardCodedStringLiteral
|
||||
super.sequenceNextValueFunction = "%s.nextval";
|
||||
//noinspection HardCodedStringLiteral
|
||||
super.sequenceCurrentValueFunction = "%s.currval";
|
||||
}
|
||||
|
||||
private void tryProxySession(final String url, final Connection con) {
|
||||
Matcher m = PROXY_USER.matcher(url);
|
||||
if (m.matches()) {
|
||||
Properties props = new Properties();
|
||||
props.put("PROXY_USER_NAME", m.group(1));
|
||||
try {
|
||||
Method method = con.getClass().getMethod("openProxySession", int.class, Properties.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(con, 1, props);
|
||||
} catch (Exception e) {
|
||||
Scope.getCurrentScope().getLog(getClass()).info("Could not open proxy session on OracleDatabase: " + e.getCause().getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDatabaseMajorVersion() throws DatabaseException {
|
||||
if (databaseMajorVersion == null) {
|
||||
return super.getDatabaseMajorVersion();
|
||||
} else {
|
||||
return databaseMajorVersion;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDatabaseMinorVersion() throws DatabaseException {
|
||||
if (databaseMinorVersion == null) {
|
||||
return super.getDatabaseMinorVersion();
|
||||
} else {
|
||||
return databaseMinorVersion;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJdbcCatalogName(CatalogAndSchema schema) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJdbcSchemaName(CatalogAndSchema schema) {
|
||||
return correctObjectName((schema.getCatalogName() == null) ? schema.getSchemaName() : schema.getCatalogName(), Schema.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getAutoIncrementClause(final String generationType, final Boolean defaultOnNull) {
|
||||
if (StringUtil.isEmpty(generationType)) {
|
||||
return super.getAutoIncrementClause();
|
||||
}
|
||||
|
||||
String autoIncrementClause = "GENERATED %s AS IDENTITY"; // %s -- [ ALWAYS | BY DEFAULT [ ON NULL ] ]
|
||||
String generationStrategy = generationType;
|
||||
if (Boolean.TRUE.equals(defaultOnNull) && generationType.toUpperCase().equals("BY DEFAULT")) {
|
||||
generationStrategy += " ON NULL";
|
||||
}
|
||||
return String.format(autoIncrementClause, generationStrategy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generatePrimaryKeyName(String tableName) {
|
||||
if (tableName.length() > 27) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
return "PK_" + tableName.toUpperCase(Locale.US).substring(0, 27);
|
||||
} else {
|
||||
//noinspection HardCodedStringLiteral
|
||||
return "PK_" + tableName.toUpperCase(Locale.US);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReservedWord(String objectName) {
|
||||
return reservedWords.contains(objectName.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSequences() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Oracle supports catalogs in liquibase terms
|
||||
*
|
||||
* @return false
|
||||
*/
|
||||
@Override
|
||||
public boolean supportsSchemas() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getConnectionCatalogName() throws DatabaseException {
|
||||
if (getConnection() instanceof OfflineConnection) {
|
||||
return getConnection().getCatalog();
|
||||
}
|
||||
try {
|
||||
//noinspection HardCodedStringLiteral
|
||||
return Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).queryForObject(new RawCallStatement("select sys_context( 'userenv', 'current_schema' ) from dual"), String.class);
|
||||
} catch (Exception e) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
Scope.getCurrentScope().getLog(getClass()).info("Error getting default schema", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDefaultCatalogName() {//NOPMD
|
||||
return (super.getDefaultCatalogName() == null) ? null : super.getDefaultCatalogName().toUpperCase(Locale.US);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Returns an Oracle date literal with the same value as a string formatted using ISO 8601.</p>
|
||||
*
|
||||
* <p>Convert an ISO8601 date string to one of the following results:
|
||||
* to_date('1995-05-23', 'YYYY-MM-DD')
|
||||
* to_date('1995-05-23 09:23:59', 'YYYY-MM-DD HH24:MI:SS')</p>
|
||||
* <p>
|
||||
* Implementation restriction:<br>
|
||||
* Currently, only the following subsets of ISO8601 are supported:<br>
|
||||
* <ul>
|
||||
* <li>YYYY-MM-DD</li>
|
||||
* <li>YYYY-MM-DDThh:mm:ss</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Override
|
||||
public String getDateLiteral(String isoDate) {
|
||||
String normalLiteral = super.getDateLiteral(isoDate);
|
||||
|
||||
if (isDateOnly(isoDate)) {
|
||||
return "TO_DATE(" + normalLiteral + ", 'YYYY-MM-DD')";
|
||||
} else if (isTimeOnly(isoDate)) {
|
||||
return "TO_DATE(" + normalLiteral + ", 'HH24:MI:SS')";
|
||||
} else if (isTimestamp(isoDate)) {
|
||||
return "TO_TIMESTAMP(" + normalLiteral + ", 'YYYY-MM-DD HH24:MI:SS.FF')";
|
||||
} else if (isDateTime(isoDate)) {
|
||||
int seppos = normalLiteral.lastIndexOf('.');
|
||||
if (seppos != -1) {
|
||||
normalLiteral = normalLiteral.substring(0, seppos) + "'";
|
||||
}
|
||||
return "TO_DATE(" + normalLiteral + ", 'YYYY-MM-DD HH24:MI:SS')";
|
||||
}
|
||||
return "UNSUPPORTED:" + isoDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSystemObject(DatabaseObject example) {
|
||||
if (example == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.isLiquibaseObject(example)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (example instanceof Schema) {
|
||||
//noinspection HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral
|
||||
if ("SYSTEM".equals(example.getName()) || "SYS".equals(example.getName()) || "CTXSYS".equals(example.getName()) || "XDB".equals(example.getName())) {
|
||||
return true;
|
||||
}
|
||||
//noinspection HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral
|
||||
if ("SYSTEM".equals(example.getSchema().getCatalogName()) || "SYS".equals(example.getSchema().getCatalogName()) || "CTXSYS".equals(example.getSchema().getCatalogName()) || "XDB".equals(example.getSchema().getCatalogName())) {
|
||||
return true;
|
||||
}
|
||||
} else if (isSystemObject(example.getSchema())) {
|
||||
return true;
|
||||
}
|
||||
if (example instanceof Catalog) {
|
||||
//noinspection HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral
|
||||
if (("SYSTEM".equals(example.getName()) || "SYS".equals(example.getName()) || "CTXSYS".equals(example.getName()) || "XDB".equals(example.getName()))) {
|
||||
return true;
|
||||
}
|
||||
} else if (example.getName() != null) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("BIN$")) { //oracle deleted table
|
||||
boolean filteredInOriginalQuery = this.canAccessDbaRecycleBin();
|
||||
if (!filteredInOriginalQuery) {
|
||||
filteredInOriginalQuery = StringUtil.trimToEmpty(example.getSchema().getName()).equalsIgnoreCase(this.getConnection().getConnectionUserName());
|
||||
}
|
||||
|
||||
if (filteredInOriginalQuery) {
|
||||
return !((example instanceof PrimaryKey) || (example instanceof Index) || (example instanceof
|
||||
liquibase.statement.UniqueConstraint));
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("AQ$")) { //oracle AQ tables
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("DR$")) { //oracle index tables
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("SYS_IOT_OVER")) { //oracle system table
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral,HardCodedStringLiteral
|
||||
if ((example.getName().startsWith("MDRT_") || example.getName().startsWith("MDRS_")) && example.getName().endsWith("$")) {
|
||||
// CORE-1768 - Oracle creates these for spatial indices and will remove them when the index is removed.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("MLOG$_")) { //Created by materliaized view logs for every table that is part of a materialized view. Not available for DDL operations.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("RUPD$_")) { //Created by materialized view log tables using primary keys. Not available for DDL operations.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("WM$_")) { //Workspace Manager backup tables.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if ("CREATE$JAVA$LOB$TABLE".equals(example.getName())) { //This table contains the name of the Java object, the date it was loaded, and has a BLOB column to store the Java object.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if ("JAVA$CLASS$MD5$TABLE".equals(example.getName())) { //This is a hash table that tracks the loading of Java objects into a schema.
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("ISEQ$$_")) { //System-generated sequence
|
||||
return true;
|
||||
} else //noinspection HardCodedStringLiteral
|
||||
if (example.getName().startsWith("USLOG$")) { //for update materialized view
|
||||
return true;
|
||||
} else if (example.getName().startsWith("SYS_FBA")) { //for Flashback tables
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return super.isSystemObject(example);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsAutoIncrement() {
|
||||
// Oracle supports Identity beginning with version 12c
|
||||
boolean isAutoIncrementSupported = false;
|
||||
|
||||
try {
|
||||
if (getDatabaseMajorVersion() >= 12) {
|
||||
isAutoIncrementSupported = true;
|
||||
}
|
||||
|
||||
// Returning true will generate create table command with 'IDENTITY' clause, example:
|
||||
// CREATE TABLE AutoIncTest (IDPrimaryKey NUMBER(19) GENERATED BY DEFAULT AS IDENTITY NOT NULL, TypeID NUMBER(3) NOT NULL, Description NVARCHAR2(50), CONSTRAINT PK_AutoIncTest PRIMARY KEY (IDPrimaryKey));
|
||||
|
||||
// While returning false will continue to generate create table command without 'IDENTITY' clause, example:
|
||||
// CREATE TABLE AutoIncTest (IDPrimaryKey NUMBER(19) NOT NULL, TypeID NUMBER(3) NOT NULL, Description NVARCHAR2(50), CONSTRAINT PK_AutoIncTest PRIMARY KEY (IDPrimaryKey));
|
||||
|
||||
} catch (DatabaseException ex) {
|
||||
isAutoIncrementSupported = false;
|
||||
}
|
||||
|
||||
return isAutoIncrementSupported;
|
||||
}
|
||||
|
||||
|
||||
// public Set<UniqueConstraint> findUniqueConstraints(String schema) throws DatabaseException {
|
||||
// Set<UniqueConstraint> returnSet = new HashSet<UniqueConstraint>();
|
||||
//
|
||||
// List<Map> maps = new Executor(this).queryForList(new RawSqlStatement("SELECT UC.CONSTRAINT_NAME, UCC.TABLE_NAME, UCC.COLUMN_NAME FROM USER_CONSTRAINTS UC, USER_CONS_COLUMNS UCC WHERE UC.CONSTRAINT_NAME=UCC.CONSTRAINT_NAME AND CONSTRAINT_TYPE='U' ORDER BY UC.CONSTRAINT_NAME"));
|
||||
//
|
||||
// UniqueConstraint constraint = null;
|
||||
// for (Map map : maps) {
|
||||
// if (constraint == null || !constraint.getName().equals(constraint.getName())) {
|
||||
// returnSet.add(constraint);
|
||||
// Table table = new Table((String) map.get("TABLE_NAME"));
|
||||
// constraint = new UniqueConstraint(map.get("CONSTRAINT_NAME").toString(), table);
|
||||
// }
|
||||
// }
|
||||
// if (constraint != null) {
|
||||
// returnSet.add(constraint);
|
||||
// }
|
||||
//
|
||||
// return returnSet;
|
||||
// }
|
||||
|
||||
@Override
|
||||
public boolean supportsRestrictForeignKeys() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDataTypeMaxParameters(String dataTypeName) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
if ("BINARY_FLOAT".equals(dataTypeName.toUpperCase())) {
|
||||
return 0;
|
||||
}
|
||||
//noinspection HardCodedStringLiteral
|
||||
if ("BINARY_DOUBLE".equals(dataTypeName.toUpperCase())) {
|
||||
return 0;
|
||||
}
|
||||
return super.getDataTypeMaxParameters(dataTypeName);
|
||||
}
|
||||
|
||||
public String getSystemTableWhereClause(String tableNameColumn) {
|
||||
List<String> clauses = new ArrayList<String>(Arrays.asList("BIN$",
|
||||
"AQ$",
|
||||
"DR$",
|
||||
"SYS_IOT_OVER",
|
||||
"MLOG$_",
|
||||
"RUPD$_",
|
||||
"WM$_",
|
||||
"ISEQ$$_",
|
||||
"USLOG$",
|
||||
"SYS_FBA"));
|
||||
|
||||
for (int i = 0;i<clauses.size(); i++) {
|
||||
clauses.set(i, tableNameColumn+" NOT LIKE '"+clauses.get(i)+"%'");
|
||||
}
|
||||
return "("+ StringUtil.join(clauses, " AND ") + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean jdbcCallsCatalogsSchemas() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public Set<String> getUserDefinedTypes() {
|
||||
if (userDefinedTypes == null) {
|
||||
userDefinedTypes = new HashSet<>();
|
||||
if ((getConnection() != null) && !(getConnection() instanceof OfflineConnection)) {
|
||||
try {
|
||||
try {
|
||||
//noinspection HardCodedStringLiteral
|
||||
userDefinedTypes.addAll(Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).queryForList(new RawSqlStatement("SELECT DISTINCT TYPE_NAME FROM ALL_TYPES"), String.class));
|
||||
} catch (DatabaseException e) { //fall back to USER_TYPES if the user cannot see ALL_TYPES
|
||||
//noinspection HardCodedStringLiteral
|
||||
userDefinedTypes.addAll(Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).queryForList(new RawSqlStatement("SELECT TYPE_NAME FROM USER_TYPES"), String.class));
|
||||
}
|
||||
} catch (DatabaseException e) {
|
||||
//ignore error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return userDefinedTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateDatabaseFunctionValue(DatabaseFunction databaseFunction) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
if ((databaseFunction != null) && "current_timestamp".equalsIgnoreCase(databaseFunction.toString())) {
|
||||
return databaseFunction.toString();
|
||||
}
|
||||
if ((databaseFunction instanceof SequenceNextValueFunction) || (databaseFunction instanceof
|
||||
SequenceCurrentValueFunction)) {
|
||||
String quotedSeq = super.generateDatabaseFunctionValue(databaseFunction);
|
||||
// replace "myschema.my_seq".nextval with "myschema"."my_seq".nextval
|
||||
return quotedSeq.replaceFirst("\"([^\\.\"]+)\\.([^\\.\"]+)\"", "\"$1\".\"$2\"");
|
||||
|
||||
}
|
||||
|
||||
return super.generateDatabaseFunctionValue(databaseFunction);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValidationErrors validate() {
|
||||
ValidationErrors errors = super.validate();
|
||||
DatabaseConnection connection = getConnection();
|
||||
if ((connection == null) || (connection instanceof OfflineConnection)) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
Scope.getCurrentScope().getLog(getClass()).info("Cannot validate offline database");
|
||||
return errors;
|
||||
}
|
||||
|
||||
if (!canAccessDbaRecycleBin()) {
|
||||
errors.addWarning(getDbaRecycleBinWarning());
|
||||
}
|
||||
|
||||
return errors;
|
||||
|
||||
}
|
||||
|
||||
public String getDbaRecycleBinWarning() {
|
||||
//noinspection HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral,
|
||||
// HardCodedStringLiteral
|
||||
//noinspection HardCodedStringLiteral,HardCodedStringLiteral,HardCodedStringLiteral
|
||||
return "Liquibase needs to access the DBA_RECYCLEBIN table so we can automatically handle the case where " +
|
||||
"constraints are deleted and restored. Since Oracle doesn't properly restore the original table names " +
|
||||
"referenced in the constraint, we use the information from the DBA_RECYCLEBIN to automatically correct this" +
|
||||
" issue.\n" +
|
||||
"\n" +
|
||||
"The user you used to connect to the database (" + getConnection().getConnectionUserName() +
|
||||
") needs to have \"SELECT ON SYS.DBA_RECYCLEBIN\" permissions set before we can perform this operation. " +
|
||||
"Please run the following SQL to set the appropriate permissions, and try running the command again.\n" +
|
||||
"\n" +
|
||||
" GRANT SELECT ON SYS.DBA_RECYCLEBIN TO " + getConnection().getConnectionUserName() + ";";
|
||||
}
|
||||
|
||||
public boolean canAccessDbaRecycleBin() {
|
||||
if (canAccessDbaRecycleBin == null) {
|
||||
DatabaseConnection connection = getConnection();
|
||||
if ((connection == null) || (connection instanceof OfflineConnection)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Statement statement = null;
|
||||
try {
|
||||
statement = ((JdbcConnection) connection).createStatement();
|
||||
@SuppressWarnings("HardCodedStringLiteral") ResultSet resultSet = statement.executeQuery("select 1 from dba_recyclebin where 0=1");
|
||||
resultSet.close(); //don't need to do anything with the result set, just make sure statement ran.
|
||||
this.canAccessDbaRecycleBin = true;
|
||||
} catch (Exception e) {
|
||||
//noinspection HardCodedStringLiteral
|
||||
if ((e instanceof SQLException) && e.getMessage().startsWith("ORA-00942")) { //ORA-00942: table or view does not exist
|
||||
this.canAccessDbaRecycleBin = false;
|
||||
} else {
|
||||
//noinspection HardCodedStringLiteral
|
||||
Scope.getCurrentScope().getLog(getClass()).warning("Cannot check dba_recyclebin access", e);
|
||||
this.canAccessDbaRecycleBin = false;
|
||||
}
|
||||
} finally {
|
||||
JdbcUtils.close(null, statement);
|
||||
}
|
||||
}
|
||||
|
||||
return canAccessDbaRecycleBin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsNotNullConstraintNames() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if the given String would be a valid identifier in Oracle DBMS. In Oracle, a valid identifier has
|
||||
* the following form (case-insensitive comparison):
|
||||
* 1st character: A-Z
|
||||
* 2..n characters: A-Z0-9$_#
|
||||
* The maximum length of an identifier differs by Oracle version and object type.
|
||||
*/
|
||||
public boolean isValidOracleIdentifier(String identifier, Class<? extends DatabaseObject> type) {
|
||||
if ((identifier == null) || (identifier.length() < 1))
|
||||
return false;
|
||||
|
||||
if (!identifier.matches("^(i?)[A-Z][A-Z0-9\\$\\_\\#]*$"))
|
||||
return false;
|
||||
|
||||
/*
|
||||
* @todo It seems we currently do not have a class for tablespace identifiers, and all other classes
|
||||
* we do know seem to be supported as 12cR2 long identifiers, so:
|
||||
*/
|
||||
return (identifier.length() <= LONG_IDENTIFIERS_LEGNTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum number of bytes (NOT: characters) for an identifier. For Oracle <=12c Release 20, this
|
||||
* is 30 bytes, and starting from 12cR2, up to 128 (except for tablespaces, PDB names and some other rather rare
|
||||
* object types).
|
||||
*
|
||||
* @return the maximum length of an object identifier, in bytes
|
||||
*/
|
||||
public int getIdentifierMaximumLength() {
|
||||
try {
|
||||
if (getDatabaseMajorVersion() < ORACLE_12C_MAJOR_VERSION) {
|
||||
return SHORT_IDENTIFIERS_LENGTH;
|
||||
} else if ((getDatabaseMajorVersion() == ORACLE_12C_MAJOR_VERSION) && (getDatabaseMinorVersion() <= 1)) {
|
||||
return SHORT_IDENTIFIERS_LENGTH;
|
||||
} else {
|
||||
return LONG_IDENTIFIERS_LEGNTH;
|
||||
}
|
||||
} catch (DatabaseException ex) {
|
||||
throw new UnexpectedLiquibaseException("Cannot determine the Oracle database version number", ex);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,165 @@
|
||||
package liquibase.datatype.core;
|
||||
|
||||
import liquibase.change.core.LoadDataChange;
|
||||
import liquibase.database.Database;
|
||||
import liquibase.database.core.*;
|
||||
import liquibase.datatype.DataTypeInfo;
|
||||
import liquibase.datatype.DatabaseDataType;
|
||||
import liquibase.datatype.LiquibaseDataType;
|
||||
import liquibase.exception.UnexpectedLiquibaseException;
|
||||
import liquibase.statement.DatabaseFunction;
|
||||
import liquibase.util.StringUtil;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@DataTypeInfo(name = "boolean", aliases = {"java.sql.Types.BOOLEAN", "java.lang.Boolean", "bit", "bool"}, minParameters = 0, maxParameters = 0, priority = LiquibaseDataType.PRIORITY_DEFAULT)
|
||||
public class BooleanType extends LiquibaseDataType {
|
||||
|
||||
@Override
|
||||
public DatabaseDataType toDatabaseDataType(Database database) {
|
||||
String originalDefinition = StringUtil.trimToEmpty(getRawDefinition());
|
||||
if ((database instanceof Firebird3Database)) {
|
||||
return new DatabaseDataType("BOOLEAN");
|
||||
}
|
||||
|
||||
if ((database instanceof Db2zDatabase) || (database instanceof FirebirdDatabase)) {
|
||||
return new DatabaseDataType("SMALLINT");
|
||||
} else if (database instanceof MSSQLDatabase) {
|
||||
return new DatabaseDataType(database.escapeDataTypeName("bit"));
|
||||
} else if (database instanceof MySQLDatabase) {
|
||||
if (originalDefinition.toLowerCase(Locale.US).startsWith("bit")) {
|
||||
return new DatabaseDataType("BIT", getParameters());
|
||||
}
|
||||
return new DatabaseDataType("BIT", 1);
|
||||
} else if (database instanceof OracleDatabase) {
|
||||
return new DatabaseDataType("NUMBER", 1);
|
||||
} else if ((database instanceof SybaseASADatabase) || (database instanceof SybaseDatabase)) {
|
||||
return new DatabaseDataType("BIT");
|
||||
} else if (database instanceof DerbyDatabase) {
|
||||
if (((DerbyDatabase) database).supportsBooleanDataType()) {
|
||||
return new DatabaseDataType("BOOLEAN");
|
||||
} else {
|
||||
return new DatabaseDataType("SMALLINT");
|
||||
}
|
||||
} else if (database instanceof DB2Database) {
|
||||
if (((DB2Database) database).supportsBooleanDataType())
|
||||
return new DatabaseDataType("BOOLEAN");
|
||||
else
|
||||
return new DatabaseDataType("SMALLINT");
|
||||
} else if (database instanceof HsqlDatabase) {
|
||||
return new DatabaseDataType("BOOLEAN");
|
||||
} else if (database instanceof PostgresDatabase) {
|
||||
if (originalDefinition.toLowerCase(Locale.US).startsWith("bit")) {
|
||||
return new DatabaseDataType("BIT", getParameters());
|
||||
}
|
||||
} else if (database instanceof DmDatabase) { // dhb52: DM Support
|
||||
return new DatabaseDataType("bit");
|
||||
}
|
||||
|
||||
return super.toDatabaseDataType(database);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String objectToSql(Object value, Database database) {
|
||||
if ((value == null) || "null".equals(value.toString().toLowerCase(Locale.US))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String returnValue;
|
||||
if (value instanceof String) {
|
||||
value = ((String) value).replaceAll("'", "");
|
||||
if ("true".equals(((String) value).toLowerCase(Locale.US)) || "1".equals(value) || "b'1'".equals(((String) value).toLowerCase(Locale.US)) || "t".equals(((String) value).toLowerCase(Locale.US)) || ((String) value).toLowerCase(Locale.US).equals(this.getTrueBooleanValue(database).toLowerCase(Locale.US))) {
|
||||
returnValue = this.getTrueBooleanValue(database);
|
||||
} else if ("false".equals(((String) value).toLowerCase(Locale.US)) || "0".equals(value) || "b'0'".equals(
|
||||
((String) value).toLowerCase(Locale.US)) || "f".equals(((String) value).toLowerCase(Locale.US)) || ((String) value).toLowerCase(Locale.US).equals(this.getFalseBooleanValue(database).toLowerCase(Locale.US))) {
|
||||
returnValue = this.getFalseBooleanValue(database);
|
||||
} else if (database instanceof PostgresDatabase && Pattern.matches("b?([01])\\1*(::bit|::\"bit\")?", (String) value)) {
|
||||
returnValue = "b'"
|
||||
+ value.toString()
|
||||
.replace("b", "")
|
||||
.replace("\"", "")
|
||||
.replace("::it", "")
|
||||
+ "'::\"bit\"";
|
||||
} else {
|
||||
throw new UnexpectedLiquibaseException("Unknown boolean value: " + value);
|
||||
}
|
||||
} else if (value instanceof Long) {
|
||||
if (Long.valueOf(1).equals(value)) {
|
||||
returnValue = this.getTrueBooleanValue(database);
|
||||
} else {
|
||||
returnValue = this.getFalseBooleanValue(database);
|
||||
}
|
||||
} else if (value instanceof Number) {
|
||||
if (value.equals(1) || "1".equals(value.toString()) || "1.0".equals(value.toString())) {
|
||||
returnValue = this.getTrueBooleanValue(database);
|
||||
} else {
|
||||
returnValue = this.getFalseBooleanValue(database);
|
||||
}
|
||||
} else if (value instanceof DatabaseFunction) {
|
||||
return value.toString();
|
||||
} else if (value instanceof Boolean) {
|
||||
if (((Boolean) value)) {
|
||||
returnValue = this.getTrueBooleanValue(database);
|
||||
} else {
|
||||
returnValue = this.getFalseBooleanValue(database);
|
||||
}
|
||||
} else {
|
||||
throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass() + " to a boolean value");
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
protected boolean isNumericBoolean(Database database) {
|
||||
if (database instanceof Firebird3Database) {
|
||||
return false;
|
||||
}
|
||||
if (database instanceof DerbyDatabase) {
|
||||
return !((DerbyDatabase) database).supportsBooleanDataType();
|
||||
} else if (database instanceof DB2Database) {
|
||||
return !((DB2Database) database).supportsBooleanDataType();
|
||||
}
|
||||
return (database instanceof Db2zDatabase)
|
||||
|| (database instanceof FirebirdDatabase)
|
||||
|| (database instanceof MSSQLDatabase)
|
||||
|| (database instanceof MySQLDatabase)
|
||||
|| (database instanceof OracleDatabase)
|
||||
|| (database instanceof SQLiteDatabase)
|
||||
|| (database instanceof SybaseASADatabase)
|
||||
|| (database instanceof SybaseDatabase)
|
||||
|| (database instanceof DmDatabase); // dhb52: DM Support
|
||||
}
|
||||
|
||||
/**
|
||||
* The database-specific value to use for "false" "boolean" columns.
|
||||
*/
|
||||
public String getFalseBooleanValue(Database database) {
|
||||
if (isNumericBoolean(database)) {
|
||||
return "0";
|
||||
}
|
||||
if (database instanceof InformixDatabase) {
|
||||
return "'f'";
|
||||
}
|
||||
return "FALSE";
|
||||
}
|
||||
|
||||
/**
|
||||
* The database-specific value to use for "true" "boolean" columns.
|
||||
*/
|
||||
public String getTrueBooleanValue(Database database) {
|
||||
if (isNumericBoolean(database)) {
|
||||
return "1";
|
||||
}
|
||||
if (database instanceof InformixDatabase) {
|
||||
return "'t'";
|
||||
}
|
||||
return "TRUE";
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoadDataChange.LOAD_DATA_TYPE getLoadTypeName() {
|
||||
return LoadDataChange.LOAD_DATA_TYPE.BOOLEAN;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1 @@
|
||||
防止IDEA将`.`和`/`混为一谈
|
||||
@ -0,0 +1,21 @@
|
||||
liquibase.database.core.CockroachDatabase
|
||||
liquibase.database.core.DB2Database
|
||||
liquibase.database.core.Db2zDatabase
|
||||
liquibase.database.core.DerbyDatabase
|
||||
liquibase.database.core.Firebird3Database
|
||||
liquibase.database.core.FirebirdDatabase
|
||||
liquibase.database.core.H2Database
|
||||
liquibase.database.core.HsqlDatabase
|
||||
liquibase.database.core.InformixDatabase
|
||||
liquibase.database.core.Ingres9Database
|
||||
liquibase.database.core.MSSQLDatabase
|
||||
liquibase.database.core.MariaDBDatabase
|
||||
liquibase.database.core.MockDatabase
|
||||
liquibase.database.core.MySQLDatabase
|
||||
liquibase.database.core.OracleDatabase
|
||||
liquibase.database.core.PostgresDatabase
|
||||
liquibase.database.core.SQLiteDatabase
|
||||
liquibase.database.core.SybaseASADatabase
|
||||
liquibase.database.core.SybaseDatabase
|
||||
liquibase.database.core.DmDatabase
|
||||
liquibase.database.core.UnsupportedDatabase
|
||||
@ -1,42 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.aliyun;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.SmsCodeMapping;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants;
|
||||
|
||||
/**
|
||||
* 阿里云的 SmsCodeMapping 实现类
|
||||
*
|
||||
* 参见 https://help.aliyun.com/document_detail/101346.htm 文档
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class AliyunSmsCodeMapping implements SmsCodeMapping {
|
||||
|
||||
@Override
|
||||
public ErrorCode apply(String apiCode) {
|
||||
switch (apiCode) {
|
||||
case "OK": return GlobalErrorCodeConstants.SUCCESS;
|
||||
case "isv.ACCOUNT_NOT_EXISTS":
|
||||
case "isv.ACCOUNT_ABNORMAL":
|
||||
case "MissingAccessKeyId": return SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_INVALID;
|
||||
case "isp.RAM_PERMISSION_DENY": return SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY;
|
||||
case "isv.INVALID_JSON_PARAM":
|
||||
case "isv.INVALID_PARAMETERS": return SmsFrameworkErrorCodeConstants.SMS_API_PARAM_ERROR;
|
||||
case "isv.BUSINESS_LIMIT_CONTROL": return SmsFrameworkErrorCodeConstants.SMS_SEND_BUSINESS_LIMIT_CONTROL;
|
||||
case "isv.DAY_LIMIT_CONTROL": return SmsFrameworkErrorCodeConstants.SMS_SEND_DAY_LIMIT_CONTROL;
|
||||
case "isv.SMS_CONTENT_ILLEGAL": return SmsFrameworkErrorCodeConstants.SMS_SEND_CONTENT_INVALID;
|
||||
case "isv.SMS_TEMPLATE_ILLEGAL": return SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_INVALID;
|
||||
case "isv.SMS_SIGNATURE_ILLEGAL":
|
||||
case "isv.SIGN_NAME_ILLEGAL":
|
||||
case "isv.SMS_SIGN_ILLEGAL": return SmsFrameworkErrorCodeConstants.SMS_SIGN_INVALID;
|
||||
case "isv.AMOUNT_NOT_ENOUGH":
|
||||
case "isv.OUT_OF_SERVICE": return SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_MONEY_NOT_ENOUGH;
|
||||
case "isv.MOBILE_NUMBER_ILLEGAL": return SmsFrameworkErrorCodeConstants.SMS_MOBILE_INVALID;
|
||||
case "isv.TEMPLATE_MISSING_PARAMETERS": return SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_PARAM_ERROR;
|
||||
default: return SmsFrameworkErrorCodeConstants.SMS_UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.debug;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.SmsCodeMapping;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 钉钉的 SmsCodeMapping 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class DebugDingTalkCodeMapping implements SmsCodeMapping {
|
||||
|
||||
@Override
|
||||
public ErrorCode apply(String apiCode) {
|
||||
return Objects.equals(apiCode, "0") ? GlobalErrorCodeConstants.SUCCESS : SmsFrameworkErrorCodeConstants.SMS_UNKNOWN;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.tencent;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.SmsCodeMapping;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants;
|
||||
|
||||
import static cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants.*;
|
||||
|
||||
/**
|
||||
* 腾讯云的 SmsCodeMapping 实现类
|
||||
*
|
||||
* 参见 https://cloud.tencent.com/document/api/382/52075#.E5.85.AC.E5.85.B1.E9.94.99.E8.AF.AF.E7.A0.81
|
||||
*
|
||||
* @author : shiwp
|
||||
*/
|
||||
public class TencentSmsCodeMapping implements SmsCodeMapping {
|
||||
|
||||
@Override
|
||||
public ErrorCode apply(String apiCode) {
|
||||
switch (apiCode) {
|
||||
case TencentSmsClient.API_SUCCESS_CODE: return GlobalErrorCodeConstants.SUCCESS;
|
||||
case "FailedOperation.ContainSensitiveWord": return SMS_SEND_CONTENT_INVALID;
|
||||
case "FailedOperation.JsonParseFail":
|
||||
case "MissingParameter.EmptyPhoneNumberSet":
|
||||
case "LimitExceeded.PhoneNumberCountLimit":
|
||||
case "FailedOperation.FailResolvePacket": return GlobalErrorCodeConstants.BAD_REQUEST;
|
||||
case "FailedOperation.InsufficientBalanceInSmsPackage": return SMS_ACCOUNT_MONEY_NOT_ENOUGH;
|
||||
case "FailedOperation.MarketingSendTimeConstraint": return SMS_SEND_MARKET_LIMIT_CONTROL;
|
||||
case "FailedOperation.PhoneNumberInBlacklist": return SMS_MOBILE_BLACK;
|
||||
case "FailedOperation.SignatureIncorrectOrUnapproved": return SMS_SIGN_INVALID;
|
||||
case "FailedOperation.MissingTemplateToModify":
|
||||
case "FailedOperation.TemplateIncorrectOrUnapproved": return SMS_TEMPLATE_INVALID;
|
||||
case "InvalidParameterValue.IncorrectPhoneNumber": return SMS_MOBILE_INVALID;
|
||||
case "InvalidParameterValue.SdkAppIdNotExist": return SMS_APP_ID_INVALID;
|
||||
case "InvalidParameterValue.TemplateParameterLengthLimit":
|
||||
case "InvalidParameterValue.TemplateParameterFormatError": return SMS_TEMPLATE_PARAM_ERROR;
|
||||
case "LimitExceeded.PhoneNumberDailyLimit": return SMS_SEND_DAY_LIMIT_CONTROL;
|
||||
case "LimitExceeded.PhoneNumberThirtySecondLimit":
|
||||
case "LimitExceeded.PhoneNumberOneHourLimit": return SMS_SEND_BUSINESS_LIMIT_CONTROL;
|
||||
case "UnauthorizedOperation.RequestPermissionDeny":
|
||||
case "FailedOperation.ForbidAddMarketingTemplates":
|
||||
case "FailedOperation.NotEnterpriseCertification":
|
||||
case "UnauthorizedOperation.IndividualUserMarketingSmsPermissionDeny": return SMS_PERMISSION_DENY;
|
||||
case "UnauthorizedOperation.RequestIpNotInWhitelist": return SMS_IP_DENY;
|
||||
case "AuthFailure.SecretIdNotFound": return SMS_ACCOUNT_INVALID;
|
||||
}
|
||||
return SmsFrameworkErrorCodeConstants.SMS_UNKNOWN;
|
||||
}
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.aliyun;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.core.KeyValue;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.impl.aliyun.AliyunSmsClient;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsChannelEnum;
|
||||
import cn.iocoder.yudao.framework.sms.core.property.SmsChannelProperties;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@link AliyunSmsClient} 的集成测试
|
||||
*/
|
||||
public class AliyunSmsClientIntegrationTest {
|
||||
|
||||
private static AliyunSmsClient smsClient;
|
||||
|
||||
@BeforeAll
|
||||
public static void before() {
|
||||
// 创建配置类
|
||||
SmsChannelProperties properties = new SmsChannelProperties();
|
||||
properties.setId(1L);
|
||||
properties.setSignature("Ballcat");
|
||||
properties.setCode(SmsChannelEnum.ALIYUN.getCode());
|
||||
properties.setApiKey(System.getenv("ALIYUN_ACCESS_KEY"));
|
||||
properties.setApiSecret(System.getenv("ALIYUN_SECRET_KEY"));
|
||||
// 创建客户端
|
||||
smsClient = new AliyunSmsClient(properties);
|
||||
smsClient.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendSms() {
|
||||
List<KeyValue<String, Object>> templateParams = new ArrayList<>();
|
||||
templateParams.add(new KeyValue<>("code", "1024"));
|
||||
// templateParams.put("operation", "嘿嘿");
|
||||
// SmsResult result = smsClient.send(1L, "15601691399", "4372216", templateParams);
|
||||
SmsCommonResult<SmsSendRespDTO> result = smsClient.sendSms(1L, "15601691399",
|
||||
"SMS_207945135", templateParams);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetSmsTemplate() {
|
||||
String apiTemplateId = "SMS_2079451351";
|
||||
SmsCommonResult<SmsTemplateRespDTO> result = smsClient.getSmsTemplate(apiTemplateId);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,46 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.debug;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.core.KeyValue;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO;
|
||||
import cn.iocoder.yudao.framework.sms.core.client.impl.debug.DebugDingTalkSmsClient;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsChannelEnum;
|
||||
import cn.iocoder.yudao.framework.sms.core.property.SmsChannelProperties;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@link DebugDingTalkSmsClient} 的集成测试
|
||||
*/
|
||||
public class DebugDingTalkSmsClientIntegrationTest {
|
||||
|
||||
private static DebugDingTalkSmsClient smsClient;
|
||||
|
||||
@BeforeAll
|
||||
public static void init() {
|
||||
// 创建配置类
|
||||
SmsChannelProperties properties = new SmsChannelProperties();
|
||||
properties.setId(1L);
|
||||
properties.setSignature("芋道");
|
||||
properties.setCode(SmsChannelEnum.DEBUG_DING_TALK.getCode());
|
||||
properties.setApiKey("696b5d8ead48071237e4aa5861ff08dbadb2b4ded1c688a7b7c9afc615579859");
|
||||
properties.setApiSecret("SEC5c4e5ff888bc8a9923ae47f59e7ccd30af1f14d93c55b4e2c9cb094e35aeed67");
|
||||
// 创建客户端
|
||||
smsClient = new DebugDingTalkSmsClient(properties);
|
||||
smsClient.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendSms() {
|
||||
List<KeyValue<String, Object>> templateParams = new ArrayList<>();
|
||||
templateParams.add(new KeyValue<>("code", "1024"));
|
||||
templateParams.add(new KeyValue<>("operation", "嘿嘿"));
|
||||
// SmsResult result = smsClient.send(1L, "15601691399", "4372216", templateParams);
|
||||
SmsCommonResult<SmsSendRespDTO> result = smsClient.sendSms(1L, "15601691399", "4383920", templateParams);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.aliyun;
|
||||
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@link AliyunSmsCodeMapping} 的单元测试
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class AliyunSmsCodeMappingTest extends BaseMockitoUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
private AliyunSmsCodeMapping codeMapping;
|
||||
|
||||
@Test
|
||||
public void testApply() {
|
||||
assertEquals(GlobalErrorCodeConstants.SUCCESS, codeMapping.apply("OK"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_INVALID, codeMapping.apply("MissingAccessKeyId"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_INVALID, codeMapping.apply("isv.ACCOUNT_NOT_EXISTS"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_INVALID, codeMapping.apply("isv.ACCOUNT_ABNORMAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_DAY_LIMIT_CONTROL, codeMapping.apply("isv.DAY_LIMIT_CONTROL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_CONTENT_INVALID, codeMapping.apply("isv.SMS_CONTENT_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SIGN_INVALID, codeMapping.apply("isv.SMS_SIGN_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SIGN_INVALID, codeMapping.apply("isv.SIGN_NAME_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY, codeMapping.apply("isp.RAM_PERMISSION_DENY"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_MONEY_NOT_ENOUGH, codeMapping.apply("isv.OUT_OF_SERVICE"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_MONEY_NOT_ENOUGH, codeMapping.apply("isv.AMOUNT_NOT_ENOUGH"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_INVALID, codeMapping.apply("isv.SMS_TEMPLATE_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SIGN_INVALID, codeMapping.apply("isv.SMS_SIGNATURE_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_API_PARAM_ERROR, codeMapping.apply("isv.INVALID_PARAMETERS"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_API_PARAM_ERROR, codeMapping.apply("isv.INVALID_JSON_PARAM"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_MOBILE_INVALID, codeMapping.apply("isv.MOBILE_NUMBER_ILLEGAL"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_PARAM_ERROR, codeMapping.apply("isv.TEMPLATE_MISSING_PARAMETERS"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_BUSINESS_LIMIT_CONTROL, codeMapping.apply("isv.BUSINESS_LIMIT_CONTROL"));
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.sms.core.client.impl.tencent;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@link TencentSmsCodeMapping} 的单元测试
|
||||
*
|
||||
* @author : shiwp
|
||||
*/
|
||||
public class TencentSmsCodeMappingTest extends BaseMockitoUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
private TencentSmsCodeMapping codeMapping;
|
||||
|
||||
@Test
|
||||
public void testApply() {
|
||||
assertEquals(GlobalErrorCodeConstants.SUCCESS, codeMapping.apply(TencentSmsClient.API_SUCCESS_CODE));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_CONTENT_INVALID, codeMapping.apply("FailedOperation.ContainSensitiveWord"));
|
||||
assertEquals(GlobalErrorCodeConstants.BAD_REQUEST, codeMapping.apply("FailedOperation.JsonParseFail"));
|
||||
assertEquals(GlobalErrorCodeConstants.BAD_REQUEST, codeMapping.apply("MissingParameter.EmptyPhoneNumberSet"));
|
||||
assertEquals(GlobalErrorCodeConstants.BAD_REQUEST, codeMapping.apply("LimitExceeded.PhoneNumberCountLimit"));
|
||||
assertEquals(GlobalErrorCodeConstants.BAD_REQUEST, codeMapping.apply("FailedOperation.FailResolvePacket"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_MONEY_NOT_ENOUGH, codeMapping.apply("FailedOperation.InsufficientBalanceInSmsPackage"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_MARKET_LIMIT_CONTROL, codeMapping.apply("FailedOperation.MarketingSendTimeConstraint"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_MOBILE_BLACK, codeMapping.apply("FailedOperation.PhoneNumberInBlacklist"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SIGN_INVALID, codeMapping.apply("FailedOperation.SignatureIncorrectOrUnapproved"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_INVALID, codeMapping.apply("FailedOperation.MissingTemplateToModify"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_INVALID, codeMapping.apply("FailedOperation.TemplateIncorrectOrUnapproved"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_MOBILE_INVALID, codeMapping.apply("InvalidParameterValue.IncorrectPhoneNumber"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_APP_ID_INVALID, codeMapping.apply("InvalidParameterValue.SdkAppIdNotExist"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_PARAM_ERROR, codeMapping.apply("InvalidParameterValue.TemplateParameterLengthLimit"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_TEMPLATE_PARAM_ERROR, codeMapping.apply("InvalidParameterValue.TemplateParameterFormatError"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_DAY_LIMIT_CONTROL, codeMapping.apply("LimitExceeded.PhoneNumberDailyLimit"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_BUSINESS_LIMIT_CONTROL, codeMapping.apply("LimitExceeded.PhoneNumberThirtySecondLimit"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_SEND_BUSINESS_LIMIT_CONTROL, codeMapping.apply("LimitExceeded.PhoneNumberOneHourLimit"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY, codeMapping.apply("UnauthorizedOperation.RequestPermissionDeny"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY, codeMapping.apply("FailedOperation.ForbidAddMarketingTemplates"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY, codeMapping.apply("FailedOperation.NotEnterpriseCertification"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_PERMISSION_DENY, codeMapping.apply("UnauthorizedOperation.IndividualUserMarketingSmsPermissionDeny"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_IP_DENY, codeMapping.apply("UnauthorizedOperation.RequestIpNotInWhitelist"));
|
||||
assertEquals(SmsFrameworkErrorCodeConstants.SMS_ACCOUNT_INVALID, codeMapping.apply("AuthFailure.SecretIdNotFound"));
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,56 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-framework</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<packaging>jar</packaging>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>yudao-spring-boot-starter-biz-social</artifactId>
|
||||
<name>${project.artifactId}</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-common</artifactId>
|
||||
</dependency>
|
||||
<!-- Spring 核心 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<!-- Web 相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- spring boot 配置所需依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<!-- 三方云服务相关 -->
|
||||
<dependency>
|
||||
<groupId>com.xingyuv</groupId>
|
||||
<artifactId>spring-boot-starter-justauth</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@ -1,36 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.social.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.social.core.YudaoAuthRequestFactory;
|
||||
import com.xingyuv.http.HttpUtil;
|
||||
import com.xingyuv.http.support.hutool.HutoolImpl;
|
||||
import com.xingyuv.jushauth.cache.AuthStateCache;
|
||||
import com.xingyuv.justauth.autoconfigure.JustAuthProperties;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
/**
|
||||
* 社交自动装配类
|
||||
*
|
||||
* @author timfruit
|
||||
* @date 2021-10-30
|
||||
*/
|
||||
@Slf4j
|
||||
@AutoConfiguration
|
||||
@EnableConfigurationProperties(JustAuthProperties.class)
|
||||
public class YudaoSocialAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
@ConditionalOnProperty(prefix = "justauth", value = "enabled", havingValue = "true", matchIfMissing = true)
|
||||
public YudaoAuthRequestFactory yudaoAuthRequestFactory(JustAuthProperties properties, AuthStateCache authStateCache) {
|
||||
// 需要修改 HttpUtil 使用的实现,避免类报错
|
||||
HttpUtil.setHttp(new HutoolImpl());
|
||||
// 创建 YudaoAuthRequestFactory
|
||||
return new YudaoAuthRequestFactory(properties, authStateCache);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
cn.iocoder.yudao.framework.social.config.YudaoSocialAutoConfiguration
|
||||
@ -1,45 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-framework</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>yudao-spring-boot-starter-biz-weixin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>微信拓展
|
||||
1. 基于 weixin-java-mp 库,对接微信公众号平台。目前主要解决微信公众号的支付场景。
|
||||
2. 基于 weixin-java-miniapp 库,对接微信小程序。目前主要解决微信小程序的一键登录场景。
|
||||
</description>
|
||||
<url>https://github.com/YunaiV/ruoyi-vue-pro</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-common</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Test 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- 三方云服务相关 -->
|
||||
<dependency>
|
||||
<groupId>com.github.binarywang</groupId>
|
||||
<artifactId>wx-java-mp-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.binarywang</groupId>
|
||||
<artifactId>wx-java-miniapp-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@ -1,34 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.weixin;
|
||||
|
||||
import me.chanjar.weixin.common.error.WxErrorException;
|
||||
import me.chanjar.weixin.mp.api.WxMpService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@SpringBootTest(classes = WxMpServiceTest.Application.class)
|
||||
public class WxMpServiceTest {
|
||||
|
||||
@Resource
|
||||
private WxMpService wxMpService;
|
||||
|
||||
@Test
|
||||
public void testGetAccessToken() throws WxErrorException {
|
||||
String accessToken = wxMpService.getAccessToken();
|
||||
System.out.println(accessToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGet() throws WxErrorException {
|
||||
String jsapiTicket = wxMpService.getJsapiTicket();
|
||||
System.out.println(jsapiTicket);
|
||||
}
|
||||
|
||||
@SpringBootApplication
|
||||
public static class Application {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package cn.iocoder.yudao.framework.mq.redis.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.mq.redis.core.RedisMQTemplate;
|
||||
import cn.iocoder.yudao.framework.mq.redis.core.interceptor.RedisMessageInterceptor;
|
||||
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Redis 消息队列 Producer 配置类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
@AutoConfiguration(after = YudaoRedisAutoConfiguration.class)
|
||||
public class YudaoRedisMQProducerAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public RedisMQTemplate redisMQTemplate(StringRedisTemplate redisTemplate,
|
||||
List<RedisMessageInterceptor> interceptors) {
|
||||
RedisMQTemplate redisMQTemplate = new RedisMQTemplate(redisTemplate);
|
||||
// 添加拦截器
|
||||
interceptors.forEach(redisMQTemplate::addInterceptor);
|
||||
return redisMQTemplate;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,2 +1,3 @@
|
||||
cn.iocoder.yudao.framework.mq.redis.config.YudaoRedisMQAutoConfiguration
|
||||
cn.iocoder.yudao.framework.mq.redis.config.YudaoRedisMQProducerAutoConfiguration
|
||||
cn.iocoder.yudao.framework.mq.redis.config.YudaoRedisMQConsumerAutoConfiguration
|
||||
cn.iocoder.yudao.framework.mq.rabbitmq.config.YudaoRabbitMQAutoConfiguration
|
||||
@ -1,14 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.websocket.core.UserHandshakeInterceptor;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.socket.server.HandshakeInterceptor;
|
||||
|
||||
@EnableConfigurationProperties(WebSocketProperties.class)
|
||||
public class WebSocketHandlerConfig {
|
||||
@Bean
|
||||
public HandshakeInterceptor handshakeInterceptor() {
|
||||
return new UserHandshakeInterceptor();
|
||||
}
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.HandshakeInterceptor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class UserHandshakeInterceptor implements HandshakeInterceptor {
|
||||
@Override
|
||||
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
|
||||
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||
attributes.put(WebSocketKeyDefine.LOGIN_USER, loginUser);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
|
||||
|
||||
}
|
||||
}
|
||||
@ -1,9 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class WebSocketKeyDefine {
|
||||
public static final String LOGIN_USER ="LOGIN_USER";
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
public class WebSocketMessageDO {
|
||||
/**
|
||||
* 接收消息的seesion
|
||||
*/
|
||||
private List<Object> seesionKeyList;
|
||||
/**
|
||||
* 发送消息
|
||||
*/
|
||||
private String msgText;
|
||||
|
||||
public static WebSocketMessageDO build(List<Object> seesionKeyList, String msgText) {
|
||||
return new WebSocketMessageDO().setMsgText(msgText).setSeesionKeyList(seesionKeyList);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class WebSocketSessionHandler {
|
||||
private WebSocketSessionHandler() {
|
||||
}
|
||||
|
||||
private static final Map<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();
|
||||
|
||||
public static void addSession(Object sessionKey, WebSocketSession session) {
|
||||
SESSION_MAP.put(sessionKey.toString(), session);
|
||||
}
|
||||
|
||||
public static void removeSession(Object sessionKey) {
|
||||
SESSION_MAP.remove(sessionKey.toString());
|
||||
}
|
||||
|
||||
public static WebSocketSession getSession(Object sessionKey) {
|
||||
return SESSION_MAP.get(sessionKey.toString());
|
||||
}
|
||||
|
||||
public static Collection<WebSocketSession> getSessions() {
|
||||
return SESSION_MAP.values();
|
||||
}
|
||||
|
||||
public static Set<String> getSessionKeys() {
|
||||
return SESSION_MAP.keySet();
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
public class WebSocketUtils {
|
||||
public static boolean sendMessage(WebSocketSession seesion, String message) {
|
||||
if (seesion == null) {
|
||||
log.error("seesion 不存在");
|
||||
return false;
|
||||
}
|
||||
if (seesion.isOpen()) {
|
||||
try {
|
||||
seesion.sendMessage(new TextMessage(message));
|
||||
} catch (IOException e) {
|
||||
log.error("WebSocket 消息发送异常 Session={} | msg= {} | exception={}", seesion, message, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean sendMessage(Object sessionKey, String message) {
|
||||
WebSocketSession session = WebSocketSessionHandler.getSession(sessionKey);
|
||||
return sendMessage(session, message);
|
||||
}
|
||||
}
|
||||
@ -1,49 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core;
|
||||
|
||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
|
||||
|
||||
public class YudaoWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
|
||||
public YudaoWebSocketHandlerDecorator(WebSocketHandler delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
|
||||
/**
|
||||
* websocket 连接时执行的动作
|
||||
* @param session websocket session 对象
|
||||
* @throws Exception 异常对象
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
|
||||
Object sessionKey = sessionKeyGen(session);
|
||||
WebSocketSessionHandler.addSession(sessionKey, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* websocket 关闭连接时执行的动作
|
||||
* @param session websocket session 对象
|
||||
* @param closeStatus 关闭状态对象
|
||||
* @throws Exception 异常对象
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionClosed(final WebSocketSession session, CloseStatus closeStatus) throws Exception {
|
||||
Object sessionKey = sessionKeyGen(session);
|
||||
WebSocketSessionHandler.removeSession(sessionKey);
|
||||
}
|
||||
|
||||
public Object sessionKeyGen(WebSocketSession webSocketSession) {
|
||||
|
||||
Object obj = webSocketSession.getAttributes().get(WebSocketKeyDefine.LOGIN_USER);
|
||||
|
||||
if (obj instanceof LoginUser) {
|
||||
LoginUser loginUser = (LoginUser) obj;
|
||||
// userId 作为唯一区分
|
||||
return String.valueOf(loginUser.getId());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.security;
|
||||
|
||||
import cn.iocoder.yudao.framework.security.config.AuthorizeRequestsCustomizer;
|
||||
import cn.iocoder.yudao.framework.websocket.config.WebSocketProperties;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
|
||||
/**
|
||||
* WebSocket 的权限自定义
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class WebSocketAuthorizeRequestsCustomizer extends AuthorizeRequestsCustomizer {
|
||||
|
||||
private final WebSocketProperties webSocketProperties;
|
||||
|
||||
@Override
|
||||
public void customize(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) {
|
||||
registry.antMatchers(webSocketProperties.getPath()).permitAll();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.kafka;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* Kafka 广播 WebSocket 的消息
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class KafkaWebSocketMessage {
|
||||
|
||||
/**
|
||||
* Session 编号
|
||||
*/
|
||||
private String sessionId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
private String messageType;
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
private String messageContent;
|
||||
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.kafka;
|
||||
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.AbstractWebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
/**
|
||||
* 基于 Kafka 的 {@link WebSocketMessageSender} 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class KafkaWebSocketMessageSender extends AbstractWebSocketMessageSender {
|
||||
|
||||
private final KafkaTemplate<Object, Object> kafkaTemplate;
|
||||
|
||||
private final String topic;
|
||||
|
||||
public KafkaWebSocketMessageSender(WebSocketSessionManager sessionManager,
|
||||
KafkaTemplate<Object, Object> kafkaTemplate,
|
||||
String topic) {
|
||||
super(sessionManager);
|
||||
this.kafkaTemplate = kafkaTemplate;
|
||||
this.topic = topic;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, Long userId, String messageType, String messageContent) {
|
||||
sendKafkaMessage(null, userId, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, String messageType, String messageContent) {
|
||||
sendKafkaMessage(null, null, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(String sessionId, String messageType, String messageContent) {
|
||||
sendKafkaMessage(sessionId, null, null, messageType, messageContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Kafka 广播消息
|
||||
*
|
||||
* @param sessionId Session 编号
|
||||
* @param userId 用户编号
|
||||
* @param userType 用户类型
|
||||
* @param messageType 消息类型
|
||||
* @param messageContent 消息内容
|
||||
*/
|
||||
private void sendKafkaMessage(String sessionId, Long userId, Integer userType,
|
||||
String messageType, String messageContent) {
|
||||
KafkaWebSocketMessage mqMessage = new KafkaWebSocketMessage()
|
||||
.setSessionId(sessionId).setUserId(userId).setUserType(userType)
|
||||
.setMessageType(messageType).setMessageContent(messageContent);
|
||||
try {
|
||||
kafkaTemplate.send(topic, mqMessage).get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
log.error("[sendKafkaMessage][发送消息({}) 到 Kafka 失败]", mqMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.rabbitmq;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* RabbitMQ 广播 WebSocket 的消息
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class RabbitMQWebSocketMessage implements Serializable {
|
||||
|
||||
/**
|
||||
* Session 编号
|
||||
*/
|
||||
private String sessionId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
private String messageType;
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
private String messageContent;
|
||||
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.rabbitmq;
|
||||
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.AbstractWebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.TopicExchange;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
|
||||
/**
|
||||
* 基于 RabbitMQ 的 {@link WebSocketMessageSender} 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class RabbitMQWebSocketMessageSender extends AbstractWebSocketMessageSender {
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
private final TopicExchange topicExchange;
|
||||
|
||||
public RabbitMQWebSocketMessageSender(WebSocketSessionManager sessionManager,
|
||||
RabbitTemplate rabbitTemplate,
|
||||
TopicExchange topicExchange) {
|
||||
super(sessionManager);
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
this.topicExchange = topicExchange;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, Long userId, String messageType, String messageContent) {
|
||||
sendRabbitMQMessage(null, userId, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, String messageType, String messageContent) {
|
||||
sendRabbitMQMessage(null, null, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(String sessionId, String messageType, String messageContent) {
|
||||
sendRabbitMQMessage(sessionId, null, null, messageType, messageContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 RabbitMQ 广播消息
|
||||
*
|
||||
* @param sessionId Session 编号
|
||||
* @param userId 用户编号
|
||||
* @param userType 用户类型
|
||||
* @param messageType 消息类型
|
||||
* @param messageContent 消息内容
|
||||
*/
|
||||
private void sendRabbitMQMessage(String sessionId, Long userId, Integer userType,
|
||||
String messageType, String messageContent) {
|
||||
RabbitMQWebSocketMessage mqMessage = new RabbitMQWebSocketMessage()
|
||||
.setSessionId(sessionId).setUserId(userId).setUserType(userType)
|
||||
.setMessageType(messageType).setMessageContent(messageContent);
|
||||
rabbitTemplate.convertAndSend(topicExchange.getName(), null, mqMessage);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.redis;
|
||||
|
||||
import cn.iocoder.yudao.framework.mq.redis.core.pubsub.AbstractRedisChannelMessage;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* Redis 广播 WebSocket 的消息
|
||||
*/
|
||||
@Data
|
||||
public class RedisWebSocketMessage extends AbstractRedisChannelMessage {
|
||||
|
||||
/**
|
||||
* Session 编号
|
||||
*/
|
||||
private String sessionId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
private String messageType;
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
private String messageContent;
|
||||
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.redis;
|
||||
|
||||
import cn.iocoder.yudao.framework.mq.redis.core.RedisMQTemplate;
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.AbstractWebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 基于 Redis 的 {@link WebSocketMessageSender} 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedisWebSocketMessageSender extends AbstractWebSocketMessageSender {
|
||||
|
||||
private final RedisMQTemplate redisMQTemplate;
|
||||
|
||||
public RedisWebSocketMessageSender(WebSocketSessionManager sessionManager,
|
||||
RedisMQTemplate redisMQTemplate) {
|
||||
super(sessionManager);
|
||||
this.redisMQTemplate = redisMQTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, Long userId, String messageType, String messageContent) {
|
||||
sendRedisMessage(null, userId, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, String messageType, String messageContent) {
|
||||
sendRedisMessage(null, null, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(String sessionId, String messageType, String messageContent) {
|
||||
sendRedisMessage(sessionId, null, null, messageType, messageContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Redis 广播消息
|
||||
*
|
||||
* @param sessionId Session 编号
|
||||
* @param userId 用户编号
|
||||
* @param userType 用户类型
|
||||
* @param messageType 消息类型
|
||||
* @param messageContent 消息内容
|
||||
*/
|
||||
private void sendRedisMessage(String sessionId, Long userId, Integer userType,
|
||||
String messageType, String messageContent) {
|
||||
RedisWebSocketMessage mqMessage = new RedisWebSocketMessage()
|
||||
.setSessionId(sessionId).setUserId(userId).setUserType(userType)
|
||||
.setMessageType(messageType).setMessageContent(messageContent);
|
||||
redisMQTemplate.send(mqMessage);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.rocketmq;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* RocketMQ 广播 WebSocket 的消息
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class RocketMQWebSocketMessage {
|
||||
|
||||
/**
|
||||
* Session 编号
|
||||
*/
|
||||
private String sessionId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
private String messageType;
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
private String messageContent;
|
||||
|
||||
}
|
||||
@ -0,0 +1,61 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.sender.rocketmq;
|
||||
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.AbstractWebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
|
||||
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.core.RocketMQTemplate;
|
||||
|
||||
/**
|
||||
* 基于 RocketMQ 的 {@link WebSocketMessageSender} 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class RocketMQWebSocketMessageSender extends AbstractWebSocketMessageSender {
|
||||
|
||||
private final RocketMQTemplate rocketMQTemplate;
|
||||
|
||||
private final String topic;
|
||||
|
||||
public RocketMQWebSocketMessageSender(WebSocketSessionManager sessionManager,
|
||||
RocketMQTemplate rocketMQTemplate,
|
||||
String topic) {
|
||||
super(sessionManager);
|
||||
this.rocketMQTemplate = rocketMQTemplate;
|
||||
this.topic = topic;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, Long userId, String messageType, String messageContent) {
|
||||
sendRocketMQMessage(null, userId, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Integer userType, String messageType, String messageContent) {
|
||||
sendRocketMQMessage(null, null, userType, messageType, messageContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(String sessionId, String messageType, String messageContent) {
|
||||
sendRocketMQMessage(sessionId, null, null, messageType, messageContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 RocketMQ 广播消息
|
||||
*
|
||||
* @param sessionId Session 编号
|
||||
* @param userId 用户编号
|
||||
* @param userType 用户类型
|
||||
* @param messageType 消息类型
|
||||
* @param messageContent 消息内容
|
||||
*/
|
||||
private void sendRocketMQMessage(String sessionId, Long userId, Integer userType,
|
||||
String messageType, String messageContent) {
|
||||
RocketMQWebSocketMessage mqMessage = new RocketMQWebSocketMessage()
|
||||
.setSessionId(sessionId).setUserId(userId).setUserType(userType)
|
||||
.setMessageType(messageType).setMessageContent(messageContent);
|
||||
rocketMQTemplate.syncSend(topic, mqMessage);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.session;
|
||||
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* {@link WebSocketSession} 管理器的接口
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public interface WebSocketSessionManager {
|
||||
|
||||
/**
|
||||
* 添加 Session
|
||||
*
|
||||
* @param session Session
|
||||
*/
|
||||
void addSession(WebSocketSession session);
|
||||
|
||||
/**
|
||||
* 移除 Session
|
||||
*
|
||||
* @param session Session
|
||||
*/
|
||||
void removeSession(WebSocketSession session);
|
||||
|
||||
/**
|
||||
* 获得指定编号的 Session
|
||||
*
|
||||
* @param id Session 编号
|
||||
* @return Session
|
||||
*/
|
||||
WebSocketSession getSession(String id);
|
||||
|
||||
/**
|
||||
* 获得指定用户类型的 Session 列表
|
||||
*
|
||||
* @param userType 用户类型
|
||||
* @return Session 列表
|
||||
*/
|
||||
Collection<WebSocketSession> getSessionList(Integer userType);
|
||||
|
||||
/**
|
||||
* 获得指定用户编号的 Session 列表
|
||||
*
|
||||
* @param userType 用户类型
|
||||
* @param userId 用户编号
|
||||
* @return Session 列表
|
||||
*/
|
||||
Collection<WebSocketSession> getSessionList(Integer userType, Long userId);
|
||||
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
package cn.iocoder.yudao.framework.websocket.core.util;
|
||||
|
||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 专属于 web 包的工具类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class WebSocketFrameworkUtils {
|
||||
|
||||
public static final String ATTRIBUTE_LOGIN_USER = "LOGIN_USER";
|
||||
|
||||
/**
|
||||
* 设置当前用户
|
||||
*
|
||||
* @param loginUser 登录用户
|
||||
* @param attributes Session
|
||||
*/
|
||||
public static void setLoginUser(LoginUser loginUser, Map<String, Object> attributes) {
|
||||
attributes.put(ATTRIBUTE_LOGIN_USER, loginUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户
|
||||
*
|
||||
* @return 当前用户
|
||||
*/
|
||||
public static LoginUser getLoginUser(WebSocketSession session) {
|
||||
return (LoginUser) session.getAttributes().get(ATTRIBUTE_LOGIN_USER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前用户的编号
|
||||
*
|
||||
* @return 用户编号
|
||||
*/
|
||||
public static Long getLoginUserId(WebSocketSession session) {
|
||||
LoginUser loginUser = getLoginUser(session);
|
||||
return loginUser != null ? loginUser.getId() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前用户的类型
|
||||
*
|
||||
* @return 用户编号
|
||||
*/
|
||||
public static Integer getLoginUserType(WebSocketSession session) {
|
||||
LoginUser loginUser = getLoginUser(session);
|
||||
return loginUser != null ? loginUser.getUserType() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前用户的租户编号
|
||||
*
|
||||
* @param session Session
|
||||
* @return 租户编号
|
||||
*/
|
||||
public static Long getTenantId(WebSocketSession session) {
|
||||
LoginUser loginUser = getLoginUser(session);
|
||||
return loginUser != null ? loginUser.getTenantId() : null;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1 @@
|
||||
<http://www.iocoder.cn/Spring-Boot/WebSocket/?yudao>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue