instruction
stringlengths
77
90.1k
package com.strongdata.shardata.executor.connector;import java.sql.SQLException;/** * Transaction manager interface for proxy. */public interface TransactionManager { /** * Begin transaction. * * @throws SQLException SQL exception */ void begin() throws SQLException; /** * Commit transaction. * * @throws SQLException SQL exception */ void commit() throws SQLException; /** * Rollback transaction. * * @throws SQLException SQL exception */ void rollback() throws SQLException; /** * Set savepoint. * * @param savepointName savepoint name * @throws SQLException SQL exception */ void setSavepoint(String savepointName) throws SQLException; /** * Rollback to savepoint. * * @param savepointName savepoint name * @throws SQLException SQL exception */ void rollbackTo(String savepointName) throws SQLException; /** * Release savepoint. * * @param savepointName savepoint name * @throws SQLException SQL exception */ void releaseSavepoint(String savepointName) throws SQLException;}
package com.strongdata.shardata.executor.context;import lombok.AccessLevel;import lombok.Getter;import lombok.NoArgsConstructor;import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;import org.apache.shardingsphere.infra.executor.kernel.ExecutorEngine;/** * Backend executor context. */@NoArgsConstructor(access = AccessLevel.PRIVATE)@Getterpublic final class BackendExecutorContext { private static final BackendExecutorContext INSTANCE = new BackendExecutorContext(); private final ExecutorEngine executorEngine = ExecutorEngine.createExecutorEngineWithSize( ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps().<Integer>getValue(ConfigurationPropertyKey.KERNEL_EXECUTOR_SIZE)); /** * Get executor context instance. * * @return instance of executor context */ public static BackendExecutorContext getInstance() { return INSTANCE; }}
package com.strongdata.shardata.executor.context;import com.google.common.base.Strings;import com.strongdata.shardata.executor.jdbc.datasource.JDBCBackendDataSource;import lombok.AccessLevel;import lombok.Getter;import lombok.NoArgsConstructor;import org.apache.shardingsphere.dialect.exception.syntax.database.NoDatabaseSelectedException;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.mode.manager.ContextManager;import java.util.Collection;import java.util.Optional;import java.util.stream.Collectors;/** * Proxy context. */@NoArgsConstructor(access = AccessLevel.PRIVATE)@Getterpublic final class ProxyContext { private static final ProxyContext INSTANCE = new ProxyContext(); private final JDBCBackendDataSource backendDataSource = new JDBCBackendDataSource(); private ContextManager contextManager; /** * Initialize proxy context. * * @param contextManager context manager */ public static void init(final ContextManager contextManager) { INSTANCE.contextManager = contextManager; } /** * Get instance of proxy context. * * @return got instance */ public static ProxyContext getInstance() { return INSTANCE; } /** * Check database exists. * * @param name database name * @return database exists or not */ public boolean databaseExists(final String name) { return contextManager.getMetaDataContexts().getMetaData().containsDatabase(name); } public boolean tableExists(final String databaseName, final String tableName) { return contextManager.getMetaDataContexts().getMetaData().getDatabase(databaseName).getSchema(databaseName).containsTable(tableName); } /** * Get database. * * @param name database name * @return got database */ public ShardingSphereDatabase getDatabase(final String name) { ShardingSpherePreconditions.checkState(!Strings.isNullOrEmpty(name) && contextManager.getMetaDataContexts().getMetaData().containsDatabase(name), NoDatabaseSelectedException::new); return contextManager.getMetaDataContexts().getMetaData().getDatabase(name); } /** * Get all database names. * * @return all database names */ public Collection<String> getAllDatabaseNames() { return contextManager.getMetaDataContexts().getMetaData().getDatabases().values().stream().map(ShardingSphereDatabase::getName).collect(Collectors.toList()); } /** * Get instance state context. * * @return instance state context */ public Optional<InstanceStateContext> getInstanceStateContext() { return null == contextManager.getInstanceContext() ? Optional.empty() : Optional.ofNullable(contextManager.getInstanceContext().getInstance().getState()); }}
package com.strongdata.shardata.executor.export;import com.strongdata.shardata.common.utils.EncryptUtils;import lombok.AccessLevel;import lombok.NoArgsConstructor;import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;import org.apache.shardingsphere.infra.datasource.props.DataSourcePropertiesCreator;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.util.spi.type.ordered.OrderedSPILoader;import org.apache.shardingsphere.infra.util.yaml.YamlEngine;import org.apache.shardingsphere.infra.yaml.config.swapper.rule.YamlRuleConfigurationSwapper;import org.apache.shardingsphere.mask.api.config.MaskRuleConfiguration;import org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration;import org.apache.shardingsphere.shadow.api.config.ShadowRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;import org.apache.shardingsphere.single.api.config.SingleRuleConfiguration;import javax.sql.DataSource;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;/** * Export utility class. */@NoArgsConstructor(access = AccessLevel.PRIVATE)public class YamlExportor { private static final String PASSWORD_KEY = "password"; private static final String DATASOURCECLASSNAME_KEY = "dataSourceClassName"; /** * Generate configuration data of ShardingSphere database. * * @param database ShardingSphere database * @return configuration data */ public static String generateExportDatabaseData(final ShardingSphereDatabase database) { StringBuilder result = new StringBuilder(); appendDatabaseName(database.getName(), result); appendDataSourceConfigurations(database, result); appendRuleConfigurations(database.getRuleMetaData().getConfigurations(), result); return result.toString(); } private static void appendDatabaseName(final String databaseName, final StringBuilder stringBuilder) { stringBuilder.append("databaseName: ").append(databaseName).append(System.lineSeparator()); } private static void appendDataSourceConfigurations(final ShardingSphereDatabase database, final StringBuilder stringBuilder) { if (database.getResourceMetaData().getDataSources().isEmpty()) { return; } stringBuilder.append("dataSources:").append(System.lineSeparator()); for (Entry<String, DataSource> entry : database.getResourceMetaData().getDataSources().entrySet()) { appendDataSourceConfiguration(entry.getKey(), entry.getValue(), stringBuilder); } } private static void appendDataSourceConfiguration(final String name, final DataSource dataSource, final StringBuilder stringBuilder) { stringBuilder.append(" ").append(name).append(":").append(System.lineSeparator()); DataSourceProperties dataSourceProps = DataSourcePropertiesCreator.create(dataSource); Map<String, Object> map = new HashMap<>(); map.put(DATASOURCECLASSNAME_KEY, dataSourceProps.getDataSourceClassName()); map.putAll(dataSourceProps.getConnectionPropertySynonyms().getStandardProperties()); map.putAll(dataSourceProps.getPoolPropertySynonyms().getStandardProperties()); map.putAll(dataSourceProps.getPoolPropertySynonyms().getLocalProperties()); map.put(PASSWORD_KEY, EncryptUtils.encryptFromString(String.valueOf(map.get(PASSWORD_KEY)))); map.forEach((key, value) -> stringBuilder.append(" ").append(key).append(": ").append(value).append(System.lineSeparator())); } @SuppressWarnings({"rawtypes", "unchecked"}) private static void appendRuleConfigurations(final Collection<RuleConfiguration> ruleConfigs, final StringBuilder stringBuilder) { if (ruleConfigs.isEmpty()) { return; } stringBuilder.append("rules:").append(System.lineSeparator()); for (Entry<RuleConfiguration, YamlRuleConfigurationSwapper> entry : OrderedSPILoader.getServices(YamlRuleConfigurationSwapper.class, ruleConfigs).entrySet()) { if (checkRuleConfigIsEmpty(entry.getKey())) { continue; } stringBuilder.append(YamlEngine.marshal(Collections.singletonList(entry.getValue().swapToYamlConfiguration(entry.getKey())))); } } private static boolean checkRuleConfigIsEmpty(final RuleConfiguration ruleConfig) { if (ruleConfig instanceof ShardingRuleConfiguration) { ShardingRuleConfiguration shardingRuleConfig = (ShardingRuleConfiguration) ruleConfig; return shardingRuleConfig.getTables().isEmpty() && shardingRuleConfig.getAutoTables().isEmpty(); } else if (ruleConfig instanceof ReadwriteSplittingRuleConfiguration) { return ((ReadwriteSplittingRuleConfiguration) ruleConfig).getDataSources().isEmpty(); } else if (ruleConfig instanceof EncryptRuleConfiguration) { return ((EncryptRuleConfiguration) ruleConfig).getTables().isEmpty(); } else if (ruleConfig instanceof ShadowRuleConfiguration) { return ((ShadowRuleConfiguration) ruleConfig).getTables().isEmpty(); } else if (ruleConfig instanceof MaskRuleConfiguration) { return ((MaskRuleConfiguration) ruleConfig).getTables().isEmpty(); } else if (ruleConfig instanceof SingleRuleConfiguration) { return !((SingleRuleConfiguration) ruleConfig).getDefaultDataSource().isPresent(); } return false; }}
package com.strongdata.shardata.executor.instance;import lombok.Getter;import org.apache.shardingsphere.infra.autogen.version.ShardingSphereVersion;import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;import org.apache.shardingsphere.infra.instance.metadata.InstanceType;import org.apache.shardingsphere.infra.instance.utils.IpUtils;@Getterpublic final class ConsoleInstanceMetaData implements InstanceMetaData { private final String id; private final String ip; private final String version; public ConsoleInstanceMetaData(final String id) { this.id = id; ip = IpUtils.getIp(); this.version = ShardingSphereVersion.VERSION; } public ConsoleInstanceMetaData(final String id, final String version) { this.id = id; ip = IpUtils.getIp(); this.version = version; } @Override public InstanceType getType() { return InstanceType.PROXY; } @Override public String getAttributes() { return ""; }}
package com.strongdata.shardata.executor.instance;import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaDataBuilder;import java.util.UUID;public final class ConsoleInstanceMetaDataBuilder implements InstanceMetaDataBuilder { @Override public InstanceMetaData build(final int port) { return new ConsoleInstanceMetaData(UUID.randomUUID().toString()); } @Override public String getType() { return "Console"; }}
package com.strongdata.shardata.executor.jdbc.connection;import java.sql.Connection;/** * Connection post processor. */@FunctionalInterfacepublic interface ConnectionPostProcessor { /** * Process connection. * * @param target target connection */ void process(Connection target);}
package com.strongdata.shardata.executor.jdbc.connection;import lombok.SneakyThrows;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * Resource lock. */public final class ResourceLock { private static final long DEFAULT_TIMEOUT_MILLISECONDS = 200L; private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); /** * Await. */ @SneakyThrows(InterruptedException.class) public void doAwait() { lock.lock(); boolean result = false; try { result = condition.await(DEFAULT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);// if (result) {// //正常被signal唤醒// }else {// //超时// } } finally { lock.unlock(); } } /** * Notify. */ public void doNotify() { lock.lock(); try { condition.signalAll(); } finally { lock.unlock(); } }}
package com.strongdata.shardata.executor.jdbc.datasource;/** * Backend data source. */public interface BackendDataSource {}
package com.strongdata.shardata.executor.jdbc.datasource;import com.google.common.base.Preconditions;import com.strongdata.shardata.executor.context.ProxyContext;import org.apache.shardingsphere.infra.datasource.registry.GlobalDataSourceRegistry;import org.apache.shardingsphere.infra.exception.OverallConnectionNotEnoughException;import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;import org.apache.shardingsphere.transaction.api.TransactionType;import org.apache.shardingsphere.transaction.rule.TransactionRule;import org.apache.shardingsphere.transaction.spi.ShardingSphereTransactionManager;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * Backend data source of JDBC. */public final class JDBCBackendDataSource implements BackendDataSource { /** * Get connections. * * @param databaseName database name * @param dataSourceName data source name * @param connectionSize size of connections to get * @param connectionMode connection mode * @return connections * @throws SQLException SQL exception */ public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionSize, final ConnectionMode connectionMode) throws SQLException { return getConnections(databaseName, dataSourceName, connectionSize, connectionMode, ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(TransactionRule.class).getDefaultType()); } /** * Get connections. * * @param databaseName database name * @param dataSourceName data source name * @param connectionSize size of connections to be get * @param connectionMode connection mode * @param transactionType transaction type * @return connections * @throws SQLException SQL exception */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionSize, final ConnectionMode connectionMode, final TransactionType transactionType) throws SQLException { DataSource dataSource = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(databaseName).getResourceMetaData().getDataSources().get(dataSourceName); if (dataSourceName.contains(".")) { String dataSourceStr = dataSourceName.split("\\.")[0]; if (GlobalDataSourceRegistry.getInstance().getCachedDataSourceDataSources().containsKey(dataSourceStr)) { dataSource = GlobalDataSourceRegistry.getInstance().getCachedDataSourceDataSources().get(dataSourceStr); } } Preconditions.checkNotNull(dataSource, "Can not get connection from datasource %s.", dataSourceName); if (1 == connectionSize) { return Collections.singletonList(createConnection(databaseName, dataSourceName, dataSource, transactionType)); } if (ConnectionMode.CONNECTION_STRICTLY == connectionMode) { return createConnections(databaseName, dataSourceName, dataSource, connectionSize, transactionType); } synchronized (dataSource) { return createConnections(databaseName, dataSourceName, dataSource, connectionSize, transactionType); } } private List<Connection> createConnections(final String databaseName, final String dataSourceName, final DataSource dataSource, final int connectionSize, final TransactionType transactionType) throws SQLException { List<Connection> result = new ArrayList<>(connectionSize); for (int i = 0; i < connectionSize; i++) { try { result.add(createConnection(databaseName, dataSourceName, dataSource, transactionType)); } catch (final SQLException ex) { for (Connection each : result) { each.close(); } throw new OverallConnectionNotEnoughException(connectionSize, result.size()); } } return result; } private Connection createConnection(final String databaseName, final String dataSourceName, final DataSource dataSource, final TransactionType transactionType) throws SQLException { TransactionRule transactionRule = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(TransactionRule.class); ShardingSphereTransactionManager transactionManager = transactionRule.getResource().getTransactionManager(transactionType); Connection result = isInTransaction(transactionManager) ? transactionManager.getConnection(databaseName, dataSourceName) : dataSource.getConnection(); if (dataSourceName.contains(".")) { String catalog = dataSourceName.split("\\.")[1]; result.setCatalog(catalog); } return result; } private boolean isInTransaction(final ShardingSphereTransactionManager transactionManager) { return null != transactionManager && transactionManager.isInTransaction(); }}
package com.strongdata.shardata.executor.jdbc.executor.callback;import com.strongdata.shardata.executor.connector.CommandExcutor;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.jdbc.sane.SaneQueryResultEngine;import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.database.type.DatabaseTypeEngine;import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.driver.jdbc.type.memory.JDBCMemoryQueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.driver.jdbc.type.stream.JDBCStreamQueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.update.UpdateResult;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.sql.Types;import java.util.Map;import java.util.Optional;/** * JDBC executor callback for proxy. */public abstract class ConsoleJDBCExecutorCallback extends JDBCExecutorCallback<ExecuteResult> { private final CommandExcutor commandExcutor; private final boolean isReturnGeneratedKeys; private final boolean fetchMetaData; private boolean hasMetaData; public ConsoleJDBCExecutorCallback(final DatabaseType protocolType, final Map<String, DatabaseType> storageTypes, final SQLStatement sqlStatement, final CommandExcutor commandExcutor, final boolean isReturnGeneratedKeys, final boolean isExceptionThrown, final boolean fetchMetaData) { super(protocolType, storageTypes, sqlStatement, isExceptionThrown); this.commandExcutor = commandExcutor; this.isReturnGeneratedKeys = isReturnGeneratedKeys; this.fetchMetaData = fetchMetaData; } @Override public ExecuteResult executeSQL(final String sql, final Statement statement, final ConnectionMode connectionMode, final DatabaseType storageType) throws SQLException { if (fetchMetaData && !hasMetaData) { hasMetaData = true; return executeSQL(sql, statement, connectionMode, true, storageType); } return executeSQL(sql, statement, connectionMode, false, storageType); } private ExecuteResult executeSQL(final String sql, final Statement statement, final ConnectionMode connectionMode, final boolean withMetaData, final DatabaseType storageType) throws SQLException { commandExcutor.add(statement); if (execute(sql, statement, isReturnGeneratedKeys)) { ResultSet resultSet = statement.getResultSet(); commandExcutor.add(resultSet); return createQueryResult(resultSet, connectionMode, storageType); } return new UpdateResult(statement.getUpdateCount(), isReturnGeneratedKeys ? getGeneratedKey(statement) : 0L); } protected abstract boolean execute(String sql, Statement statement, boolean isReturnGeneratedKeys) throws SQLException; private QueryResult createQueryResult(final ResultSet resultSet, final ConnectionMode connectionMode, final DatabaseType storageType) throws SQLException { return ConnectionMode.MEMORY_STRICTLY == connectionMode ? new JDBCStreamQueryResult(resultSet) : new JDBCMemoryQueryResult(resultSet, storageType); } private long getGeneratedKey(final Statement statement) throws SQLException { ResultSet resultSet = statement.getGeneratedKeys(); return resultSet.next() ? getGeneratedKeyIfInteger(resultSet) : 0L; } private long getGeneratedKeyIfInteger(final ResultSet resultSet) throws SQLException { switch (resultSet.getMetaData().getColumnType(1)) { case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: return resultSet.getLong(1); default: return 0L; } } @Override protected final Optional<ExecuteResult> getSaneResult(final SQLStatement sqlStatement, final SQLException ex) { return TypedSPILoader.getService(SaneQueryResultEngine.class, getProtocolTypeType().getType()).getSaneQueryResult(sqlStatement, ex); } private DatabaseType getProtocolTypeType() { Optional<DatabaseType> configuredDatabaseType = findConfiguredDatabaseType(); if (configuredDatabaseType.isPresent()) { return configuredDatabaseType.get(); } if (ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabases().isEmpty()) { return DatabaseTypeEngine.getTrunkDatabaseType("MySQL"); } return ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabases().values().iterator().next().getProtocolType(); } private static Optional<DatabaseType> findConfiguredDatabaseType() { String configuredDatabaseType = ProxyContext.getInstance() .getContextManager().getMetaDataContexts().getMetaData().getProps().getValue(ConfigurationPropertyKey.PROXY_FRONTEND_DATABASE_PROTOCOL_TYPE); return configuredDatabaseType.isEmpty() ? Optional.empty() : Optional.of(DatabaseTypeEngine.getTrunkDatabaseType(configuredDatabaseType)); }}
package com.strongdata.shardata.executor.jdbc.executor.callback;import com.strongdata.shardata.executor.connector.CommandExcutor;import com.strongdata.shardata.executor.jdbc.executor.callback.impl.ConsolePreparedStatementExecutorCallback;import com.strongdata.shardata.executor.jdbc.executor.callback.impl.ConsoleStatementExecutorCallback;import lombok.AccessLevel;import lombok.NoArgsConstructor;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.JDBCDriverType;import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.util.Map;/** * Proxy JDBC executor callback factory. */@NoArgsConstructor(access = AccessLevel.PRIVATE)public final class ConsoleJDBCExecutorCallbackFactory { /** * Create new instance of Proxy JDBC executor callback. * * @param type driver type * @param protocolType protocol type * @param storageTypes storage types * @param sqlStatement SQL statement * @param databaseConnector database connector * @param isReturnGeneratedKeys is return generated keys or not * @param isExceptionThrown is exception thrown or not * @param isFetchMetaData is fetch meta data or not * @return created instance */ public static ConsoleJDBCExecutorCallback newInstance(final String type, final DatabaseType protocolType, final Map<String, DatabaseType> storageTypes, final SQLStatement sqlStatement, final CommandExcutor databaseConnector, final boolean isReturnGeneratedKeys, final boolean isExceptionThrown, final boolean isFetchMetaData) { if (JDBCDriverType.STATEMENT.equals(type)) { return new ConsoleStatementExecutorCallback(protocolType, storageTypes, sqlStatement, databaseConnector, isReturnGeneratedKeys, isExceptionThrown, isFetchMetaData); } if (JDBCDriverType.PREPARED_STATEMENT.equals(type)) { return new ConsolePreparedStatementExecutorCallback(protocolType, storageTypes, sqlStatement, databaseConnector, isReturnGeneratedKeys, isExceptionThrown, isFetchMetaData); } throw new UnsupportedSQLOperationException(String.format("Unsupported driver type: `%s`", type)); }}
package com.strongdata.shardata.executor.jdbc.executor.callback.impl;import com.strongdata.shardata.executor.connector.CommandExcutor;import com.strongdata.shardata.executor.jdbc.executor.callback.ConsoleJDBCExecutorCallback;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;import java.util.Map;/** * Prepared statement executor callback for proxy. */public final class ConsolePreparedStatementExecutorCallback extends ConsoleJDBCExecutorCallback { public ConsolePreparedStatementExecutorCallback(final DatabaseType protocolType, final Map<String, DatabaseType> storageTypes, final SQLStatement sqlStatement, final CommandExcutor commandExcutor, final boolean isReturnGeneratedKeys, final boolean isExceptionThrown, final boolean fetchMetaData) { super(protocolType, storageTypes, sqlStatement, commandExcutor, isReturnGeneratedKeys, isExceptionThrown, fetchMetaData); } @Override protected boolean execute(final String sql, final Statement statement, final boolean isReturnGeneratedKeys) throws SQLException { return ((PreparedStatement) statement).execute(); }}
package com.strongdata.shardata.executor.jdbc.executor.callback.impl;import com.strongdata.shardata.executor.connector.CommandExcutor;import com.strongdata.shardata.executor.jdbc.executor.callback.ConsoleJDBCExecutorCallback;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.sql.SQLException;import java.sql.Statement;import java.util.Map;/** * Statement executor callback for proxy. */public final class ConsoleStatementExecutorCallback extends ConsoleJDBCExecutorCallback { public ConsoleStatementExecutorCallback(final DatabaseType protocolType, final Map<String, DatabaseType> storageTypes, final SQLStatement sqlStatement, final CommandExcutor commandExcutor, final boolean isReturnGeneratedKeys, final boolean isExceptionThrown, final boolean fetchMetaData) { super(protocolType, storageTypes, sqlStatement, commandExcutor, isReturnGeneratedKeys, isExceptionThrown, fetchMetaData); } @Override protected boolean execute(final String sql, final Statement statement, final boolean isReturnGeneratedKeys) throws SQLException { return statement.execute(sql, isReturnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); }}
package com.strongdata.shardata.executor.jdbc.executor;import com.strongdata.shardata.executor.connector.CommandExcutor;import com.strongdata.shardata.executor.connector.session.ConnectionSession;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.jdbc.executor.callback.ConsoleJDBCExecutorCallbackFactory;import lombok.RequiredArgsConstructor;import org.apache.shardingsphere.infra.binder.QueryContext;import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.executor.kernel.model.ExecutionGroupContext;import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutionUnit;import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutor;import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;import org.apache.shardingsphere.infra.executor.sql.process.ExecuteProcessEngine;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.mode.metadata.MetaDataContexts;import java.sql.SQLException;import java.util.List;import java.util.Map;/** * Proxy JDBC executor. */@RequiredArgsConstructorpublic final class ConsoleJDBCExecutor { private final String type; private final ConnectionSession connectionSession; private final CommandExcutor databaseConnector; private final JDBCExecutor jdbcExecutor; /** * Execute. * * @param queryContext query context * @param executionGroupContext execution group context * @param isReturnGeneratedKeys is return generated keys * @param isExceptionThrown is exception thrown * @return execute results * @throws SQLException SQL exception */ public List<ExecuteResult> execute(final QueryContext queryContext, final ExecutionGroupContext<JDBCExecutionUnit> executionGroupContext, final boolean isReturnGeneratedKeys, final boolean isExceptionThrown) throws SQLException { ExecuteProcessEngine executeProcessEngine = new ExecuteProcessEngine(); try { MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); ShardingSphereDatabase database = metaDataContexts.getMetaData().getDatabase(connectionSession.getDatabaseName()); DatabaseType protocolType = database.getProtocolType(); Map<String, DatabaseType> storageTypes = database.getResourceMetaData().getStorageTypes(); executeProcessEngine.initializeExecution(executionGroupContext, queryContext); SQLStatementContext<?> context = queryContext.getSqlStatementContext(); return jdbcExecutor.execute(executionGroupContext, ConsoleJDBCExecutorCallbackFactory.newInstance(type, protocolType, storageTypes, context.getSqlStatement(), databaseConnector, isReturnGeneratedKeys, isExceptionThrown, true), ConsoleJDBCExecutorCallbackFactory.newInstance(type, protocolType, storageTypes, context.getSqlStatement(), databaseConnector, isReturnGeneratedKeys, isExceptionThrown, false)); } finally { executeProcessEngine.cleanExecution(); } }}
package com.strongdata.shardata.executor.jdbc.response.data;import lombok.Getter;import lombok.RequiredArgsConstructor;/** * Query response cell. */@RequiredArgsConstructor@Getterpublic final class QueryResponseCell { private final int jdbcType; private final Object data;}
package com.strongdata.shardata.executor.jdbc.response.data;import lombok.Getter;import lombok.RequiredArgsConstructor;import java.util.ArrayList;import java.util.List;/** * Query response row. */@RequiredArgsConstructor@Getterpublic final class QueryResponseRow { private final List<QueryResponseCell> cells; /** * Get row data. * * @return row data */ public List<Object> getData() { List<Object> result = new ArrayList<>(cells.size()); for (QueryResponseCell cell : cells) { result.add(cell.getData()); } return result; }}
package com.strongdata.shardata.executor.jdbc.response.header.query;import lombok.Getter;import lombok.RequiredArgsConstructor;/** * Query header. */@RequiredArgsConstructor@Getterpublic final class QueryHeader { private final String schema; private final String table; private final String columnLabel; private final String columnName; private final int columnType; private final String columnTypeName; private final int columnLength; private final int decimals; private final boolean signed; private final boolean primaryKey; private final boolean notNull; private final boolean autoIncrement;}
package com.strongdata.shardata.executor.jdbc.response.header.query;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.util.spi.annotation.SingletonSPI;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPI;import java.sql.SQLException;/** * Query header builder. */@SingletonSPIpublic interface QueryHeaderBuilder extends TypedSPI { /** * Build query header. * * @param queryResultMetaData query result meta data * @param database database * @param columnName column name * @param columnLabel column label * @param columnIndex column index * @return query header * @throws SQLException SQL exception */ QueryHeader build(QueryResultMetaData queryResultMetaData, ShardingSphereDatabase database, String columnName, String columnLabel, int columnIndex) throws SQLException;}
package com.strongdata.shardata.executor.jdbc.response.header.query;import lombok.RequiredArgsConstructor;import org.apache.shardingsphere.infra.binder.segment.select.projection.DerivedColumn;import org.apache.shardingsphere.infra.binder.segment.select.projection.Projection;import org.apache.shardingsphere.infra.binder.segment.select.projection.ProjectionsContext;import org.apache.shardingsphere.infra.binder.segment.select.projection.impl.ColumnProjection;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import java.sql.SQLException;/** * Query header builder engine. */@RequiredArgsConstructorpublic final class QueryHeaderBuilderEngine { private final DatabaseType databaseType; /** * Build query header builder. * * @param queryResultMetaData query result meta data * @param database database * @param columnIndex column index * @return query header * @throws SQLException SQL exception */ public QueryHeader build(final QueryResultMetaData queryResultMetaData, final ShardingSphereDatabase database, final int columnIndex) throws SQLException { String columnName = queryResultMetaData.getColumnName(columnIndex); String columnLabel = queryResultMetaData.getColumnLabel(columnIndex); return TypedSPILoader.getService(QueryHeaderBuilder.class, databaseType.getType()).build(queryResultMetaData, database, columnName, columnLabel, columnIndex); } /** * Build query header builder. * * @param projectionsContext projections context * @param queryResultMetaData query result meta data * @param database database * @param columnIndex column index * @return query header * @throws SQLException SQL exception */ public QueryHeader build(final ProjectionsContext projectionsContext, final QueryResultMetaData queryResultMetaData, final ShardingSphereDatabase database, final int columnIndex) throws SQLException { String columnName = getColumnName(projectionsContext, queryResultMetaData, columnIndex); String columnLabel = getColumnLabel(projectionsContext, queryResultMetaData, columnIndex); return TypedSPILoader.getService(QueryHeaderBuilder.class, databaseType.getType()).build(queryResultMetaData, database, columnName, columnLabel, columnIndex); } private String getColumnLabel(final ProjectionsContext projectionsContext, final QueryResultMetaData queryResultMetaData, final int columnIndex) throws SQLException { Projection projection = projectionsContext.getExpandProjections().get(columnIndex - 1); return DerivedColumn.isDerivedColumnName(projection.getColumnLabel()) ? projection.getExpression() : queryResultMetaData.getColumnLabel(columnIndex); } private String getColumnName(final ProjectionsContext projectionsContext, final QueryResultMetaData queryResultMetaData, final int columnIndex) throws SQLException { Projection projection = projectionsContext.getExpandProjections().get(columnIndex - 1); return projection instanceof ColumnProjection ? ((ColumnProjection) projection).getName() : queryResultMetaData.getColumnName(columnIndex); }}
package com.strongdata.shardata.executor.jdbc.response.header.query;import com.strongdata.shardata.executor.jdbc.response.header.ResponseHeader;import lombok.Getter;import lombok.RequiredArgsConstructor;import java.util.List;/** * Query response header. */@RequiredArgsConstructor@Getterpublic final class QueryResponseHeader implements ResponseHeader { private final List<QueryHeader> queryHeaders;}
package com.strongdata.shardata.executor.jdbc.response.header;/** * Response header. */public interface ResponseHeader {}
package com.strongdata.shardata.executor.jdbc.response.header.update;import com.strongdata.shardata.executor.jdbc.response.header.ResponseHeader;import lombok.AccessLevel;import lombok.Getter;import org.apache.shardingsphere.infra.executor.sql.execute.result.update.UpdateResult;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.util.*;/** * Update response header. */@Getterpublic final class UpdateResponseHeader implements ResponseHeader { private final SQLStatement sqlStatement; private final long lastInsertId; @Getter(AccessLevel.NONE) private final Collection<Integer> updateCounts = new LinkedList<>(); private long updateCount; public UpdateResponseHeader(final SQLStatement sqlStatement) { this(sqlStatement, Collections.emptyList(), Collections.emptyList()); } public UpdateResponseHeader(final SQLStatement sqlStatement, final Collection<UpdateResult> updateResults) { this(sqlStatement, updateResults, Collections.emptyList()); } public UpdateResponseHeader(final SQLStatement sqlStatement, final Collection<UpdateResult> updateResults, final Collection<Comparable<?>> autoIncrementGeneratedValues) { this.sqlStatement = sqlStatement; lastInsertId = getLastInsertId(updateResults, autoIncrementGeneratedValues); updateCount = updateResults.iterator().hasNext() ? updateResults.iterator().next().getUpdateCount() : 0; for (UpdateResult each : updateResults) { updateCounts.add(each.getUpdateCount()); } } private long getLastInsertId(final Collection<UpdateResult> updateResults, final Collection<Comparable<?>> autoIncrementGeneratedValues) { List<Long> lastInsertIds = new ArrayList<>(updateResults.size() + autoIncrementGeneratedValues.size()); for (UpdateResult each : updateResults) { if (each.getLastInsertId() > 0) { lastInsertIds.add(each.getLastInsertId()); } } for (Comparable<?> each : autoIncrementGeneratedValues) { if (each instanceof Number) { lastInsertIds.add(((Number) each).longValue()); } } return lastInsertIds.isEmpty() ? 0 : getMinLastInsertId(lastInsertIds); } private static long getMinLastInsertId(final List<Long> lastInsertIds) { Collections.sort(lastInsertIds); return lastInsertIds.iterator().next(); } /** * Merge updated counts. */ public void mergeUpdateCount() { updateCount = 0; for (int each : updateCounts) { updateCount += each; } }}
package com.strongdata.shardata.executor.jdbc.response;/** * Response type. */public enum ResponseType { QUERY, UPDATE}
package com.strongdata.shardata.executor.jdbc.sane;import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.metadata.RawQueryResultColumnMetaData;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.metadata.RawQueryResultMetaData;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.type.RawMemoryQueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.type.memory.row.MemoryQueryResultDataRow;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.SelectStatement;import java.sql.SQLException;import java.sql.Types;import java.util.Collections;import java.util.Optional;/** * Default Sane query result engine. */public final class DefaultSaneQueryResultEngine implements SaneQueryResultEngine { @Override public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) { return sqlStatement instanceof SelectStatement ? Optional.of(createDefaultQueryResult()) : Optional.empty(); } private QueryResult createDefaultQueryResult() { RawQueryResultColumnMetaData queryResultColumnMetaData = new RawQueryResultColumnMetaData("", "", "", Types.VARCHAR, "VARCHAR", 255, 0); MemoryQueryResultDataRow resultDataRow = new MemoryQueryResultDataRow(Collections.singletonList("1")); return new RawMemoryQueryResult(new RawQueryResultMetaData(Collections.singletonList(queryResultColumnMetaData)), Collections.singletonList(resultDataRow)); } @Override public boolean isDefault() { return true; }}
package com.strongdata.shardata.executor.jdbc.sane;import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;import org.apache.shardingsphere.infra.util.spi.annotation.SingletonSPI;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPI;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import java.sql.SQLException;import java.util.Optional;/** * Sane query result engine. */@SingletonSPIpublic interface SaneQueryResultEngine extends TypedSPI { /** * Get sane query result. * * @param sqlStatement SQL statement * @param ex SQL exception * @return sane execute result */ Optional<ExecuteResult> getSaneQueryResult(SQLStatement sqlStatement, SQLException ex);}
package com.strongdata.shardata.executor.jdbc.statement;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.executor.sql.context.ExecutionUnit;import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.ExecutorJDBCStatementManager;import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.StatementOption;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import java.sql.*;import java.util.List;import java.util.Optional;/** * JDBC backend statement. */public final class JDBCBackendStatement implements ExecutorJDBCStatementManager { @Override public Statement createStorageResource(final Connection connection, final ConnectionMode connectionMode, final StatementOption option, final DatabaseType databaseType) throws SQLException { Statement result = connection.createStatement(); if (ConnectionMode.MEMORY_STRICTLY == connectionMode) { setFetchSize(result, databaseType); } return result; } @Override public Statement createStorageResource(final ExecutionUnit executionUnit, final Connection connection, final ConnectionMode connectionMode, final StatementOption option, final DatabaseType databaseType) throws SQLException { String sql = executionUnit.getSqlUnit().getSql(); List<Object> params = executionUnit.getSqlUnit().getParameters(); PreparedStatement result = option.isReturnGeneratedKeys() ? connection.prepareStatement(executionUnit.getSqlUnit().getSql(), Statement.RETURN_GENERATED_KEYS) : connection.prepareStatement(sql); for (int i = 0; i < params.size(); i++) { Object param = params.get(i); result.setObject(i + 1, param); } if (ConnectionMode.MEMORY_STRICTLY == connectionMode) { setFetchSize(result, databaseType); } return result; } private void setFetchSize(final Statement statement, final DatabaseType databaseType) throws SQLException { Optional<StatementMemoryStrictlyFetchSizeSetter> fetchSizeSetter = TypedSPILoader.findService(StatementMemoryStrictlyFetchSizeSetter.class, databaseType.getType()); if (fetchSizeSetter.isPresent()) { fetchSizeSetter.get().setFetchSize(statement); } }}
package com.strongdata.shardata.executor.jdbc.statement;import org.apache.shardingsphere.infra.util.spi.annotation.SingletonSPI;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPI;import java.sql.SQLException;import java.sql.Statement;/** * Statement memory strictly fetch size setter. */@SingletonSPIpublic interface StatementMemoryStrictlyFetchSizeSetter extends TypedSPI { /** * Set fetch size. * * @param statement statement to be set * @throws SQLException SQL exception */ void setFetchSize(Statement statement) throws SQLException;}
package com.strongdata.shardata.executor.jdbc.transaction;import com.strongdata.shardata.executor.connector.ConnectionPool;import com.strongdata.shardata.executor.connector.TransactionManager;import com.strongdata.shardata.executor.context.ProxyContext;import org.apache.shardingsphere.infra.context.transaction.TransactionConnectionContext;import org.apache.shardingsphere.infra.util.spi.ShardingSphereServiceLoader;import org.apache.shardingsphere.transaction.ConnectionSavepointManager;import org.apache.shardingsphere.transaction.ShardingSphereTransactionManagerEngine;import org.apache.shardingsphere.transaction.api.TransactionType;import org.apache.shardingsphere.transaction.rule.TransactionRule;import org.apache.shardingsphere.transaction.spi.ShardingSphereTransactionManager;import org.apache.shardingsphere.transaction.spi.TransactionHook;import java.sql.Connection;import java.sql.SQLException;import java.util.Collection;import java.util.Iterator;import java.util.LinkedList;/** * Backend transaction manager. */public final class BackendTransactionManager implements TransactionManager { private final ConnectionPool connection; private final TransactionType transactionType; private final LocalTransactionManager localTransactionManager; private final ShardingSphereTransactionManager shardingSphereTransactionManager; private final Collection<TransactionHook> transactionHooks; public BackendTransactionManager(final ConnectionPool connectionPool) { connection = connectionPool; transactionType = connection.getConnectionSession().getTransactionStatus().getTransactionType(); localTransactionManager = new LocalTransactionManager(connectionPool); TransactionRule transactionRule = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(TransactionRule.class); ShardingSphereTransactionManagerEngine engine = transactionRule.getResource(); shardingSphereTransactionManager = null == engine ? null : engine.getTransactionManager(transactionType); transactionHooks = ShardingSphereServiceLoader.getServiceInstances(TransactionHook.class); } @Override public void begin() { if (!connection.getConnectionSession().getTransactionStatus().isInTransaction()) { connection.getConnectionSession().getTransactionStatus().setInTransaction(true); getTransactionContext().setInTransaction(true); connection.closeHandlers(true); connection.closeConnections(false); } for (TransactionHook each : transactionHooks) { each.beforeBegin(getTransactionContext()); } if (TransactionType.LOCAL == transactionType || null == shardingSphereTransactionManager) { localTransactionManager.begin(); } else { shardingSphereTransactionManager.begin(); } for (TransactionHook each : transactionHooks) { each.afterBegin(getTransactionContext()); } } @Override public void commit() throws SQLException { for (TransactionHook each : transactionHooks) { each.beforeCommit(connection.getCachedConnections().values(), getTransactionContext(), ProxyContext.getInstance().getContextManager().getInstanceContext().getLockContext()); } if (connection.getConnectionSession().getTransactionStatus().isInTransaction()) { try { if (TransactionType.LOCAL == transactionType || null == shardingSphereTransactionManager) { localTransactionManager.commit(); } else { shardingSphereTransactionManager.commit(connection.getConnectionSession().getTransactionStatus().isRollbackOnly()); } } finally { for (TransactionHook each : transactionHooks) { each.afterCommit(connection.getCachedConnections().values(), getTransactionContext(), ProxyContext.getInstance().getContextManager().getInstanceContext().getLockContext()); } connection.getConnectionSession().getTransactionStatus().setInTransaction(false); connection.getConnectionSession().getTransactionStatus().setRollbackOnly(false); connection.getConnectionSession().getConnectionContext().clearTransactionConnectionContext(); connection.getConnectionSession().getConnectionContext().clearCursorConnectionContext(); } } } @Override public void rollback() throws SQLException { for (TransactionHook each : transactionHooks) { each.beforeRollback(connection.getCachedConnections().values(), getTransactionContext()); } if (connection.getConnectionSession().getTransactionStatus().isInTransaction()) { try { if (TransactionType.LOCAL == transactionType || null == shardingSphereTransactionManager) { localTransactionManager.rollback(); } else { shardingSphereTransactionManager.rollback(); } } finally { for (TransactionHook each : transactionHooks) { each.afterRollback(connection.getCachedConnections().values(), getTransactionContext()); } connection.getConnectionSession().getTransactionStatus().setInTransaction(false); connection.getConnectionSession().getTransactionStatus().setRollbackOnly(false); connection.getConnectionSession().getConnectionContext().clearTransactionConnectionContext(); connection.getConnectionSession().getConnectionContext().clearCursorConnectionContext(); } } } private TransactionConnectionContext getTransactionContext() { return connection.getConnectionSession().getConnectionContext().getTransactionConnectionContext(); } @Override public void setSavepoint(final String savepointName) throws SQLException { for (Connection each : connection.getCachedConnections().values()) { ConnectionSavepointManager.getInstance().setSavepoint(each, savepointName); } connection.getConnectionPostProcessors().add(target -> { try { ConnectionSavepointManager.getInstance().setSavepoint(target, savepointName); } catch (final SQLException ex) { throw new RuntimeException(ex); } }); } @Override public void rollbackTo(final String savepointName) throws SQLException { Collection<SQLException> result = new LinkedList<>(); for (Connection each : connection.getCachedConnections().values()) { try { ConnectionSavepointManager.getInstance().rollbackToSavepoint(each, savepointName); } catch (final SQLException ex) { result.add(ex); } } if (result.isEmpty() && connection.getConnectionSession().getTransactionStatus().isRollbackOnly()) { connection.getConnectionSession().getTransactionStatus().setRollbackOnly(false); } throwSQLExceptionIfNecessary(result); } @Override public void releaseSavepoint(final String savepointName) throws SQLException { Collection<SQLException> result = new LinkedList<>(); for (Connection each : connection.getCachedConnections().values()) { try { ConnectionSavepointManager.getInstance().releaseSavepoint(each, savepointName); } catch (final SQLException ex) { result.add(ex); } } throwSQLExceptionIfNecessary(result); } private void throwSQLExceptionIfNecessary(final Collection<SQLException> exceptions) throws SQLException { if (exceptions.isEmpty()) { return; } Iterator<SQLException> iterator = exceptions.iterator(); SQLException firstException = iterator.next(); while (iterator.hasNext()) { firstException.setNextException(iterator.next()); } throw firstException; }}
package com.strongdata.shardata.executor.jdbc.transaction;import com.strongdata.shardata.executor.connector.ConnectionPool;import lombok.RequiredArgsConstructor;import org.apache.shardingsphere.transaction.ConnectionSavepointManager;import java.sql.Connection;import java.sql.SQLException;import java.util.Collection;import java.util.Iterator;import java.util.LinkedList;/** * Local transaction manager. */@RequiredArgsConstructorpublic final class LocalTransactionManager { private final ConnectionPool connection; /** * Begin transaction. */ public void begin() { connection.getConnectionPostProcessors().add(target -> { try { target.setAutoCommit(false); } catch (final SQLException ex) { throw new RuntimeException(ex); } }); } /** * Commit transaction. * * @throws SQLException SQL exception */ public void commit() throws SQLException { Collection<SQLException> exceptions = new LinkedList<>(); if (connection.getConnectionSession().getTransactionStatus().isRollbackOnly()) { exceptions.addAll(rollbackConnections()); } else { exceptions.addAll(commitConnections()); } throwSQLExceptionIfNecessary(exceptions); } private Collection<SQLException> commitConnections() { Collection<SQLException> result = new LinkedList<>(); for (Connection each : connection.getCachedConnections().values()) { try { each.commit(); } catch (final SQLException ex) { result.add(ex); } finally { ConnectionSavepointManager.getInstance().transactionFinished(each); } } return result; } /** * Rollback transaction. * * @throws SQLException SQL exception */ public void rollback() throws SQLException { if (connection.getConnectionSession().getTransactionStatus().isInTransaction()) { Collection<SQLException> exceptions = new LinkedList<>(rollbackConnections()); throwSQLExceptionIfNecessary(exceptions); } } private Collection<SQLException> rollbackConnections() { Collection<SQLException> result = new LinkedList<>(); for (Connection each : connection.getCachedConnections().values()) { try { each.rollback(); } catch (final SQLException ex) { result.add(ex); } finally { ConnectionSavepointManager.getInstance().transactionFinished(each); } } return result; } private void throwSQLExceptionIfNecessary(final Collection<SQLException> exceptions) throws SQLException { if (exceptions.isEmpty()) { return; } Iterator<SQLException> iterator = exceptions.iterator(); SQLException firstException = iterator.next(); while (iterator.hasNext()) { firstException.setNextException(iterator.next()); } throw firstException; }}
package com.strongdata.shardata.executor.jdbc.type.mysql.jdbc.statement;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.jdbc.statement.StatementMemoryStrictlyFetchSizeSetter;import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;import java.sql.SQLException;import java.sql.Statement;/** * Statement memory strictly fetch size setter for MySQL. */public final class MySQLStatementMemoryStrictlyFetchSizeSetter implements StatementMemoryStrictlyFetchSizeSetter { @Override public void setFetchSize(final Statement statement) throws SQLException { int configuredFetchSize = ProxyContext.getInstance() .getContextManager().getMetaDataContexts().getMetaData().getProps().<Integer>getValue(ConfigurationPropertyKey.PROXY_BACKEND_QUERY_FETCH_SIZE); statement.setFetchSize(ConfigurationPropertyKey.PROXY_BACKEND_QUERY_FETCH_SIZE.getDefaultValue().equals(String.valueOf(configuredFetchSize)) ? Integer.MIN_VALUE : configuredFetchSize); } @Override public String getType() { return "MySQL"; }}
package com.strongdata.shardata.executor.jdbc.type.mysql.sane;import lombok.AccessLevel;import lombok.NoArgsConstructor;import java.util.HashMap;import java.util.Map;/** * MySQL default variable. */@NoArgsConstructor(access = AccessLevel.PRIVATE)public final class MySQLDefaultVariable { private static final Map<String, String> VARIABLES = new HashMap<>(20, 1); static { VARIABLES.put("auto_increment_increment", "1"); VARIABLES.put("character_set_client", "utf8"); VARIABLES.put("character_set_connection", "utf8"); VARIABLES.put("character_set_results", "utf8"); VARIABLES.put("character_set_server", "utf8"); VARIABLES.put("collation_server", "utf8_general_ci"); VARIABLES.put("collation_connection", "utf8_general_ci"); VARIABLES.put("init_connect", ""); VARIABLES.put("interactive_timeout", "28800"); VARIABLES.put("license", "GPL"); VARIABLES.put("lower_case_table_names", "2"); VARIABLES.put("max_allowed_packet", "4194304"); VARIABLES.put("net_buffer_length", "16384"); VARIABLES.put("net_write_timeout", "60"); VARIABLES.put("sql_mode", "STRICT_TRANS_TABLES"); VARIABLES.put("system_time_zone", "CST"); VARIABLES.put("time_zone", "SYSTEM"); VARIABLES.put("transaction_isolation", "REPEATABLE-READ"); VARIABLES.put("wait_timeout", "28800"); VARIABLES.put("@@session.transaction_read_only", "0"); } /** * Judge whether contains variable. * * @param variableName variable name * @return contains variable or not */ public static boolean containsVariable(final String variableName) { return VARIABLES.containsKey(variableName); } /** * Get variable value. * * @param variableName variable name * @return variable value */ public static String getVariable(final String variableName) { return VARIABLES.get(variableName); }}
package com.strongdata.shardata.executor.jdbc.type.mysql.sane;import com.strongdata.shardata.executor.jdbc.sane.SaneQueryResultEngine;import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.metadata.RawQueryResultColumnMetaData;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.metadata.RawQueryResultMetaData;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.raw.type.RawMemoryQueryResult;import org.apache.shardingsphere.infra.executor.sql.execute.result.query.type.memory.row.MemoryQueryResultDataRow;import org.apache.shardingsphere.infra.executor.sql.execute.result.update.UpdateResult;import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ExpressionProjectionSegment;import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ProjectionSegment;import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.SelectStatement;import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLSetStatement;import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLShowOtherStatement;import java.sql.SQLException;import java.sql.Types;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Optional;/** * Sane query result engine for MySQL. */public final class MySQLSaneQueryResultEngine implements SaneQueryResultEngine { private static final int ER_PARSE_ERROR = 1064; @Override public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) { if (ER_PARSE_ERROR == ex.getErrorCode()) { return Optional.empty(); } if (sqlStatement instanceof SelectStatement) { return createQueryResult((SelectStatement) sqlStatement); } if (sqlStatement instanceof MySQLShowOtherStatement) { return Optional.of(createQueryResult((MySQLShowOtherStatement) sqlStatement)); } if (sqlStatement instanceof MySQLSetStatement) { return Optional.of(new UpdateResult(0, 0)); } return Optional.empty(); } private Optional<ExecuteResult> createQueryResult(final SelectStatement sqlStatement) { if (null != sqlStatement.getFrom()) { return Optional.empty(); } List<RawQueryResultColumnMetaData> queryResultColumnMetaDataList = new ArrayList<>(sqlStatement.getProjections().getProjections().size()); List<Object> data = new ArrayList<>(sqlStatement.getProjections().getProjections().size()); for (ProjectionSegment each : sqlStatement.getProjections().getProjections()) { if (each instanceof ExpressionProjectionSegment) { String text = ((ExpressionProjectionSegment) each).getText(); String alias = ((ExpressionProjectionSegment) each).getAlias().orElse(((ExpressionProjectionSegment) each).getText()); queryResultColumnMetaDataList.add(createRawQueryResultColumnMetaData(text, alias)); data.add(MySQLDefaultVariable.containsVariable(alias) ? MySQLDefaultVariable.getVariable(alias) : "1"); } } return queryResultColumnMetaDataList.isEmpty() ? Optional.empty() : Optional.of(new RawMemoryQueryResult(new RawQueryResultMetaData(queryResultColumnMetaDataList), Collections.singletonList(new MemoryQueryResultDataRow(data)))); } private QueryResult createQueryResult(final MySQLShowOtherStatement sqlStatement) { RawQueryResultColumnMetaData queryResultColumnMetaData = createRawQueryResultColumnMetaData("", ""); MemoryQueryResultDataRow resultDataRow = new MemoryQueryResultDataRow(Collections.singletonList("1")); return new RawMemoryQueryResult(new RawQueryResultMetaData(Collections.singletonList(queryResultColumnMetaData)), Collections.singletonList(resultDataRow)); } private RawQueryResultColumnMetaData createRawQueryResultColumnMetaData(final String name, final String label) { return new RawQueryResultColumnMetaData("", name, label, Types.VARCHAR, "VARCHAR", 255, 0); } @Override public String getType() { return "MySQL"; }}
package com.strongdata.shardata.executor.logger;import lombok.AccessLevel;import lombok.NoArgsConstructor;@NoArgsConstructor(access = AccessLevel.PRIVATE)public final class LoggingConstants { public static final String SQL_SHOW = "sql-show"; public static final String SQL_SIMPLE = "sql-simple"; public static final String SQL_LOG_TOPIC = "ShardingSphere-SQL"; public static final String SQL_LOG_ENABLE = "enable"; public static final String SQL_LOG_SIMPLE = "simple"; public static final String SQL_SHOW_VARIABLE_NAME = "sql_show"; public static final String SQL_SIMPLE_VARIABLE_NAME = "sql_simple";}
package com.strongdata.shardata.executor.logger;import ch.qos.logback.classic.Level;import ch.qos.logback.classic.Logger;import ch.qos.logback.classic.LoggerContext;import ch.qos.logback.classic.encoder.PatternLayoutEncoder;import ch.qos.logback.classic.spi.ILoggingEvent;import ch.qos.logback.core.Appender;import ch.qos.logback.core.FileAppender;import ch.qos.logback.core.OutputStreamAppender;import ch.qos.logback.core.util.DynamicClassLoadingException;import ch.qos.logback.core.util.IncompatibleClassException;import ch.qos.logback.core.util.OptionHelper;import lombok.AccessLevel;import lombok.NoArgsConstructor;import lombok.SneakyThrows;import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;import org.apache.shardingsphere.logging.config.LoggingRuleConfiguration;import org.apache.shardingsphere.logging.logger.ShardingSphereAppender;import org.apache.shardingsphere.logging.logger.ShardingSphereLogger;import org.apache.shardingsphere.logging.rule.LoggingRule;import org.slf4j.LoggerFactory;import java.util.Collection;import java.util.Iterator;import java.util.Optional;import java.util.Properties;/** * Logging utils. */@NoArgsConstructor(access = AccessLevel.PRIVATE)public class LoggingUtils { /** * Get ShardingSphere-SQL logger. * * @param globalRuleMetaData ShardingSphere global rule metaData * @return ShardingSphere-SQL logger */ public static Optional<ShardingSphereLogger> getSQLLogger(final ShardingSphereRuleMetaData globalRuleMetaData) { return globalRuleMetaData.findSingleRule(LoggingRule.class).isPresent() ? getSQLLogger(globalRuleMetaData.getSingleRule(LoggingRule.class).getConfiguration()) : Optional.empty(); } /** * Get ShardingSphere-SQL logger. * * @param loggingRuleConfiguration logging global rule configuration * @return ShardingSphere-SQL logger */ public static Optional<ShardingSphereLogger> getSQLLogger(final LoggingRuleConfiguration loggingRuleConfiguration) { return loggingRuleConfiguration.getLoggers().stream() .filter(each -> LoggingConstants.SQL_LOG_TOPIC.equalsIgnoreCase(each.getLoggerName())).findFirst(); } /** * Synchronize the log-related configuration in logging rule and props. * Use the configuration in the logging rule first. * * @param loggingRuleConfiguration logging global rule configuration * @param props configuration properties */ public static void syncLoggingConfig(final LoggingRuleConfiguration loggingRuleConfiguration, final ConfigurationProperties props) { LoggingUtils.getSQLLogger(loggingRuleConfiguration).ifPresent(option -> { Properties loggerProperties = option.getProps(); syncPropsToLoggingRule(loggerProperties, props); syncLoggingRuleToProps(loggerProperties, props); }); } private static void syncPropsToLoggingRule(final Properties loggerProperties, final ConfigurationProperties props) { if (!loggerProperties.containsKey(LoggingConstants.SQL_LOG_ENABLE) && props.getProps().containsKey(LoggingConstants.SQL_SHOW)) { loggerProperties.setProperty(LoggingConstants.SQL_LOG_ENABLE, props.getProps().get(LoggingConstants.SQL_SHOW).toString()); } if (!loggerProperties.containsKey(LoggingConstants.SQL_LOG_SIMPLE) && props.getProps().containsKey(LoggingConstants.SQL_SIMPLE)) { loggerProperties.setProperty(LoggingConstants.SQL_LOG_SIMPLE, props.getProps().get(LoggingConstants.SQL_SIMPLE).toString()); } } private static void syncLoggingRuleToProps(final Properties loggerProperties, final ConfigurationProperties props) { if (loggerProperties.containsKey(LoggingConstants.SQL_LOG_ENABLE)) { props.getProps().setProperty(LoggingConstants.SQL_SHOW, loggerProperties.get(LoggingConstants.SQL_LOG_ENABLE).toString()); } if (loggerProperties.containsKey(LoggingConstants.SQL_LOG_SIMPLE)) { props.getProps().setProperty(LoggingConstants.SQL_SIMPLE, loggerProperties.get(LoggingConstants.SQL_LOG_SIMPLE).toString()); } } /** * Refresh logger context with logging rule. * * @param loggingRuleConfiguration logging global rule configuration */ public static void refreshLogger(final LoggingRuleConfiguration loggingRuleConfiguration) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); configLoggers(loggingRuleConfiguration, loggerContext); startRootLogger(loggerContext); } private static void configLoggers(final LoggingRuleConfiguration loggingRuleConfiguration, final LoggerContext loggerContext) { Collection<ShardingSphereLogger> loggers = loggingRuleConfiguration.getLoggers(); loggers.forEach(each -> { Logger logger = loggerContext.getLogger(each.getLoggerName()); logger.setLevel(Level.valueOf(each.getLevel())); logger.setAdditive(each.getAdditivity()); addAppender(logger, loggingRuleConfiguration, each.getAppenderName()); }); } @SneakyThrows({IncompatibleClassException.class, DynamicClassLoadingException.class}) @SuppressWarnings("unchecked") private static void addAppender(final Logger logger, final LoggingRuleConfiguration loggingRuleConfiguration, final String appenderName) { if (null == appenderName) { return; } Optional<ShardingSphereAppender> shardingSphereAppenderOptional = loggingRuleConfiguration.getAppenders().stream().filter(each -> appenderName.equals(each.getAppenderName())).findFirst(); if (shardingSphereAppenderOptional.isPresent()) { ShardingSphereAppender shardingSphereAppender = shardingSphereAppenderOptional.get(); Appender<ILoggingEvent> appender = (Appender<ILoggingEvent>) OptionHelper.instantiateByClassName(shardingSphereAppender.getAppenderClass(), Appender.class, logger.getLoggerContext()); appender.setContext(logger.getLoggerContext()); appender.setName(appenderName); addEncoder(appender, shardingSphereAppender); appender.start(); logger.detachAndStopAllAppenders(); logger.addAppender(appender); } } private static void addEncoder(final Appender<ILoggingEvent> appender, final ShardingSphereAppender shardingSphereAppender) { if (appender instanceof OutputStreamAppender) { OutputStreamAppender<ILoggingEvent> outputStreamAppender = (OutputStreamAppender<ILoggingEvent>) appender; PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder(); patternLayoutEncoder.setContext(appender.getContext()); patternLayoutEncoder.setPattern(shardingSphereAppender.getPattern()); outputStreamAppender.setEncoder(patternLayoutEncoder); setFileOutput(outputStreamAppender, shardingSphereAppender); patternLayoutEncoder.start(); } } private static void setFileOutput(final OutputStreamAppender<ILoggingEvent> outputStreamAppender, final ShardingSphereAppender shardingSphereAppender) { if (outputStreamAppender instanceof FileAppender) { FileAppender<ILoggingEvent> fileAppender = (FileAppender<ILoggingEvent>) outputStreamAppender; fileAppender.setFile(shardingSphereAppender.getFile()); } } private static void startRootLogger(final LoggerContext loggerContext) { Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); Iterator<Appender<ILoggingEvent>> appenderIterator = rootLogger.iteratorForAppenders(); while (appenderIterator.hasNext()) { appenderIterator.next().start(); } }}
package com.strongdata.shardata.executor.meta.checker;import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.algorithm.MissingRequiredAlgorithmException;import org.apache.shardingsphere.distsql.handler.exception.rule.DuplicateRuleException;import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;import org.apache.shardingsphere.encrypt.api.config.rule.EncryptColumnRuleConfiguration;import org.apache.shardingsphere.encrypt.api.config.rule.EncryptTableRuleConfiguration;import org.apache.shardingsphere.encrypt.spi.EncryptAlgorithm;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import java.util.Collection;import java.util.LinkedList;import java.util.Map;import java.util.Objects;import java.util.stream.Collectors;/** * Encrypt rule configuration import checker. */public final class EncryptRuleConfigurationChecker { /** * Check encrypt rule configuration. * * @param database database * @param currentRuleConfig current rule configuration */ public void check(final ShardingSphereDatabase database, final EncryptRuleConfiguration currentRuleConfig) { if (null == database || null == currentRuleConfig) { return; } checkTables(currentRuleConfig, database.getName()); checkEncryptors(currentRuleConfig); checkTableEncryptorsExisted(currentRuleConfig, database.getName()); } private void checkTables(final EncryptRuleConfiguration currentRuleConfig, final String databaseName) { Collection<String> tableNames = currentRuleConfig.getTables().stream().map(EncryptTableRuleConfiguration::getName).collect(Collectors.toList()); Collection<String> duplicatedTables = tableNames.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedTables.isEmpty(), () -> new DuplicateRuleException("ENCRYPT", databaseName, duplicatedTables)); } private void checkEncryptors(final EncryptRuleConfiguration currentRuleConfig) { Collection<String> notExistedAlgorithms = currentRuleConfig.getEncryptors().values().stream().map(AlgorithmConfiguration::getType) .filter(each -> !TypedSPILoader.contains(EncryptAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedAlgorithms.isEmpty(), () -> new InvalidAlgorithmConfigurationException("Encryptors", notExistedAlgorithms)); } private void checkTableEncryptorsExisted(final EncryptRuleConfiguration configuration, final String databaseName) { Collection<EncryptColumnRuleConfiguration> columns = new LinkedList<>(); configuration.getTables().forEach(each -> columns.addAll(each.getColumns())); Collection<String> notExistedEncryptors = columns.stream().map(EncryptColumnRuleConfiguration::getEncryptorName).collect(Collectors.toList()); notExistedEncryptors.addAll(columns.stream().map(EncryptColumnRuleConfiguration::getLikeQueryEncryptorName).filter(Objects::nonNull).collect(Collectors.toList())); notExistedEncryptors.addAll(columns.stream().map(EncryptColumnRuleConfiguration::getAssistedQueryEncryptorName).filter(Objects::nonNull).collect(Collectors.toList())); Collection<String> encryptors = configuration.getEncryptors().keySet(); notExistedEncryptors.removeIf(encryptors::contains); ShardingSpherePreconditions.checkState(notExistedEncryptors.isEmpty(), () -> new MissingRequiredAlgorithmException(databaseName, notExistedEncryptors)); }}
package com.strongdata.shardata.executor.meta.checker;import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.algorithm.MissingRequiredAlgorithmException;import org.apache.shardingsphere.distsql.handler.exception.rule.DuplicateRuleException;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.mask.api.config.MaskRuleConfiguration;import org.apache.shardingsphere.mask.api.config.rule.MaskColumnRuleConfiguration;import org.apache.shardingsphere.mask.api.config.rule.MaskTableRuleConfiguration;import org.apache.shardingsphere.mask.spi.MaskAlgorithm;import java.util.Collection;import java.util.LinkedList;import java.util.Map;import java.util.stream.Collectors;/** * Mask rule configuration import checker. */public final class MaskRuleConfigurationChecker { /** * Check mask rule configuration. * * @param database database * @param currentRuleConfig current rule configuration */ public void check(final ShardingSphereDatabase database, final MaskRuleConfiguration currentRuleConfig) { if (null == database || null == currentRuleConfig) { return; } checkTables(currentRuleConfig, database.getName()); checkMaskAlgorithms(currentRuleConfig); checkMaskAlgorithmsExisted(currentRuleConfig, database.getName()); } private void checkTables(final MaskRuleConfiguration currentRuleConfig, final String databaseName) { Collection<String> tableNames = currentRuleConfig.getTables().stream().map(MaskTableRuleConfiguration::getName).collect(Collectors.toList()); Collection<String> duplicatedTables = tableNames.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedTables.isEmpty(), () -> new DuplicateRuleException("MASK", databaseName, duplicatedTables)); } private void checkMaskAlgorithms(final MaskRuleConfiguration currentRuleConfig) { Collection<String> notExistedAlgorithms = currentRuleConfig.getMaskAlgorithms().values().stream().map(AlgorithmConfiguration::getType) .filter(each -> !TypedSPILoader.contains(MaskAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedAlgorithms.isEmpty(), () -> new InvalidAlgorithmConfigurationException("Mask algorithms", notExistedAlgorithms)); } private void checkMaskAlgorithmsExisted(final MaskRuleConfiguration currentRuleConfig, final String databaseName) { Collection<MaskColumnRuleConfiguration> columns = new LinkedList<>(); currentRuleConfig.getTables().forEach(each -> columns.addAll(each.getColumns())); Collection<String> notExistedAlgorithms = columns.stream().map(MaskColumnRuleConfiguration::getMaskAlgorithm).collect(Collectors.toList()); Collection<String> maskAlgorithms = currentRuleConfig.getMaskAlgorithms().keySet(); notExistedAlgorithms.removeIf(maskAlgorithms::contains); ShardingSpherePreconditions.checkState(notExistedAlgorithms.isEmpty(), () -> new MissingRequiredAlgorithmException(databaseName, notExistedAlgorithms)); }}
package com.strongdata.shardata.executor.meta.checker;import com.google.common.collect.LinkedListMultimap;import com.google.common.collect.Multimap;import com.strongdata.shardata.common.exception.database.DatabaseCreateException;import com.strongdata.shardata.common.exception.database.DatabaseDropException;import com.strongdata.shardata.common.exception.storageunit.*;import com.strongdata.shardata.executor.config.property.DataSourceConfigurations;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.meta.dialect.DBType;import org.apache.shardingsphere.infra.database.metadata.url.JdbcUrl;import org.apache.shardingsphere.infra.database.metadata.url.StandardJdbcUrlParser;import org.apache.shardingsphere.infra.datanode.DataNode;import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;import org.apache.shardingsphere.infra.datasource.props.DataSourcePropertiesCreator;import org.apache.shardingsphere.infra.datasource.props.DataSourcePropertiesValidator;import org.apache.shardingsphere.infra.rule.identifier.type.DataNodeContainedRule;import org.apache.shardingsphere.infra.rule.identifier.type.DataSourceContainedRule;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;import org.apache.shardingsphere.single.rule.SingleRule;import javax.sql.DataSource;import java.util.*;import java.util.stream.Collectors;public class MetaDataConfigurationChecker { public void checkDatabase(final String databaseName) { ShardingSpherePreconditions.checkNotNull(databaseName, () -> new UnsupportedSQLOperationException("databaseName is required,can not be null!")); if (ProxyContext.getInstance().databaseExists(databaseName)) { ShardingSpherePreconditions.checkState(ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources().isEmpty(), () -> new DatabaseCreateException(databaseName)); } } public void checkDropDatabase(final String databaseName) { ShardingSpherePreconditions.checkNotNull(databaseName, () -> new UnsupportedSQLOperationException("databaseName is required,can not be null!")); ShardingSpherePreconditions.checkState(ProxyContext.getInstance().databaseExists(databaseName), () -> new DatabaseDropException(databaseName)); } public void checkDatabaseType(final String dbType) { DBType type=null; if(dbType != null){ try { type=DBType.valueOf(dbType); }catch (IllegalArgumentException e){ } ShardingSpherePreconditions.checkNotNull(type, () -> new UnsupportedSQLOperationException(String.format("Database type `%s` is not supported",dbType))); } } public void checkRegisterStorageUnits(final String databaseName,final Map<String, DataSourceProperties> dataSourcePropertiesMaps){ Collection<String> dataSourceNames = dataSourcePropertiesMaps.keySet(); checkDuplicatedStorageUnitNames(dataSourceNames); checkStorageUnitNameExisted(databaseName,dataSourceNames); checkLogicalStorageUnitNameExisted(databaseName,dataSourceNames); checkDataSource(dataSourcePropertiesMaps); } public void checkUpdateStorageUnits(final String databaseName, final Map<String, DataSourceConfigurations> dataSourcePropertiesMap) { Collection<String> dataSourceNames = dataSourcePropertiesMap.keySet(); checkDuplicatedStorageUnitNames(dataSourceNames); checkStorageUnitNameNotExisted(databaseName, dataSourceNames); checkDatabase(databaseName, dataSourcePropertiesMap); } public void checkDropStorageUnits(final String databaseName, final Collection<String> storageUnitNames) { checkExisted(databaseName, storageUnitNames); checkInUsed(databaseName, storageUnitNames); } private void checkDataSource(final Map<String, DataSourceProperties> dataSourcePropertiesMap) { Collection<String> errorMessages = new DataSourcePropertiesValidator().validate(dataSourcePropertiesMap); if (!errorMessages.isEmpty()) { throw new InvalidStorageUnitsException(errorMessages); } } private void checkDuplicatedStorageUnitNames(final Collection<String> storageUnitNames) { Collection<String> duplicatedStorageUnitNames = storageUnitNames.stream().filter(each -> storageUnitNames.stream().filter(each::equals).count() > 1).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(duplicatedStorageUnitNames.isEmpty(), () -> new DuplicateStorageUnitException(duplicatedStorageUnitNames)); } private void checkStorageUnitNameNotExisted(final String databaseName, final Collection<String> storageUnitNames) { Map<String, DataSource> storageUnits = ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources(); Collection<String> notExistedStorageUnitNames = storageUnitNames.stream().filter(each -> !storageUnits.containsKey(each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedStorageUnitNames.isEmpty(), () -> new MissingStorageUnitsException(databaseName, notExistedStorageUnitNames)); } private void checkStorageUnitNameExisted(final String databaseName, final Collection<String> storageUnitNames) { Map<String, DataSource> storageUnits = ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources(); Collection<String> existedStorageUnitNames = storageUnitNames.stream().filter(each -> storageUnits.containsKey(each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(existedStorageUnitNames.isEmpty(), () -> new AlreadyExistedStorageUnitsException(databaseName, existedStorageUnitNames)); } private void checkLogicalStorageUnitNameExisted(final String databaseName, final Collection<String> dataSourceNames){ Collection<String> logicalDataSourceNames = ProxyContext.getInstance().getDatabase(databaseName).getRuleMetaData().findRules(DataSourceContainedRule.class) .stream().map(each -> each.getDataSourceMapper().keySet()).flatMap(Collection::stream).collect(Collectors.toList()); if (logicalDataSourceNames.isEmpty()) { return; } Collection<String> duplicatedLogicalDataSourceNames = dataSourceNames.stream().filter(logicalDataSourceNames::contains).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedLogicalDataSourceNames.isEmpty(), () -> new InvalidStorageUnitsException(Collections.singleton(String.format("%s already existed in rule", duplicatedLogicalDataSourceNames)))); } private void checkDatabase(final String databaseName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap) { Map<String, DataSource> storageUnits = ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources(); Collection<String> invalidStorageUnitNames = dataSourceConfigurationsMap.entrySet().stream() .filter(each -> !isIdenticalDatabase(each.getValue(), storageUnits.get(each.getKey()))).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(invalidStorageUnitNames.isEmpty(), () -> new InvalidStorageUnitsException(Collections.singleton(String.format("Cannot alter the database of %s", invalidStorageUnitNames)))); } private boolean isIdenticalDatabase(final DataSourceConfigurations dataSourceConfigurations, final DataSource dataSource) { String url = String.valueOf(DataSourcePropertiesCreator.create(dataSource).getConnectionPropertySynonyms().getStandardProperties().get("url")); JdbcUrl oldJdbcUrl = new StandardJdbcUrlParser().parse(url); JdbcUrl newJdbcUrl = new StandardJdbcUrlParser().parse(dataSourceConfigurations.getUrl()); return Objects.equals(newJdbcUrl.getHostname(), oldJdbcUrl.getHostname()) && Objects.equals(String.valueOf(newJdbcUrl.getPort()), String.valueOf(oldJdbcUrl.getPort())) && Objects.equals(newJdbcUrl.getDatabase(), oldJdbcUrl.getDatabase()); } private void checkExisted(final String databaseName, final Collection<String> storageUnitNames) { Map<String, DataSource> dataSources = ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources(); Collection<String> notExistedStorageUnits = storageUnitNames.stream().filter(each -> !dataSources.containsKey(each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedStorageUnits.isEmpty(), () -> new MissingStorageUnitsException(databaseName, notExistedStorageUnits)); } private void checkInUsed(final String databaseName, final Collection<String> storageUnitNames) { Multimap<String, String> inUsedStorageUnits = getInUsedResources(databaseName); Collection<String> inUsedStorageUnitNames = inUsedStorageUnits.keySet(); inUsedStorageUnitNames.retainAll(storageUnitNames); if (!inUsedStorageUnitNames.isEmpty()) { checkInUsedIgnoreSingleTables(new HashSet<>(inUsedStorageUnitNames), inUsedStorageUnits); } } private Multimap<String, String> getInUsedResources(final String databaseName) { Multimap<String, String> result = LinkedListMultimap.create(); for (DataSourceContainedRule each : ProxyContext.getInstance().getDatabase(databaseName).getRuleMetaData().findRules(DataSourceContainedRule.class)) { getInUsedResourceNames(each).forEach(eachResource -> result.put(eachResource, each.getType())); } for (DataNodeContainedRule each : ProxyContext.getInstance().getDatabase(databaseName).getRuleMetaData().findRules(DataNodeContainedRule.class)) { getInUsedResourceNames(each).forEach(eachResource -> result.put(eachResource, each.getType())); } return result; } private Collection<String> getInUsedResourceNames(final DataSourceContainedRule rule) { Collection<String> result = new HashSet<>(); for (Collection<String> each : rule.getDataSourceMapper().values()) { result.addAll(each); } return result; } private Collection<String> getInUsedResourceNames(final DataNodeContainedRule rule) { Collection<String> result = new HashSet<>(); for (Collection<DataNode> each : rule.getAllDataNodes().values()) { result.addAll(each.stream().map(DataNode::getDataSourceName).collect(Collectors.toList())); } return result; } private void checkInUsedIgnoreSingleTables(final Collection<String> inUsedResourceNames, final Multimap<String, String> inUsedStorageUnits) { for (String each : inUsedResourceNames) { Collection<String> inUsedRules = inUsedStorageUnits.get(each); inUsedRules.remove(SingleRule.class.getSimpleName()); ShardingSpherePreconditions.checkState(inUsedRules.isEmpty(), () -> new StorageUnitInUsedException(each, inUsedRules)); } } /** * 按名称判断数据库是否存在 * @param databaseName * @return */ public boolean databaseExists(final String databaseName) { ShardingSpherePreconditions.checkNotNull(databaseName, () -> new UnsupportedSQLOperationException("databaseName is required,can not be null!")); return ProxyContext.getInstance().databaseExists(databaseName); } /** * 按名称判断数据库是否存在 * @param databaseName * @return */ public boolean tableExists(final String databaseName, final String tableName) { ShardingSpherePreconditions.checkNotNull(databaseName, () -> new UnsupportedSQLOperationException("databaseName is required,can not be null!")); ShardingSpherePreconditions.checkNotNull(tableName, () -> new UnsupportedSQLOperationException("tableName is required,can not be null!")); return ProxyContext.getInstance().tableExists(databaseName, tableName); } /** * 按名称判断存储单元是否存在 * @param databaseName * @param dataSourceName * @return 存在返回true,否则返回false */ public boolean storageUnitExists(final String databaseName, final String dataSourceName) { ShardingSpherePreconditions.checkNotNull(databaseName, () -> new UnsupportedSQLOperationException("databaseName is required,can not be null!")); ShardingSpherePreconditions.checkNotNull(dataSourceName, () -> new UnsupportedSQLOperationException("dataSourceNames is required,can not be null!")); return ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources().containsKey(dataSourceName); } /** * 按名称判断存储单元是否更新 * @param databaseName * @param dataSourceName * @param dataSourceConfigurations * @return 存在更新返回true,否则返回false */ public boolean storageUnitIsUpdated(final String databaseName, final String dataSourceName, final DataSourceConfigurations dataSourceConfigurations) { DataSource dataSource = ProxyContext.getInstance().getDatabase(databaseName).getResourceMetaData().getDataSources().get(dataSourceName); return !isIdenticalDatabase(dataSourceConfigurations, dataSource); }}
package com.strongdata.shardata.executor.meta.checker;import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.rule.InvalidRuleConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.storageunit.MissingRequiredStorageUnitsException;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.metadata.database.resource.ShardingSphereResourceMetaData;import org.apache.shardingsphere.infra.rule.identifier.type.DataSourceContainedRule;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration;import org.apache.shardingsphere.readwritesplitting.api.rule.ReadwriteSplittingDataSourceRuleConfiguration;import org.apache.shardingsphere.readwritesplitting.spi.ReadQueryLoadBalanceAlgorithm;import java.util.*;import java.util.stream.Collectors;/** * Readwrite-splitting rule configuration import checker. */public final class ReadwriteSplittingRuleConfigurationChecker { /** * Check readwrite-splitting rule configuration. * * @param database database * @param currentRuleConfig current rule configuration */ public void check(final ShardingSphereDatabase database, final ReadwriteSplittingRuleConfiguration currentRuleConfig) { if (null == database || null == currentRuleConfig) { return; } String databaseName = database.getName(); checkDuplicateRuleNamesWithResourceMetaData(database,currentRuleConfig); checkDataSources(databaseName, database, currentRuleConfig); checkLoadBalancers(currentRuleConfig); } private void checkDataSources(final String databaseName, final ShardingSphereDatabase database, final ReadwriteSplittingRuleConfiguration currentRuleConfig) { Collection<String> requiredDataSources = new LinkedHashSet<>(); Collection<String> requiredLogicalDataSources = new LinkedHashSet<>(); currentRuleConfig.getDataSources().forEach(each -> { if (null != each.getDynamicStrategy()) { requiredLogicalDataSources.add(each.getDynamicStrategy().getAutoAwareDataSourceName()); } if (null != each.getStaticStrategy()) { if (null != each.getStaticStrategy().getWriteDataSourceName()) { requiredDataSources.add(each.getStaticStrategy().getWriteDataSourceName()); } if (!each.getStaticStrategy().getReadDataSourceNames().isEmpty()) { requiredDataSources.addAll(each.getStaticStrategy().getReadDataSourceNames()); } } }); Collection<String> notExistedDataSources = database.getResourceMetaData().getNotExistedDataSources(requiredDataSources); ShardingSpherePreconditions.checkState(notExistedDataSources.isEmpty(), () -> new MissingRequiredStorageUnitsException(databaseName, notExistedDataSources)); Collection<String> logicalDataSources = getLogicDataSources(database); Collection<String> notExistedLogicalDataSources = requiredLogicalDataSources.stream().filter(each -> !logicalDataSources.contains(each)).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(notExistedLogicalDataSources.isEmpty(), () -> new MissingRequiredStorageUnitsException(databaseName, notExistedLogicalDataSources)); } private Collection<String> getLogicDataSources(final ShardingSphereDatabase database) { return database.getRuleMetaData().findRules(DataSourceContainedRule.class).stream() .map(each -> each.getDataSourceMapper().keySet()).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new)); } private void checkLoadBalancers(final ReadwriteSplittingRuleConfiguration currentRuleConfig) { Collection<String> notExistedLoadBalancers = currentRuleConfig.getLoadBalancers().values().stream().map(AlgorithmConfiguration::getType) .filter(each -> !TypedSPILoader.contains(ReadQueryLoadBalanceAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedLoadBalancers.isEmpty(), () -> new InvalidAlgorithmConfigurationException("Load balancers", notExistedLoadBalancers)); } private static void checkDuplicateRuleNamesWithResourceMetaData(final ShardingSphereDatabase database, final ReadwriteSplittingRuleConfiguration currentRuleConfig) { Collection<String> currentDataSources = new LinkedList<>(); ShardingSphereResourceMetaData resourceMetaData = database.getResourceMetaData(); if (null != resourceMetaData && null != resourceMetaData.getDataSources()) { currentDataSources.addAll(resourceMetaData.getDataSources().keySet()); } Collection<String> readwriteSplittingRuleNames = currentRuleConfig.getDataSources().stream().map(ReadwriteSplittingDataSourceRuleConfiguration::getName) .filter(currentDataSources::contains).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(readwriteSplittingRuleNames.isEmpty(), () -> new InvalidRuleConfigurationException("Readwrite splitting", readwriteSplittingRuleNames, Collections.singleton(String.format("%s already exists in storage unit", readwriteSplittingRuleNames)))); } private static Collection<String> getDuplicated(final Collection<String> required) { return required.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); }}
package com.strongdata.shardata.executor.meta.checker;import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.rule.DuplicateRuleException;import org.apache.shardingsphere.distsql.handler.exception.storageunit.MissingRequiredStorageUnitsException;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.rule.identifier.type.DataSourceContainedRule;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.shadow.api.config.ShadowRuleConfiguration;import org.apache.shardingsphere.shadow.spi.ShadowAlgorithm;import java.util.Collection;import java.util.LinkedHashSet;import java.util.Map;import java.util.stream.Collectors;/** * Shadow rule configuration import checker. */public final class ShadowRuleConfigurationChecker { /** * Check shadow rule configuration. * * @param database database * @param currentRuleConfig current rule configuration */ public void check(final ShardingSphereDatabase database, final ShadowRuleConfiguration currentRuleConfig) { if (null == database || null == currentRuleConfig) { return; } String databaseName = database.getName(); checkDataSources(databaseName, database, currentRuleConfig); checkTables(currentRuleConfig, databaseName); checkShadowAlgorithms(currentRuleConfig); } private void checkDataSources(final String databaseName, final ShardingSphereDatabase database, final ShadowRuleConfiguration currentRuleConfig) { Collection<String> requiredResource = getRequiredResources(currentRuleConfig); Collection<String> notExistedResources = database.getResourceMetaData().getNotExistedDataSources(requiredResource); Collection<String> logicResources = getLogicDataSources(database); notExistedResources.removeIf(logicResources::contains); ShardingSpherePreconditions.checkState(notExistedResources.isEmpty(), () -> new MissingRequiredStorageUnitsException(databaseName, notExistedResources)); } private Collection<String> getRequiredResources(final ShadowRuleConfiguration currentRuleConfig) { Collection<String> result = new LinkedHashSet<>(); currentRuleConfig.getDataSources().forEach(each -> { if (null != each.getShadowDataSourceName()) { result.add(each.getShadowDataSourceName()); } if (null != each.getProductionDataSourceName()) { result.add(each.getProductionDataSourceName()); } }); return result; } private Collection<String> getLogicDataSources(final ShardingSphereDatabase database) { return database.getRuleMetaData().findRules(DataSourceContainedRule.class).stream() .map(each -> each.getDataSourceMapper().keySet()).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new)); } private void checkTables(final ShadowRuleConfiguration currentRuleConfig, final String databaseName) { Collection<String> tableNames = currentRuleConfig.getTables().keySet(); Collection<String> duplicatedTables = tableNames.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedTables.isEmpty(), () -> new DuplicateRuleException("SHADOW", databaseName, duplicatedTables)); } private void checkShadowAlgorithms(final ShadowRuleConfiguration currentRuleConfig) { Collection<String> notExistedAlgorithms = currentRuleConfig.getShadowAlgorithms().values().stream().map(AlgorithmConfiguration::getType) .filter(each -> !TypedSPILoader.contains(ShadowAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(notExistedAlgorithms.isEmpty(), () -> new InvalidAlgorithmConfigurationException("Shadow algorithms", notExistedAlgorithms)); }}
package com.strongdata.shardata.executor.meta.checker;import com.google.common.base.Splitter;import com.strongdata.shardata.common.exception.storageunit.MissingStorageUnitsException;import com.strongdata.shardata.common.exception.rule.DuplicateRuleException;import com.strongdata.shardata.common.exception.algorithm.InvalidAlgorithmConfigurationException;import org.apache.shardingsphere.distsql.handler.exception.rule.InvalidRuleConfigurationException;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.datanode.DataNode;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.rule.identifier.type.DataSourceContainedRule;import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;import org.apache.shardingsphere.infra.util.expr.InlineExpressionParser;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.rule.ShardingAutoTableRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableReferenceRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.sharding.ComplexShardingStrategyConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.sharding.NoneShardingStrategyConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.sharding.ShardingStrategyConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;import org.apache.shardingsphere.sharding.api.sharding.ShardingAutoTableAlgorithm;import org.apache.shardingsphere.sharding.exception.algorithm.sharding.ShardingAlgorithmClassImplementationException;import org.apache.shardingsphere.sharding.exception.metadata.ShardingTableRuleNotFoundException;import org.apache.shardingsphere.sharding.rule.BindingTableCheckedConfiguration;import org.apache.shardingsphere.sharding.rule.TableRule;import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;import org.apache.shardingsphere.sharding.spi.ShardingAlgorithm;import org.apache.shardingsphere.sharding.spi.ShardingAuditAlgorithm;import java.util.*;import java.util.function.Function;import java.util.stream.Collectors;/** * Sharding rule configuration import checker. */public final class ShardingRuleConfigurationChecker { private static final String SHARDING = "sharding"; /** * Check sharding rule configuration. * * @param database database * @param currentRuleConfig current rule configuration */ public void check(final ShardingSphereDatabase database, final ShardingRuleConfiguration currentRuleConfig) { if (null == database || null == currentRuleConfig) { return; } String databaseName = database.getName(); checkLogicTables(databaseName, currentRuleConfig); checkResources(databaseName, database, currentRuleConfig); checkInvalidKeyGeneratorAlgorithms(currentRuleConfig); checkInvalidShardingAlgorithms(currentRuleConfig); checkAuditorsAlgorithms(currentRuleConfig); checkShardingRuleAlgorithms(currentRuleConfig); checkBindingAndBroadcastTables(currentRuleConfig); } private void checkLogicTables(final String databaseName, final ShardingRuleConfiguration currentRuleConfig) { Collection<String> tablesLogicTables = currentRuleConfig.getTables().stream().map(ShardingTableRuleConfiguration::getLogicTable).collect(Collectors.toList()); Collection<String> autoTablesLogicTables = currentRuleConfig.getAutoTables().stream().map(ShardingAutoTableRuleConfiguration::getLogicTable).collect(Collectors.toList()); Collection<String> allLogicTables = new LinkedList<>(); allLogicTables.addAll(tablesLogicTables); allLogicTables.addAll(autoTablesLogicTables); Set<String> duplicatedLogicTables = allLogicTables.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedLogicTables.isEmpty(), () -> new DuplicateRuleException(SHARDING, databaseName, duplicatedLogicTables)); } private void checkInvalidShardingAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { Collection<AlgorithmConfiguration> algorithmConfigurations = currentRuleConfig.getShardingAlgorithms().values(); Collection<String> invalidAlgorithms = algorithmConfigurations.stream() .map(AlgorithmConfiguration::getType).filter(each -> !TypedSPILoader.contains(ShardingAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(invalidAlgorithms.isEmpty(), () -> new InvalidAlgorithmConfigurationException(SHARDING, invalidAlgorithms)); } private void checkInvalidKeyGeneratorAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { Collection<AlgorithmConfiguration> algorithmConfigurations = currentRuleConfig.getKeyGenerators().values(); Collection<String> invalidAlgorithms = algorithmConfigurations.stream() .map(AlgorithmConfiguration::getType).filter(each -> !TypedSPILoader.contains(KeyGenerateAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(invalidAlgorithms.isEmpty(), () -> new InvalidAlgorithmConfigurationException("key generator", invalidAlgorithms)); } private Collection<String> getRequiredResources(final ShardingRuleConfiguration currentRuleConfig) { Collection<String> result = new LinkedHashSet<>(); currentRuleConfig.getTables().forEach(each -> result.addAll(getDataSourceNames(each))); currentRuleConfig.getAutoTables().forEach(each -> result.addAll(getDataSourceNames(each))); return result; } private Collection<String> getDataSourceNames(final ShardingAutoTableRuleConfiguration shardingAutoTableRuleConfig) { Collection<String> actualDataSources = new InlineExpressionParser(shardingAutoTableRuleConfig.getActualDataSources()).splitAndEvaluate(); return new HashSet<>(actualDataSources); } private Collection<String> getDataSourceNames(final ShardingTableRuleConfiguration shardingTableRuleConfig) { Collection<String> actualDataNodes = new InlineExpressionParser(shardingTableRuleConfig.getActualDataNodes()).splitAndEvaluate(); return actualDataNodes.stream().map(each -> new DataNode(each).getDataSourceName()).collect(Collectors.toList()); } private void checkResources(final String databaseName, final ShardingSphereDatabase database, final ShardingRuleConfiguration currentRuleConfig) { Collection<String> requiredResource = getRequiredResources(currentRuleConfig); Collection<String> notExistedResources = database.getResourceMetaData().getNotExistedDataSources(requiredResource); Collection<String> logicResources = getLogicResources(database); notExistedResources.removeIf(logicResources::contains); ShardingSpherePreconditions.checkState(notExistedResources.isEmpty(), () -> new MissingStorageUnitsException(databaseName, notExistedResources)); } private Collection<String> getLogicResources(final ShardingSphereDatabase database) { return database.getRuleMetaData().findRules(DataSourceContainedRule.class).stream() .map(each -> each.getDataSourceMapper().keySet()).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new)); } private void checkAuditorsAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { Collection<AlgorithmConfiguration> algorithmConfigurations = currentRuleConfig.getAuditors().values(); Collection<String> invalidAuditors = algorithmConfigurations.stream().map(AlgorithmConfiguration::getType) .filter(each -> !TypedSPILoader.contains(ShardingAuditAlgorithm.class, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkState(invalidAuditors.isEmpty(), () -> new InvalidAlgorithmConfigurationException("auditor", invalidAuditors)); } private void checkShardingRuleAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { checkAutoShardingRuleAlgorithms(currentRuleConfig); checkNormalShardingRuleAlgorithms(currentRuleConfig); } private void checkAutoShardingRuleAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { currentRuleConfig.getAutoTables().forEach(each -> { Optional<ShardingStrategyConfiguration> shardingStrategyConfiguration = Optional.ofNullable(each.getShardingStrategy()); if (shardingStrategyConfiguration.isPresent() && !shardingStrategyConfiguration.get().getType().equalsIgnoreCase("none")) { String algorithmName = shardingStrategyConfiguration.get().getShardingAlgorithmName(); AlgorithmConfiguration algorithmConfiguration = currentRuleConfig.getShardingAlgorithms().get(algorithmName); ShardingSpherePreconditions.checkState(TypedSPILoader.findService( ShardingAlgorithm.class, algorithmConfiguration.getType(), algorithmConfiguration.getProps()).isPresent(), () -> new InvalidAlgorithmConfigurationException(SHARDING, algorithmConfiguration.getType())); ShardingAlgorithm shardingAlgorithm = TypedSPILoader.getService(ShardingAlgorithm.class, algorithmConfiguration.getType(), algorithmConfiguration.getProps()); ShardingSpherePreconditions.checkState(shardingAlgorithm instanceof ShardingAutoTableAlgorithm, () -> new InvalidAlgorithmConfigurationException(SHARDING, shardingAlgorithm.getType(), String.format("auto sharding algorithm is required for rule `%s`", each.getLogicTable()))); } }); } private void checkNormalShardingRuleAlgorithms(final ShardingRuleConfiguration currentRuleConfig) { currentRuleConfig.getTables().forEach(each -> { Optional<ShardingStrategyConfiguration> databaseShardingStrategy = Optional.ofNullable(each.getDatabaseShardingStrategy()); if (databaseShardingStrategy.isPresent() && !databaseShardingStrategy.get().getType().equalsIgnoreCase("none")) { String algorithmName = databaseShardingStrategy.get().getShardingAlgorithmName(); AlgorithmConfiguration databaseAlgorithmConfiguration = currentRuleConfig.getShardingAlgorithms().get(algorithmName); if (null != databaseAlgorithmConfiguration) { ShardingAlgorithm shardingAlgorithm = TypedSPILoader.getService(ShardingAlgorithm.class, databaseAlgorithmConfiguration.getType(), databaseAlgorithmConfiguration.getProps()); ShardingSpherePreconditions.checkState(!(shardingAlgorithm instanceof ShardingAutoTableAlgorithm), () -> new InvalidAlgorithmConfigurationException(SHARDING, shardingAlgorithm.getType(), String.format("auto sharding algorithm cannot be used to create a table in Table mode `%s`", each.getLogicTable()))); } } Optional<ShardingStrategyConfiguration> tableShardingStrategy = Optional.ofNullable(each.getTableShardingStrategy()); if (tableShardingStrategy.isPresent() && !tableShardingStrategy.get().getType().equalsIgnoreCase("none")) { String algorithmName = tableShardingStrategy.get().getShardingAlgorithmName(); AlgorithmConfiguration tableAlgorithmConfiguration = currentRuleConfig.getShardingAlgorithms().get(algorithmName); if (null != tableAlgorithmConfiguration) { ShardingAlgorithm shardingAlgorithm = TypedSPILoader.getService(ShardingAlgorithm.class, tableAlgorithmConfiguration.getType(), tableAlgorithmConfiguration.getProps()); ShardingSpherePreconditions.checkState(!(shardingAlgorithm instanceof ShardingAutoTableAlgorithm), () -> new InvalidAlgorithmConfigurationException(SHARDING, shardingAlgorithm.getType(), String.format("auto sharding algorithm cannot be used to create a table in Table mode `%s`", each.getLogicTable()))); } } }); } public void checkBindingAndBroadcastTables(final ShardingRuleConfiguration checkedConfig) { Collection<String> bindingTableNames = checkedConfig.getBindingTableGroups().stream().map(ShardingTableReferenceRuleConfiguration::getName).collect(Collectors.toList()); Collection<String> allDataSourceNames = getRequiredResources(checkedConfig); Map<String, ShardingAlgorithm> shardingAlgorithms = new HashMap<>(checkedConfig.getShardingAlgorithms().size(), 1); Map<String, TableRule> tableRules = new HashMap<>(); checkedConfig.getShardingAlgorithms().forEach((key, value) -> shardingAlgorithms.put(key, TypedSPILoader.getService(ShardingAlgorithm.class, value.getType(), value.getProps()))); tableRules.putAll(createTableRules(checkedConfig.getTables(), checkedConfig.getDefaultKeyGenerateStrategy(), allDataSourceNames)); tableRules.putAll(createAutoTableRules(checkedConfig.getAutoTables(), shardingAlgorithms, checkedConfig.getDefaultKeyGenerateStrategy(), allDataSourceNames)); checkBroadcastTables(checkedConfig.getBroadcastTables()); Collection<String> broadcastTables = createBroadcastTables(checkedConfig.getBroadcastTables()); ShardingStrategyConfiguration defaultDatabaseShardingStrategyConfig = null == checkedConfig.getDefaultDatabaseShardingStrategy() ? new NoneShardingStrategyConfiguration() : checkedConfig.getDefaultDatabaseShardingStrategy(); ShardingStrategyConfiguration defaultTableShardingStrategyConfig = null == checkedConfig.getDefaultTableShardingStrategy() ? new NoneShardingStrategyConfiguration() : checkedConfig.getDefaultTableShardingStrategy(); ShardingSpherePreconditions.checkState(isValidBindingTableConfiguration(tableRules, new BindingTableCheckedConfiguration(allDataSourceNames, shardingAlgorithms, checkedConfig.getBindingTableGroups(), broadcastTables, defaultDatabaseShardingStrategyConfig, defaultTableShardingStrategyConfig, checkedConfig.getDefaultShardingColumn())), () -> new InvalidRuleConfigurationException("sharding table", bindingTableNames, Collections.singleton("invalid sharding table reference."))); } private Map<String, TableRule> createTableRules(final Collection<ShardingTableRuleConfiguration> tableRuleConfigs, final KeyGenerateStrategyConfiguration defaultKeyGenerateStrategyConfig, final Collection<String> dataSourceNames) { return tableRuleConfigs.stream().map(each -> new TableRule(each, dataSourceNames, getDefaultGenerateKeyColumn(defaultKeyGenerateStrategyConfig))) .collect(Collectors.toMap(each -> each.getLogicTable().toLowerCase(), Function.identity(), (oldValue, currentValue) -> oldValue, LinkedHashMap::new)); } private String getDefaultGenerateKeyColumn(final KeyGenerateStrategyConfiguration defaultKeyGenerateStrategyConfig) { return Optional.ofNullable(defaultKeyGenerateStrategyConfig).map(KeyGenerateStrategyConfiguration::getColumn).orElse(null); } private Map<String, TableRule> createAutoTableRules(final Collection<ShardingAutoTableRuleConfiguration> autoTableRuleConfigs, final Map<String, ShardingAlgorithm> shardingAlgorithms, final KeyGenerateStrategyConfiguration defaultKeyGenerateStrategyConfig, final Collection<String> dataSourceNames) { return autoTableRuleConfigs.stream().map(each -> createAutoTableRule(defaultKeyGenerateStrategyConfig, each, shardingAlgorithms, dataSourceNames)) .collect(Collectors.toMap(each -> each.getLogicTable().toLowerCase(), Function.identity(), (oldValue, currentValue) -> oldValue, LinkedHashMap::new)); } private TableRule createAutoTableRule(final KeyGenerateStrategyConfiguration defaultKeyGenerateStrategyConfig, final ShardingAutoTableRuleConfiguration autoTableRuleConfig, final Map<String, ShardingAlgorithm> shardingAlgorithms, final Collection<String> dataSourceNames) { ShardingAlgorithm shardingAlgorithm = shardingAlgorithms.get(autoTableRuleConfig.getShardingStrategy().getShardingAlgorithmName()); ShardingSpherePreconditions.checkState(shardingAlgorithm instanceof ShardingAutoTableAlgorithm, () -> new ShardingAlgorithmClassImplementationException(autoTableRuleConfig.getShardingStrategy().getShardingAlgorithmName(), ShardingAutoTableAlgorithm.class)); return new TableRule(autoTableRuleConfig, dataSourceNames, (ShardingAutoTableAlgorithm) shardingAlgorithm, getDefaultGenerateKeyColumn(defaultKeyGenerateStrategyConfig)); } private Collection<String> createBroadcastTables(final Collection<String> broadcastTables) { Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); result.addAll(broadcastTables); return result; } private void checkBroadcastTables(final Collection<String> broadcastTables){ Set<String> duplicatedLogicTables = broadcastTables.stream().collect(Collectors.groupingBy(each -> each, Collectors.counting())).entrySet().stream() .filter(each -> each.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet()); ShardingSpherePreconditions.checkState(duplicatedLogicTables.isEmpty(), () -> new DuplicateRuleException("Broadcast", duplicatedLogicTables)); } private boolean isValidBindingTableConfiguration(final Map<String, TableRule> tableRules, final BindingTableCheckedConfiguration checkedConfig) { for (ShardingTableReferenceRuleConfiguration each : checkedConfig.getBindingTableGroups()) { Collection<String> bindingTables = Splitter.on(",").trimResults().splitToList(each.getReference().toLowerCase()); if (bindingTables.size() <= 1) { return false; } Iterator<String> iterator = bindingTables.iterator(); TableRule sampleTableRule = getTableRule(iterator.next(), checkedConfig.getDataSourceNames(), tableRules, checkedConfig.getBroadcastTables()); while (iterator.hasNext()) { TableRule tableRule = getTableRule(iterator.next(), checkedConfig.getDataSourceNames(), tableRules, checkedConfig.getBroadcastTables()); if (!isValidActualDataSourceName(sampleTableRule, tableRule) || !isValidActualTableName(sampleTableRule, tableRule)) { return false; } if (!isValidShardingAlgorithm(sampleTableRule, tableRule, true, checkedConfig) || !isValidShardingAlgorithm(sampleTableRule, tableRule, false, checkedConfig)) { return false; } } } return true; } private TableRule getTableRule(final String logicTableName, final Collection<String> dataSourceNames, final Map<String, TableRule> tableRules, final Collection<String> broadcastTables) { TableRule result = tableRules.get(logicTableName); if (null != result) { return result; } if (broadcastTables.contains(logicTableName)) { return new TableRule(dataSourceNames, logicTableName); } throw new ShardingTableRuleNotFoundException(Collections.singleton(logicTableName)); } private boolean isValidActualDataSourceName(final TableRule sampleTableRule, final TableRule tableRule) { return sampleTableRule.getActualDataSourceNames().equals(tableRule.getActualDataSourceNames()); } private boolean isValidActualTableName(final TableRule sampleTableRule, final TableRule tableRule) { for (String each : sampleTableRule.getActualDataSourceNames()) { Collection<String> sampleActualTableNames = sampleTableRule.getActualTableNames(each).stream().map(actualTableName -> actualTableName.replace(sampleTableRule.getTableDataNode().getPrefix(), "")).collect(Collectors.toSet()); Collection<String> actualTableNames = tableRule.getActualTableNames(each).stream().map(optional -> optional.replace(tableRule.getTableDataNode().getPrefix(), "")).collect(Collectors.toSet()); if (!sampleActualTableNames.equals(actualTableNames)) { return false; } } return true; } private boolean isValidShardingAlgorithm(final TableRule sampleTableRule, final TableRule tableRule, final boolean databaseAlgorithm, final BindingTableCheckedConfiguration checkedConfig) { return getAlgorithmExpression(sampleTableRule, databaseAlgorithm, checkedConfig).equals(getAlgorithmExpression(tableRule, databaseAlgorithm, checkedConfig)); } private Optional<String> getAlgorithmExpression(final TableRule tableRule, final boolean databaseAlgorithm, final BindingTableCheckedConfiguration checkedConfig) { ShardingStrategyConfiguration shardingStrategyConfig = databaseAlgorithm ? null == tableRule.getDatabaseShardingStrategyConfig() ? checkedConfig.getDefaultDatabaseShardingStrategyConfig() : tableRule.getDatabaseShardingStrategyConfig() : null == tableRule.getTableShardingStrategyConfig() ? checkedConfig.getDefaultTableShardingStrategyConfig() : tableRule.getTableShardingStrategyConfig(); ShardingAlgorithm shardingAlgorithm = checkedConfig.getShardingAlgorithms().get(shardingStrategyConfig.getShardingAlgorithmName()); String dataNodePrefix = databaseAlgorithm ? tableRule.getDataSourceDataNode().getPrefix() : tableRule.getTableDataNode().getPrefix(); String shardingColumn = getShardingColumn(shardingStrategyConfig, checkedConfig.getDefaultShardingColumn()); return null == shardingAlgorithm ? Optional.empty() : shardingAlgorithm.getAlgorithmStructure(dataNodePrefix, shardingColumn); } private String getShardingColumn(final ShardingStrategyConfiguration shardingStrategyConfig, final String defaultShardingColumn) { String shardingColumn = defaultShardingColumn; if (shardingStrategyConfig instanceof ComplexShardingStrategyConfiguration) { shardingColumn = ((ComplexShardingStrategyConfiguration) shardingStrategyConfig).getShardingColumns(); } if (shardingStrategyConfig instanceof StandardShardingStrategyConfiguration) { shardingColumn = ((StandardShardingStrategyConfiguration) shardingStrategyConfig).getShardingColumn(); } return null == shardingColumn ? "" : shardingColumn; }}
package com.strongdata.shardata.executor.meta.dialect;import lombok.RequiredArgsConstructor;@RequiredArgsConstructorpublic enum DBType { MYSQL("MySQL"), MARIADB("MariaDB"), OPENGAUSS("openGauss"), POSTGRESQL("PostgreSQL"), H2("H2"), UNKNOWN("unkown"); private final String dbType;}
package com.strongdata.shardata.executor.meta.dialect;import org.apache.shardingsphere.infra.database.type.BranchDatabaseType;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;public class DBTypeResolver { private static final String DEFAULT_DATABASE_TYPE = "MySQL"; public static DatabaseType getProtocolType(DBType dbtype) { DatabaseType databaseType; if (dbtype != null) { databaseType = getTrunkDatabaseType(dbtype.name()); }else{ databaseType = TypedSPILoader.getService(DatabaseType.class, DEFAULT_DATABASE_TYPE); } return databaseType; } public static DatabaseType getTrunkDatabaseType(final String name) { DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, name); return databaseType instanceof BranchDatabaseType ? ((BranchDatabaseType) databaseType).getTrunkDatabaseType() : databaseType; }}
package com.strongdata.shardata.executor.meta.dialect;import com.strongdata.shardata.common.exception.database.UnsupportedVariableException;/** * Variable enum. */public enum VariableEnum { AGENT_PLUGINS_ENABLED, CACHED_CONNECTIONS, TRANSACTION_TYPE; /** * Returns the variable constant of the specified variable name. * * @param variableName variable name * @return variable constant */ public static VariableEnum getValueOf(final String variableName) { try { return valueOf(variableName.toUpperCase()); } catch (final IllegalArgumentException ex) { throw new UnsupportedVariableException(variableName); } }}
package com.strongdata.shardata.executor.meta.handler;import com.google.common.base.Preconditions;import com.google.common.base.Strings;import com.strongdata.shardata.executor.config.auth.AuthorityConfiguration;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.web.common.dto.LogicAuthDto;import lombok.extern.slf4j.Slf4j;import org.apache.shardingsphere.authority.config.AuthorityRuleConfiguration;import org.apache.shardingsphere.authority.rule.builder.DefaultAuthorityRuleConfigurationBuilder;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;import org.apache.shardingsphere.infra.metadata.user.Grantee;import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser;import org.apache.shardingsphere.mode.metadata.persist.service.config.global.GlobalRulePersistService;import org.springframework.util.CollectionUtils;import java.util.*;@Slf4jpublic class AuthorityHandler { public static final String DEFAULT_AUTHENTICATION_METHOD_NAME = "MD5"; public static final String DEFAULT_AUTHENTICATION_MAPPINGS = "user-database-mappings"; public void handle(AuthorityConfiguration authority) { GlobalRulePersistService globalRulePersistService = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getPersistService().getGlobalRuleService(); AuthorityRuleConfiguration authorityRuleConfiguration = convertAuthToConfiguration(authority.getUsers()); Collection<RuleConfiguration> ruleConfigurations = globalRulePersistService.load(); if(!CollectionUtils.isEmpty(ruleConfigurations)) { ruleConfigurations.forEach(ruleConfiguration -> { if(ruleConfiguration instanceof AuthorityRuleConfiguration) { AuthorityRuleConfiguration authorityRuleConfig = (AuthorityRuleConfiguration) ruleConfiguration; authorityRuleConfig.getUsers().stream() .filter(user -> !authorityRuleConfig.getUsers().contains(user)) .forEach(user -> authorityRuleConfig.getUsers().add(user)); } }); } globalRulePersistService.persist(Collections.singleton(authorityRuleConfiguration)); } public Collection<RuleConfiguration> getAuth() { Collection<RuleConfiguration> ruleConfigurations = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getPersistService().getGlobalRuleService().load(); return ruleConfigurations; } public AuthorityRuleConfiguration convertAuthToConfiguration(final LogicAuthDto logicAuthDto) { Collection<ShardingSphereUser> users = new LinkedList<>(); logicAuthDto.getUsers().forEach(each -> { Grantee grantee = convertUserToGrantee(each.getUsername()); users.add(new ShardingSphereUser(grantee.getUsername(), each.getPassword(), grantee.getHostname(), DEFAULT_AUTHENTICATION_METHOD_NAME)); }); AlgorithmConfiguration provider = convertToAlgorithm(logicAuthDto); if (null == provider) { provider = new DefaultAuthorityRuleConfigurationBuilder().build().getAuthorityProvider(); } AuthorityRuleConfiguration result = new AuthorityRuleConfiguration(users, provider, DEFAULT_AUTHENTICATION_METHOD_NAME); result.getAuthenticators().put(DEFAULT_AUTHENTICATION_METHOD_NAME, new AlgorithmConfiguration(DEFAULT_AUTHENTICATION_METHOD_NAME, new Properties())); return result; } private Grantee convertUserToGrantee(final String authUser) { if (!authUser.contains("@")) { return new Grantee(authUser, ""); } String username = authUser.substring(0, authUser.indexOf("@")); String hostname = authUser.substring(authUser.indexOf("@") + 1); Preconditions.checkArgument(!Strings.isNullOrEmpty(username), "user configuration `%s` is invalid, the legal format is `username@hostname`", authUser); return new Grantee(username, hostname); } public AlgorithmConfiguration convertToAlgorithm(final LogicAuthDto logicAuthDto) { if (null == logicAuthDto) { return null; } Properties userMap = new Properties(); if (!Strings.isNullOrEmpty(logicAuthDto.getUserDatabaseMappings())) { userMap.put(DEFAULT_AUTHENTICATION_MAPPINGS, logicAuthDto.getUserDatabaseMappings()); } return new AlgorithmConfiguration(logicAuthDto.getPrivilegeType(), userMap); }}
package com.strongdata.shardata.executor.meta.handler;import ch.qos.logback.classic.Level;import ch.qos.logback.classic.Logger;import ch.qos.logback.classic.LoggerContext;import com.strongdata.shardata.common.exception.database.InvalidValueException;import com.strongdata.shardata.common.exception.database.UnsupportedVariableException;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.logger.LoggingConstants;import com.strongdata.shardata.executor.logger.LoggingUtils;import lombok.extern.slf4j.Slf4j;import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;import org.apache.shardingsphere.infra.util.props.TypedPropertyKey;import org.apache.shardingsphere.infra.util.props.TypedPropertyValue;import org.apache.shardingsphere.infra.util.props.exception.TypedPropertyValueException;import org.apache.shardingsphere.mode.manager.ContextManager;import org.apache.shardingsphere.mode.metadata.MetaDataContexts;import org.slf4j.LoggerFactory;import java.util.*;import java.util.stream.Collectors;@Slf4jpublic class PropertyHandler { public void handle(Map<String, String> map) { Map<TypedPropertyKey, String> enumMap = new LinkedHashMap<>(); map.entrySet().forEach(each -> { Enum<?> enumKey = getEnumType(each.getKey()); if (enumKey instanceof TypedPropertyKey) { enumMap.put((TypedPropertyKey) enumKey, each.getValue()); } else { throw new UnsupportedVariableException(each.getKey()); } }); handleConfigurationProperties(enumMap); } private Enum<?> getEnumType(final String name) { try { return ConfigurationPropertyKey.valueOf(name.toUpperCase()); } catch (final IllegalArgumentException ex) { throw new UnsupportedVariableException(name); } } public void handleConfigurationProperties(Map<TypedPropertyKey, String> propertyMap) { ContextManager contextManager = ProxyContext.getInstance().getContextManager(); MetaDataContexts metaDataContexts = contextManager.getMetaDataContexts(); Properties props = new Properties(); props.putAll(metaDataContexts.getMetaData().getProps().getProps()); props.putAll(metaDataContexts.getMetaData().getInternalProps().getProps()); List<String> propertyMapKeys = new ArrayList<>(); propertyMap.entrySet().forEach(each -> { props.put(each.getKey().getKey(), getValue(each.getKey(), each.getValue())); syncSQLShowToLoggingRule(each.getKey(), metaDataContexts, each.getValue()); syncSQLSimpleToLoggingRule(each.getKey(), metaDataContexts, each.getValue()); propertyMapKeys.add(each.getKey().getKey()); }); List<Object> propsKeys = props.keySet().stream().collect(Collectors.toList()); propsKeys.forEach(propsKey -> { if (!propertyMapKeys.contains(String.valueOf(propsKey))) { props.remove(propsKey); } }); contextManager.getInstanceContext().getModeContextManager().alterProperties(props); refreshRootLogger(props); } public void handleConfigurationProperty(final TypedPropertyKey propertyKey, final String value) { ContextManager contextManager = ProxyContext.getInstance().getContextManager(); MetaDataContexts metaDataContexts = contextManager.getMetaDataContexts(); Properties props = new Properties(); props.putAll(metaDataContexts.getMetaData().getProps().getProps()); props.putAll(metaDataContexts.getMetaData().getInternalProps().getProps()); props.put(propertyKey.getKey(), getValue(propertyKey, value)); contextManager.getInstanceContext().getModeContextManager().alterProperties(props); refreshRootLogger(props); syncSQLShowToLoggingRule(propertyKey, metaDataContexts, value); syncSQLSimpleToLoggingRule(propertyKey, metaDataContexts, value); } private Object getValue(final TypedPropertyKey propertyKey, final String value) { try { Object propertyValue = new TypedPropertyValue(propertyKey, value).getValue(); return Enum.class.isAssignableFrom(propertyKey.getType()) ? propertyValue.toString() : propertyValue; } catch (final TypedPropertyValueException ex) { throw new InvalidValueException(value); } } private void refreshRootLogger(final Properties props) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); renewRootLoggerLevel(rootLogger, props); } private void renewRootLoggerLevel(final Logger rootLogger, final Properties props) { rootLogger.setLevel(Level.valueOf(props.getOrDefault(ConfigurationPropertyKey.SYSTEM_LOG_LEVEL.getKey(), ConfigurationPropertyKey.SYSTEM_LOG_LEVEL.getDefaultValue()).toString())); } private void syncSQLShowToLoggingRule(final TypedPropertyKey propertyKey, final MetaDataContexts metaDataContexts, final String value) { if (LoggingConstants.SQL_SHOW.equalsIgnoreCase(propertyKey.getKey())) { LoggingUtils.getSQLLogger(metaDataContexts.getMetaData().getGlobalRuleMetaData()).ifPresent(option -> { option.getProps().setProperty(LoggingConstants.SQL_LOG_ENABLE, value); metaDataContexts.getPersistService().getGlobalRuleService().persist(metaDataContexts.getMetaData().getGlobalRuleMetaData().getConfigurations()); }); } } private void syncSQLSimpleToLoggingRule(final TypedPropertyKey propertyKey, final MetaDataContexts metaDataContexts, final String value) { if (LoggingConstants.SQL_SIMPLE.equalsIgnoreCase(propertyKey.getKey())) { LoggingUtils.getSQLLogger(metaDataContexts.getMetaData().getGlobalRuleMetaData()).ifPresent(option -> { option.getProps().setProperty(LoggingConstants.SQL_LOG_SIMPLE, value); metaDataContexts.getPersistService().getGlobalRuleService().persist(metaDataContexts.getMetaData().getGlobalRuleMetaData().getConfigurations()); }); } } public Map<String, String> getProperties() { ContextManager contextManager = ProxyContext.getInstance().getContextManager(); MetaDataContexts metaDataContexts = contextManager.getMetaDataContexts(); Properties props = new Properties(); props.putAll(metaDataContexts.getMetaData().getProps().getProps()); props.putAll(metaDataContexts.getMetaData().getInternalProps().getProps()); Map<String, String> result = new LinkedHashMap<>(); props.entrySet().forEach(each -> result.put(each.getKey().toString(), each.getValue().toString())); return result; } public static void main(String[] args) { Enum anEnum = ConfigurationPropertyKey.valueOf("SQL_SHOW".toUpperCase()); log.info("sql-show is {}", anEnum); }}
package com.strongdata.shardata.executor.meta;import com.strongdata.shardata.common.exception.database.FullDatabaseAddException;import com.strongdata.shardata.common.exception.storageunit.InvalidStorageUnitsException;import com.strongdata.shardata.executor.ShardataMetaExecutor;import com.strongdata.shardata.executor.config.auth.AuthorityConfiguration;import com.strongdata.shardata.executor.config.extractor.DataSourceExtractor;import com.strongdata.shardata.executor.config.extractor.DataSourcePropertiesBuilder;import com.strongdata.shardata.executor.config.order.*;import com.strongdata.shardata.executor.config.property.DataSourceConfigurations;import com.strongdata.shardata.executor.config.property.DatabaseConfigurations;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.executor.export.YamlExportor;import com.strongdata.shardata.executor.meta.checker.*;import com.strongdata.shardata.executor.meta.dialect.DBType;import com.strongdata.shardata.executor.meta.dialect.DBTypeResolver;import com.strongdata.shardata.executor.meta.handler.AuthorityHandler;import com.strongdata.shardata.executor.meta.handler.PropertyHandler;import com.zaxxer.hikari.HikariDataSource;import lombok.extern.slf4j.Slf4j;import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;import org.apache.shardingsphere.encrypt.rule.EncryptRule;import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;import org.apache.shardingsphere.infra.database.type.DatabaseType;import org.apache.shardingsphere.infra.datasource.pool.creator.DataSourcePoolCreator;import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;import org.apache.shardingsphere.infra.instance.InstanceContext;import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;import org.apache.shardingsphere.infra.rule.ShardingSphereRule;import org.apache.shardingsphere.infra.util.exception.external.server.ShardingSphereServerException;import org.apache.shardingsphere.mask.api.config.MaskRuleConfiguration;import org.apache.shardingsphere.mask.rule.MaskRule;import org.apache.shardingsphere.mode.manager.ContextManager;import org.apache.shardingsphere.mode.metadata.MetaDataContexts;import org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration;import org.apache.shardingsphere.readwritesplitting.rule.ReadwriteSplittingRule;import org.apache.shardingsphere.shadow.api.config.ShadowRuleConfiguration;import org.apache.shardingsphere.shadow.rule.ShadowRule;import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;import org.apache.shardingsphere.sharding.rule.ShardingRule;import javax.sql.DataSource;import java.sql.SQLException;import java.util.*;import java.util.stream.Collectors;@Slf4jpublic class ShardataMetaDataExecutor implements ShardataMetaExecutor { PropertyHandler propertyHandler = new PropertyHandler(); AuthorityHandler authorityHandler = new AuthorityHandler(); DataSourceExtractor dataSourceExtractor = new DataSourceExtractor(); MetaDataConfigurationChecker metaDataChecker = new MetaDataConfigurationChecker(); private final ShardingRuleConfigurationChecker shardingRuleConfigurationChecker = new ShardingRuleConfigurationChecker(); private final ReadwriteSplittingRuleConfigurationChecker readwriteSplittingRuleConfigurationChecker = new ReadwriteSplittingRuleConfigurationChecker(); private final EncryptRuleConfigurationChecker encryptRuleConfigurationChecker = new EncryptRuleConfigurationChecker(); private final ShadowRuleConfigurationChecker shadowRuleConfigurationChecker = new ShadowRuleConfigurationChecker(); private final MaskRuleConfigurationChecker maskRuleConfigImportChecker = new MaskRuleConfigurationChecker(); public void addFullDatabase(final DatabaseConfigurations databaseConfigurations) { String databaseName = databaseConfigurations.getDatabaseName(); DBType dbType = databaseConfigurations.getDbType(); addLogicDatabase(databaseName,dbType); addStorageUnit(databaseName, HikariDataSource.class.getName(), databaseConfigurations.getDataSources()); try { addRules(databaseName, databaseConfigurations.getRules()); } catch (final Exception ex) { dropLogicDatabase(databaseName); throw new FullDatabaseAddException(databaseName,ex.getMessage()); } } public String exportFullDatabase(String databaseName){ log.info("导出数据库"+databaseName+"规则"); MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); ShardingSphereDatabase database = metaDataContexts.getMetaData().getDatabase(databaseName); return YamlExportor.generateExportDatabaseData(database); } public void addLogicDatabase(final String databaseName,final DBType dbType) { metaDataChecker.checkDatabase(databaseName); ContextManager contextManager = ProxyContext.getInstance().getContextManager(); contextManager.getInstanceContext().getModeContextManager().createDatabase(databaseName); DatabaseType protocolType = DBTypeResolver.getProtocolType(dbType); contextManager.getMetaDataContexts().getMetaData().addDatabase(databaseName, protocolType); } public void addLogicDatabase(final String databaseName,final String dbType) { metaDataChecker.checkDatabaseType(dbType); addLogicDatabase(databaseName,DBType.valueOf(dbType)); } public void dropLogicDatabase(final String databaseName) { metaDataChecker.checkDropDatabase(databaseName); ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().dropDatabase(databaseName); } public void addStorageUnit(final String databaseName, final String dataSourcePoolClassName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap) { Map<String, DataSourceProperties> dataSourcePropsMap = datasourceConvert(dataSourcePoolClassName, dataSourceConfigurationsMap); addStorageUnitWithPropsMap(databaseName, dataSourcePropsMap); } public void addStorageUnit(final String databaseName, final Map<String, DataSource> dataSourceMap) { Map<String, DataSourceProperties> dataSourcePropsMap = new HashMap<>(); dataSourceMap.entrySet().stream().forEach(entry -> { dataSourcePropsMap.put(entry.getKey(), DataSourcePropertiesBuilder.build(entry.getValue())); }); addStorageUnitWithPropsMap(databaseName, dataSourcePropsMap); } private void addStorageUnitWithPropsMap(final String databaseName, final Map<String, DataSourceProperties> dataSourcePropsMap) { metaDataChecker.checkRegisterStorageUnits(databaseName, dataSourcePropsMap); try { ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().registerStorageUnits(databaseName, dataSourcePropsMap); } catch (final SQLException ex) { throw new InvalidStorageUnitsException(Collections.singleton(ex.getMessage())); } Map<String, DataSource> dataSource = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(databaseName).getResourceMetaData().getDataSources(); dataSourcePropsMap.forEach((key, value) -> dataSource.put(key, DataSourcePoolCreator.create(value))); } private void addStorageUnitWithDataSource(final String databaseName, final String dataSourcePoolClassName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap) { Map<String, DataSourceProperties> dataSourcePropsMap = datasourceConvert(dataSourcePoolClassName, dataSourceConfigurationsMap); metaDataChecker.checkRegisterStorageUnits(databaseName,dataSourcePropsMap); try { ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().registerStorageUnits(databaseName, dataSourcePropsMap); } catch (final SQLException ex) { throw new InvalidStorageUnitsException(Collections.singleton(ex.getMessage())); } Map<String, DataSource> dataSource = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(databaseName).getResourceMetaData().getDataSources(); dataSourcePropsMap.forEach((key, value) -> dataSource.put(key, DataSourcePoolCreator.create(value))); } public void dropStorageUnit(final String databaseName, final Collection<String> droppedStorageUnitNames){ metaDataChecker.checkDropStorageUnits(databaseName,droppedStorageUnitNames); try { ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().unregisterStorageUnits(databaseName,droppedStorageUnitNames); } catch (final SQLException | ShardingSphereServerException ex) { throw new InvalidStorageUnitsException(Collections.singleton(ex.getMessage())); } } public void updateStorageUnit(final String databaseName, final String dataSourcePoolClassName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap){ metaDataChecker.checkUpdateStorageUnits(databaseName, dataSourceConfigurationsMap); Map<String, DataSourceProperties> dataSourcePropsMap = datasourceConvert(dataSourcePoolClassName, dataSourceConfigurationsMap); try { ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().alterStorageUnits(databaseName, dataSourcePropsMap); } catch (final SQLException | ShardingSphereServerException ex) { throw new InvalidStorageUnitsException(Collections.singleton(ex.getMessage())); } } public void updateStorageUnit(final String databaseName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap, final Map<String, DataSource> dataSourceMap){ Map<String, DataSourceProperties> dataSourcePropsMap = new HashMap<>(); dataSourceMap.entrySet().stream().forEach(entry -> { dataSourcePropsMap.put(entry.getKey(), DataSourcePropertiesBuilder.build(entry.getValue())); }); metaDataChecker.checkUpdateStorageUnits(databaseName, dataSourceConfigurationsMap); try { ProxyContext.getInstance().getContextManager().getInstanceContext().getModeContextManager().alterStorageUnits(databaseName, dataSourcePropsMap); } catch (final SQLException | ShardingSphereServerException ex) { throw new InvalidStorageUnitsException(Collections.singleton(ex.getMessage())); } } public void addRules(final String databaseName, final Collection<RuleConfiguration> ruleConfigs) { if (null == ruleConfigs || ruleConfigs.isEmpty()) { return; } Collection<RuleConfiguration> allRuleConfigs = new LinkedList<>(); MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); ShardingSphereDatabase database = metaDataContexts.getMetaData().getDatabase(databaseName); clearRulesConfiguration(database); Map<Integer, Collection<RuleConfiguration>> ruleConfigsMap = new HashMap<>(); for (RuleConfiguration rule : ruleConfigs) { if (rule instanceof ShardingRuleConfiguration) { ruleConfigsMap.computeIfAbsent(ShardingOrder.ORDER, key -> new LinkedList<>()); ruleConfigsMap.get(ShardingOrder.ORDER).add(rule); } else if (rule instanceof ReadwriteSplittingRuleConfiguration) { ruleConfigsMap.computeIfAbsent(ReadwriteSplittingOrder.ORDER,key -> new LinkedList<>()); ruleConfigsMap.get(ReadwriteSplittingOrder.ORDER).add(rule); } else if (rule instanceof EncryptRuleConfiguration) { ruleConfigsMap.computeIfAbsent(EncryptOrder.ORDER,key -> new LinkedList<>()); ruleConfigsMap.get(EncryptOrder.ORDER).add(rule); } else if (rule instanceof ShadowRuleConfiguration) { ruleConfigsMap.computeIfAbsent(ShadowOrder.ORDER, key -> new LinkedList<>()); ruleConfigsMap.get(ShadowOrder.ORDER).add(rule); } else if (rule instanceof MaskRuleConfiguration) { ruleConfigsMap.computeIfAbsent(MaskOrder.ORDER, key -> new LinkedList<>()); ruleConfigsMap.get(MaskOrder.ORDER).add(rule); } } ruleConfigsMap.keySet().stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()) .forEach(each -> addRules(allRuleConfigs, ruleConfigsMap.get(each), database)); log.info("修改分库分表规则"); metaDataContexts.getPersistService().getDatabaseRulePersistService().persist(metaDataContexts.getMetaData().getDatabase(databaseName).getName(), allRuleConfigs); } public void addProperties(Map<String, String> properties){ propertyHandler.handle(properties); } public Map<String, String> getProperties(){ return propertyHandler.getProperties(); } public void addAuth(AuthorityConfiguration authorityConfiguration){ authorityHandler.handle(authorityConfiguration); } public Collection<RuleConfiguration> getAuth() { return authorityHandler.getAuth(); } private void addRules(final Collection<RuleConfiguration> allRuleConfigs, final Collection<RuleConfiguration> ruleConfigs, final ShardingSphereDatabase database) { RuleConfiguration ruleConfig = ruleConfigs.stream().findFirst().orElse(null); if (null == ruleConfig) { return; } if (ruleConfig instanceof ShardingRuleConfiguration) { ruleConfigs.forEach(each -> addShardingRuleConfiguration((ShardingRuleConfiguration) each, allRuleConfigs, database)); } else if (ruleConfig instanceof ReadwriteSplittingRuleConfiguration) { ruleConfigs.forEach(each -> addReadwriteSplittingRuleConfiguration((ReadwriteSplittingRuleConfiguration) each, allRuleConfigs, database)); } else if (ruleConfig instanceof EncryptRuleConfiguration) { ruleConfigs.forEach(each -> addEncryptRuleConfiguration((EncryptRuleConfiguration) each, allRuleConfigs, database)); } else if (ruleConfig instanceof ShadowRuleConfiguration) { ruleConfigs.forEach(each -> addShadowRuleConfiguration((ShadowRuleConfiguration) each, allRuleConfigs, database)); } else if (ruleConfig instanceof MaskRuleConfiguration) { ruleConfigs.forEach(each -> addMaskRuleConfiguration((MaskRuleConfiguration) each, allRuleConfigs, database)); } } private void addShardingRuleConfiguration(final ShardingRuleConfiguration shardingRuleConfig, final Collection<RuleConfiguration> allRuleConfigs, final ShardingSphereDatabase database) { InstanceContext instanceContext = ProxyContext.getInstance().getContextManager().getInstanceContext(); shardingRuleConfigurationChecker.check(database, shardingRuleConfig); allRuleConfigs.add(shardingRuleConfig); database.getRuleMetaData().getRules().add(new ShardingRule(shardingRuleConfig, database.getResourceMetaData().getDataSources().keySet(), instanceContext)); } private void addReadwriteSplittingRuleConfiguration(final ReadwriteSplittingRuleConfiguration readwriteSplittingRuleConfig, final Collection<RuleConfiguration> allRuleConfigs, final ShardingSphereDatabase database) { InstanceContext instanceContext = ProxyContext.getInstance().getContextManager().getInstanceContext(); Collection<ShardingSphereRule> rules = database.getRuleMetaData().getRules(); readwriteSplittingRuleConfigurationChecker.check(database, readwriteSplittingRuleConfig); allRuleConfigs.add(readwriteSplittingRuleConfig); rules.add(new ReadwriteSplittingRule(database.getName(), readwriteSplittingRuleConfig, rules,instanceContext)); } private void addEncryptRuleConfiguration(final EncryptRuleConfiguration encryptRuleConfig, final Collection<RuleConfiguration> allRuleConfigs, final ShardingSphereDatabase database) { encryptRuleConfigurationChecker.check(database, encryptRuleConfig); allRuleConfigs.add(encryptRuleConfig); database.getRuleMetaData().getRules().add(new EncryptRule(encryptRuleConfig)); } private void addShadowRuleConfiguration(final ShadowRuleConfiguration shadowRuleConfig, final Collection<RuleConfiguration> allRuleConfigs, final ShardingSphereDatabase database) { shadowRuleConfigurationChecker.check(database, shadowRuleConfig); allRuleConfigs.add(shadowRuleConfig); database.getRuleMetaData().getRules().add(new ShadowRule(shadowRuleConfig)); } private void addMaskRuleConfiguration(final MaskRuleConfiguration maskRuleConfig, final Collection<RuleConfiguration> allRuleConfigs, final ShardingSphereDatabase database) { maskRuleConfigImportChecker.check(database, maskRuleConfig); allRuleConfigs.add(maskRuleConfig); database.getRuleMetaData().getRules().add(new MaskRule(maskRuleConfig)); } private void clearRulesConfiguration(ShardingSphereDatabase database){ database.getRuleMetaData().getRules().clear(); } private Map<String, DataSourceProperties> datasourceConvert(String dataSourcePoolClassName, Map<String, DataSourceConfigurations> dataSourcePropertyMap) { Map<String, DataSourceProperties> dataSourcePropsMap = new LinkedHashMap<>(dataSourcePropertyMap.size(), 1F); for (Map.Entry<String, DataSourceConfigurations> entry : dataSourcePropertyMap.entrySet()) { // HikariDataSource.class.getName() dataSourcePropsMap.put(entry.getKey(), DataSourcePropertiesBuilder.build(dataSourcePoolClassName, dataSourceExtractor.extract(entry.getValue()))); } return dataSourcePropsMap; } /** * 按名称判断数据库是否存在 * @param databaseName * @return */ public boolean databaseExists(final String databaseName) { return metaDataChecker.databaseExists(databaseName); } /** * 按库名和表名判断表是否存在 * @param databaseName 库名/schema名 * @param tableName 表名 * @return */ public boolean tableExists(final String databaseName, final String tableName) { return metaDataChecker.tableExists(databaseName, tableName); } /** * 按名称判断存储单元是否存在 * @param databaseName * @param dataSourceName * @return */ public boolean storageUnitExists(final String databaseName, final String dataSourceName) { return metaDataChecker.storageUnitExists(databaseName, dataSourceName); } /** * 按名称判断存储单元是否更新 * @param databaseName * @param dataSourceName * @param dataSourceConfiguration * @return */ public boolean storageUnitIsUpdated(final String databaseName, final String dataSourceName, final DataSourceConfigurations dataSourceConfiguration) { return metaDataChecker.storageUnitIsUpdated(databaseName, dataSourceName, dataSourceConfiguration); } /** * 检查逻辑库规则中绑定表和广播表配置 * @param shardingRuleConfiguration */ public void checkBindingAndBroadcastTables(final ShardingRuleConfiguration shardingRuleConfiguration) { shardingRuleConfigurationChecker.checkBindingAndBroadcastTables(shardingRuleConfiguration); }}
package com.strongdata.shardata.executor.runner;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import java.util.Optional;@Slf4j@RequiredArgsConstructorpublic final class UIRunnerArguments { private static final String DEFAULT_CONFIG_PATH = "/conf/"; private static final String DEFAULT_BIND_ADDRESS = "0.0.0.0"; private final String[] args; /** * Get port. * * @return port * @throws IllegalArgumentException illegal argument exception */ public Optional<Integer> getPort() { if (0 == args.length) { return Optional.empty(); } try { int port = Integer.parseInt(args[0]); if (port < 0) { return Optional.empty(); } return Optional.of(port); } catch (final NumberFormatException ignored) { throw new IllegalArgumentException(String.format("Invalid port `%s`.", args[0])); } } /** * Get configuration path. * * @return configuration path */ public String getConfigurationPath() { return args.length < 2 ? DEFAULT_CONFIG_PATH : paddingWithSlash(args[1]); } private String paddingWithSlash(final String pathArg) { StringBuilder result = new StringBuilder(pathArg); if (!pathArg.startsWith("/")) { result.insert(0, '/'); } if (!pathArg.endsWith("/")) { result.append('/'); } return result.toString(); }}
package com.strongdata.shardata.executor.runner;import com.strongdata.shardata.executor.config.yaml.YamlUIConfiguration;import com.strongdata.shardata.executor.context.ProxyContext;import com.strongdata.shardata.web.common.constant.MetaDataPath;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaDataBuilder;import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;import org.apache.shardingsphere.infra.yaml.config.swapper.mode.YamlModeConfigurationSwapper;import org.apache.shardingsphere.mode.manager.ContextManager;import org.apache.shardingsphere.mode.manager.ContextManagerBuilder;import org.apache.shardingsphere.mode.manager.ContextManagerBuilderParameter;import java.sql.SQLException;import java.util.Collections;import java.util.Properties;@RequiredArgsConstructor@Slf4jpublic final class UIRunnerContext { public static final String CONS_UINAMESPACE="shardata_ui_ds"; public static final String CONS_NAMESPACE="shardata_governance_ds"; public static final String CONSOLE="Console"; public void init(final YamlUIConfiguration yamlConfig, final int port, final boolean force) throws SQLException { ModeConfiguration modeConfig = null == yamlConfig.getServerConfiguration().getMode() ? null : new YamlModeConfigurationSwapper().swapToObject(yamlConfig.getServerConfiguration().getMode()); ContextManager contextManager = createContextManager(modeConfig, port, force); ProxyContext.init(contextManager); initMetaDataPath(modeConfig); } private void initMetaDataPath(ModeConfiguration modeConfig){ if (modeConfig != null) { MetaDataPath.uiNameSpace=null!=modeConfig.getRepository().getProps().get("ui-namespace")?modeConfig.getRepository().getProps().get("ui-namespace").toString():CONS_UINAMESPACE; MetaDataPath.nameSpace=null!=modeConfig.getRepository().getProps().get("namespace")?modeConfig.getRepository().getProps().get("namespace").toString():CONS_NAMESPACE; MetaDataPath.serverList=null!=modeConfig.getRepository().getProps().get("server-lists")?modeConfig.getRepository().getProps().get("server-lists").toString():""; } } private ContextManager createContextManager( final ModeConfiguration modeConfig, final int port, final boolean force) throws SQLException { ContextManagerBuilderParameter param = new ContextManagerBuilderParameter(modeConfig, Collections.emptyMap(), Collections.emptyList(), new Properties(), Collections.emptyList(), createInstanceMetaData(port), force); return TypedSPILoader.getService(ContextManagerBuilder.class, null == modeConfig ? null : getModeConfigType(modeConfig)).build(param); } private InstanceMetaData createInstanceMetaData(final int port) { return TypedSPILoader.getService(InstanceMetaDataBuilder.class, "PROXY").build(port); } private String getModeConfigType(ModeConfiguration modeConfig){ return CONSOLE+modeConfig.getType(); }}
package com.strongdata.shardata.executor;public interface ShardataCommandExcutor extends ShardataExecutor{}
package com.strongdata.shardata.executor;public interface ShardataExecutor {}
package com.strongdata.shardata.executor;import com.strongdata.shardata.executor.config.auth.AuthorityConfiguration;import com.strongdata.shardata.executor.config.property.DataSourceConfigurations;import com.strongdata.shardata.executor.config.property.DatabaseConfigurations;import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;import javax.sql.DataSource;import java.util.Collection;import java.util.Map;public interface ShardataMetaExecutor extends ShardataExecutor { public void addFullDatabase(final DatabaseConfigurations databaseConfigurations); public String exportFullDatabase(String databaseName); public void addLogicDatabase(final String databaseName,final String dbType); public void dropLogicDatabase(final String databaseName); public void addStorageUnit(final String databaseName, final String dataSourcePoolClassName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap); public void addStorageUnit(final String databaseName, final Map<String, DataSource> dataSourceMap); public void dropStorageUnit(final String databaseName, final Collection<String> droppedStorageUnitNames); public void updateStorageUnit(final String databaseName, final String dataSourcePoolClassName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap); public void updateStorageUnit(final String databaseName, final Map<String, DataSourceConfigurations> dataSourceConfigurationsMap, final Map<String, DataSource> dataSourceMap); public void addRules(final String databaseName, final Collection<RuleConfiguration> ruleConfigs); public void addProperties(Map<String, String> properties); public Map<String, String> getProperties(); public void addAuth(AuthorityConfiguration authorityConfiguration); public Collection<RuleConfiguration> getAuth(); public boolean databaseExists(final String databaseName); public boolean tableExists(final String databaseName, final String tableName); public boolean storageUnitExists(final String databaseName, final String dataSourceNames); public boolean storageUnitIsUpdated(final String databaseName, final String dataSourceName, final DataSourceConfigurations dataSourceConfiguration); public void checkBindingAndBroadcastTables(final ShardingRuleConfiguration shardingRuleConfiguration);}
package com.strongdata.shardata.executor.test;import com.strongdata.shardata.executor.config.UIConfigurationLoader;import com.strongdata.shardata.executor.config.property.DataSourceConfigurations;import com.strongdata.shardata.executor.config.yaml.YamlUIConfiguration;import com.strongdata.shardata.executor.meta.ShardataMetaDataExecutor;import com.strongdata.shardata.executor.meta.dialect.DBType;import com.strongdata.shardata.executor.runner.UIRunnerArguments;import com.strongdata.shardata.executor.runner.UIRunnerContext;import com.strongdata.shardata.executor.utils.PropertiesBuilder;import com.zaxxer.hikari.HikariDataSource;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;public class TestDatabase { public static void main(String[] args) throws Exception{ UIRunnerArguments bootstrapArgs = new UIRunnerArguments(args); YamlUIConfiguration yamlConfig = UIConfigurationLoader.load(bootstrapArgs.getConfigurationPath()); new UIRunnerContext().init(yamlConfig,0,true); TestDatabase test = new TestDatabase(); test.testAddDatabase(); test.testAddDatasource();// test.testAlertDatasource();// test.testDeleteDatasource(); } public void testAddDatabase(){ ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addLogicDatabase("test", DBType.MYSQL); } public void testDropDatabase(){ ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.dropLogicDatabase("test"); } public void testAddDatasource(){ Map datasources=new LinkedHashMap(); DataSourceConfigurations shard1_m= buildDatasource("jdbc:mysql://10.1.1.22:27754/shard_1?serverTimezone=UTC&useSSL=false&autoReconnect=true&failOverReadOnly=false", "root", "oMr1F7f2ck"); DataSourceConfigurations shard1_s= buildDatasource("jdbc:mysql://10.1.1.22:22820/shard_1?serverTimezone=UTC&useSSL=false&autoReconnect=true", "root", "oMr1F7f2ck"); DataSourceConfigurations shard0_m= buildDatasource("jdbc:mysql://10.1.1.21:60865/shard_0?serverTimezone=UTC&useSSL=false&autoReconnect=true&failOverReadOnly=false", "root", "GR4bVoMsTv"); DataSourceConfigurations shard0_s= buildDatasource("jdbc:mysql://10.1.1.21:56020/shard_0?serverTimezone=UTC&useSSL=false&autoReconnect=true", "root", "GR4bVoMsTv"); datasources.put("shard1",shard1_m); datasources.put("shard1_s",shard1_s); datasources.put("shard0",shard0_m); datasources.put("shard0_s",shard0_s); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addStorageUnit("test", HikariDataSource.class.getName(),datasources); } public void testAlertDatasource(){ Map datasources=new LinkedHashMap(); DataSourceConfigurations shard1_m= buildDatasource("jdbc:mysql://10.1.1.22:27754/shard_1?serverTimezone=UTC&useSSL=false&autoReconnect=true&failOverReadOnly=false", "root", "oMr1F7f2ck"); DataSourceConfigurations shard1_s= buildDatasource("jdbc:mysql://10.1.1.22:22820/shard_1?serverTimezone=UTC&useSSL=false&autoReconnect=true", "root", "oMr1F7f2ck"); datasources.put("shard1",shard1_m); datasources.put("shard1_s",shard1_s); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.updateStorageUnit("test", HikariDataSource.class.getName(),datasources); } public void testDeleteDatasource(){ List datasources=new LinkedList<>(); datasources.add("shard1"); datasources.add("shard1_s"); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.dropStorageUnit("test", datasources); } private DataSourceConfigurations buildDatasource(String url,String usrname,String password){ DataSourceConfigurations dataSourceConfigurations=new DataSourceConfigurations(); dataSourceConfigurations.setUrl(url); dataSourceConfigurations.setUsername(usrname); dataSourceConfigurations.setPassword(password); dataSourceConfigurations.setConnectionTimeoutMilliseconds(30000L); dataSourceConfigurations.setIdleTimeoutMilliseconds(60000L); dataSourceConfigurations.setMaxLifetimeMilliseconds(1800000L); dataSourceConfigurations.setMinPoolSize(1); dataSourceConfigurations.setMaxPoolSize(20); dataSourceConfigurations.setCustomPoolProps(PropertiesBuilder.build(new PropertiesBuilder.Property("keepaliveTime", "60000"))); return dataSourceConfigurations; }}
package com.strongdata.shardata.executor.test;import com.strongdata.shardata.executor.config.UIConfigurationLoader;import com.strongdata.shardata.executor.config.auth.AuthorityConfiguration;import com.strongdata.shardata.executor.config.yaml.YamlUIConfiguration;import com.strongdata.shardata.executor.meta.ShardataMetaDataExecutor;import com.strongdata.shardata.executor.runner.UIRunnerArguments;import com.strongdata.shardata.executor.runner.UIRunnerContext;import com.strongdata.shardata.executor.utils.PropertiesBuilder;import com.strongdata.shardata.web.common.dto.LogicAuthDto;import com.strongdata.shardata.web.common.dto.LogicAuthUser;import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.rule.ShardingAutoTableRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;import java.util.*;public class TestRules { public static void main(String[] args) throws Exception { UIRunnerArguments bootstrapArgs = new UIRunnerArguments(args); YamlUIConfiguration yamlConfig = UIConfigurationLoader.load(bootstrapArgs.getConfigurationPath()); new UIRunnerContext().init(yamlConfig, 0, true); TestRules testRules = new TestRules(); testRules.testAddNormalRules(); testRules.testAddAutoRules(); testRules.addAuth(); testRules.addProperties(); testRules.exportYaml(); } public void testAddAutoRules() { ShardingRuleConfiguration shardingRuleConfig = createAutoTableRule(); Collection<RuleConfiguration> rules = new ArrayList<>(); rules.add(shardingRuleConfig); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addRules("test", rules); } private ShardingRuleConfiguration createAutoTableRule() { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); ShardingAutoTableRuleConfiguration autoTableRuleConfig = new ShardingAutoTableRuleConfiguration("test", "shard${0..1}"); autoTableRuleConfig.setShardingStrategy(new StandardShardingStrategyConfiguration("db_id", "hash_mod")); shardingRuleConfig.getAutoTables().add(autoTableRuleConfig); Properties properties = new Properties(); properties.setProperty("sharding-count", "4"); shardingRuleConfig.getShardingAlgorithms().put("hash_mod", new AlgorithmConfiguration("hash_mod", properties)); return shardingRuleConfig; } public void testAddNormalRules() { ShardingRuleConfiguration shardingTableRuleConfig = createTableRuleConfiguration("t_normal", "shard${0..1}.t_normal_${0..2}"); Collection<RuleConfiguration> rules = new ArrayList<>(); rules.add(shardingTableRuleConfig); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addRules("test", rules); } private ShardingRuleConfiguration createTableRuleConfiguration(final String logicTableName, final String actualDataNodes) { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); ShardingTableRuleConfiguration shardingTableRuleConfiguration = new ShardingTableRuleConfiguration(logicTableName, actualDataNodes); shardingTableRuleConfiguration.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("db_id", "database_inline")); shardingTableRuleConfiguration.setTableShardingStrategy(new StandardShardingStrategyConfiguration("table_id", "table_inline")); shardingRuleConfig.getTables().add(shardingTableRuleConfiguration); shardingRuleConfig.getShardingAlgorithms().put("database_inline", new AlgorithmConfiguration("INLINE", PropertiesBuilder.build(new PropertiesBuilder.Property("algorithm-expression", "shard%{db_id % 2}")))); shardingRuleConfig.getShardingAlgorithms().put("table_inline", new AlgorithmConfiguration("INLINE", PropertiesBuilder.build(new PropertiesBuilder.Property("algorithm-expression", "t_normal_%{table_id % 2}")))); return shardingRuleConfig; } public void exportYaml() { ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); String yaml = executor.exportFullDatabase("test"); System.out.println(yaml); } public void addAuth() { LogicAuthUser user = new LogicAuthUser("root@localhost", "test"); LogicAuthDto logicAuthDto = new LogicAuthDto(); ArrayList<LogicAuthUser> logicAuthUsers = new ArrayList<>(); logicAuthUsers.add(user); logicAuthDto.setUsers(logicAuthUsers); AuthorityConfiguration authorityConfiguration = new AuthorityConfiguration(logicAuthDto, "ALL_PERMITTED"); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addAuth(authorityConfiguration); } public void addProperties() { Map<String, String> properties = new HashMap<>(); properties.put("sql_show","true"); ShardataMetaDataExecutor executor = new ShardataMetaDataExecutor(); executor.addProperties(properties); }}
package com.strongdata.shardata.executor.test;import com.strongdata.shardata.executor.command.ShardataComandExecutor;import com.strongdata.shardata.executor.config.UIConfigurationLoader;import com.strongdata.shardata.executor.config.yaml.YamlUIConfiguration;import com.strongdata.shardata.executor.runner.UIRunnerArguments;import com.strongdata.shardata.executor.runner.UIRunnerContext;import java.sql.SQLException;public class TestTable { public static void main(String[] args) throws Exception { UIRunnerArguments bootstrapArgs = new UIRunnerArguments(args); YamlUIConfiguration yamlConfig = UIConfigurationLoader.load(bootstrapArgs.getConfigurationPath()); new UIRunnerContext().init(yamlConfig, 0, true); ShardataComandExecutor comandExecutor=new ShardataComandExecutor(); TestTable testTable = new TestTable(); testTable.testCreateTable(comandExecutor); testTable.alertTable(comandExecutor); Thread.sleep(5000); testTable.dropTable(comandExecutor); } public void testCreateTable(ShardataComandExecutor comandExecutor) throws SQLException { System.out.println("create==============================================="); String sql="CREATE TABLE test (\n" + "\tdb_id varchar(100) NOT NULL,\n" + "\ttable_id varchar(100) NULL,\n" + "\ttest varchar(100) NULL,\n" + "\tCONSTRAINT test_PK PRIMARY KEY (db_id)\n" + ")"; comandExecutor.doExecuteCommand("test",sql); } public void alertTable(ShardataComandExecutor comandExecutor) throws SQLException { System.out.println("alert==============================================="); String sql="ALTER TABLE test ADD mark varchar(100) DEFAULT '1' NOT NULL;"; comandExecutor.doExecuteCommand("test",sql); } public void dropTable(ShardataComandExecutor comandExecutor) throws SQLException { System.out.println("drop==============================================="); String sql="DROP TABLE test"; comandExecutor.doExecuteCommand("test",sql); }}
package com.strongdata.shardata.executor.utils;import lombok.AccessLevel;import lombok.NoArgsConstructor;import lombok.RequiredArgsConstructor;import java.util.Properties;@NoArgsConstructor(access = AccessLevel.PRIVATE)public final class PropertiesBuilder { /** * Build properties. * * @param properties to be built properties * @return built properties */ public static Properties build(final Property... properties) { Properties result = new Properties(); for (Property each : properties) { result.setProperty(each.key, each.value); } return result; } /** * Property. */ @RequiredArgsConstructor public static class Property { private final String key; private final String value; }}
package com.strongdata.shardata.executor.utils;import lombok.AccessLevel;import lombok.NoArgsConstructor;import org.apache.shardingsphere.sql.parser.sql.common.enums.TransactionIsolationLevel;import java.sql.Connection;@NoArgsConstructor(access = AccessLevel.PRIVATE)public final class TransactionUtil { /** * Get the value of type int according to TransactionIsolationLevel. * * @param isolationLevel value of type TransactionIsolationLevel * @return isolation level */ public static int getTransactionIsolationLevel(final TransactionIsolationLevel isolationLevel) { switch (isolationLevel) { case READ_UNCOMMITTED: return Connection.TRANSACTION_READ_UNCOMMITTED; case READ_COMMITTED: return Connection.TRANSACTION_READ_COMMITTED; case REPEATABLE_READ: return Connection.TRANSACTION_REPEATABLE_READ; case SERIALIZABLE: return Connection.TRANSACTION_SERIALIZABLE; default: return Connection.TRANSACTION_NONE; } } /** * Get the value of type TransactionIsolationLevel according to int. * * @param isolationLevel value of type int * @return isolation level */ public static TransactionIsolationLevel getTransactionIsolationLevel(final int isolationLevel) { switch (isolationLevel) { case Connection.TRANSACTION_READ_UNCOMMITTED: return TransactionIsolationLevel.READ_UNCOMMITTED; case Connection.TRANSACTION_READ_COMMITTED: return TransactionIsolationLevel.READ_COMMITTED; case Connection.TRANSACTION_REPEATABLE_READ: return TransactionIsolationLevel.REPEATABLE_READ; case Connection.TRANSACTION_SERIALIZABLE: return TransactionIsolationLevel.SERIALIZABLE; default: return TransactionIsolationLevel.NONE; } }}
package com.strongdata.workflow.modules.sys.controller;import com.google.code.kaptcha.Producer;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.redis.util.RedisUtil;import com.strongdata.workflow.common.core.util.SpringContextUtils;import com.strongdata.workflow.common.security.annotation.AnonymousAccess;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.imageio.ImageIO;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.awt.image.BufferedImage;import java.io.IOException;/** * @author 庄金明 * @date 2020年3月23日 */@RestControllerpublic class SysCaptchaController { @Autowired private RedisUtil redisUtil; @AnonymousAccess @GetMapping("/captcha.jpg") public void captcha(HttpServletResponse response, String uuid) throws IOException { Producer producer = SpringContextUtils.getBean(Producer.class); response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); // 生成文字验证码 String text = producer.createText(); // 保存到 redis,60秒 redisUtil.set(CacheConstants.CAPTCHA + uuid, text, 60); // 获取图片验证码 BufferedImage image = producer.createImage(text); ServletOutputStream out = null; try { out = response.getOutputStream(); ImageIO.write(image, "jpg", out); } finally { if (out != null) { out.close(); } } }}
package com.strongdata.workflow.modules.sys.controller;import java.util.List;import java.util.Map;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysCodeInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysCodeInfo;/** * 代码信息Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/codeInfo")public class SysCodeInfoController extends BaseController { @Autowired private SysCodeInfoService sysCodeInfoService; /** * 自定义查询列表 * * @param sysCodeInfo * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:codeInfo:list')") @GetMapping(value = "/list") public Result list(SysCodeInfo sysCodeInfo, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysCodeInfo> pageList = sysCodeInfoService.list(new Page<SysCodeInfo>(current, size), sysCodeInfo); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:codeInfo:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysCodeInfo sysCodeInfo = sysCodeInfoService.getById(id); return Result.ok(sysCodeInfo); } /** * @param sysCodeInfo * @return * @功能:新增 */ @Log(value = "新增代码信息") @PreAuthorize("@elp.single('sys:codeInfo:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysCodeInfo sysCodeInfo) { sysCodeInfoService.saveSysCodeInfo(sysCodeInfo); return Result.ok(); } /** * @param sysCodeInfo * @return * @功能:修改 */ @Log(value = "修改代码信息") @PreAuthorize("@elp.single('sys:codeInfo:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysCodeInfo sysCodeInfo) { sysCodeInfoService.updateSysCodeInfo(sysCodeInfo); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除代码信息") @PreAuthorize("@elp.single('sys:codeInfo:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { sysCodeInfoService.deleteSysCodeInfo(ids); return Result.ok(); } /** * 根据代码类型查询代码信息清单 * * @param codeTypeIds * @return */ @GetMapping(value = "/getSysCodeInfos") public Result getSysCodeInfos(String codeTypeIds) { Map<String, List<SysCodeInfo>> sysCodeInfosMap = sysCodeInfoService.getSysCodeInfosFromRedis(codeTypeIds); if (sysCodeInfosMap == null) { sysCodeInfosMap = sysCodeInfoService.getSysCodeInfosFromDb(codeTypeIds); } return Result.ok(sysCodeInfosMap); }}
package com.strongdata.workflow.modules.sys.controller;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysCodeTypeService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysCodeType;/** * 代码类别Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/codeType")public class SysCodeTypeController extends BaseController { @Autowired private SysCodeTypeService sysCodeTypeService; /** * 自定义查询列表 * * @param sysCodeType * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:codeType:list')") @GetMapping(value = "/list") public Result list(SysCodeType sysCodeType, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysCodeType> pageList = sysCodeTypeService.list(new Page<SysCodeType>(current, size), sysCodeType); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:codeType:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysCodeType sysCodeType = sysCodeTypeService.getById(id); return Result.ok(sysCodeType); } /** * @param sysCodeType * @return * @功能:新增 */ @Log(value = "新增代码类别") @PreAuthorize("@elp.single('sys:codeType:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysCodeType sysCodeType) { sysCodeTypeService.save(sysCodeType); return Result.ok(); } /** * @param sysCodeType * @return * @功能:修改 */ @Log(value = "修改代码类别") @PreAuthorize("@elp.single('sys:codeType:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysCodeType sysCodeType) { sysCodeTypeService.updateById(sysCodeType); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除代码类别") @PreAuthorize("@elp.single('sys:codeType:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { sysCodeTypeService.deleteSysCodeType(ids); return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysConfigService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysConfig;/** * 系统参数Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/config")public class SysConfigController extends BaseController { @Autowired private SysConfigService sysConfigService; /** * 自定义查询列表 * * @param sysConfig * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:config:list')") @GetMapping(value = "/list") public Result list(SysConfig sysConfig, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysConfig> pageList = sysConfigService.list(new Page<SysConfig>(current, size), sysConfig); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:config:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysConfig sysConfig = sysConfigService.getById(id); return Result.ok(sysConfig); } /** * @param sysConfig * @return * @功能:新增 */ @Log(value = "新增系统参数") @PreAuthorize("@elp.single('sys:config:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysConfig sysConfig) { sysConfigService.saveSysConfig(sysConfig); return Result.ok(); } /** * @param sysConfig * @return * @功能:修改 */ @Log(value = "修改系统参数") @PreAuthorize("@elp.single('sys:config:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysConfig sysConfig) { sysConfigService.updateSysConfig(sysConfig); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除系统参数") @PreAuthorize("@elp.single('sys:config:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { sysConfigService.deleteSysConfig(ids); return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysDataPermissionService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysDataPermission;/** * 数据权限Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/dataPermission")public class SysDataPermissionController extends BaseController { @Autowired private SysDataPermissionService sysDataPermissionService; /** * 自定义查询列表 * * @param sysDataPermission * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:dataPermission:list')") @GetMapping(value = "/list") public Result list(SysDataPermission sysDataPermission, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysDataPermission> pageList = sysDataPermissionService.list(new Page<SysDataPermission>(current, size), sysDataPermission); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:dataPermission:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysDataPermission sysDataPermission = sysDataPermissionService.getById(id); return Result.ok(sysDataPermission); } /** * @param sysDataPermission * @return * @功能:新增 */ @Log(value = "新增数据权限") @PreAuthorize("@elp.single('sys:dataPermission:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysDataPermission sysDataPermission) { sysDataPermissionService.save(sysDataPermission); return Result.ok(); } /** * @param sysDataPermission * @return * @功能:修改 */ @Log(value = "修改数据权限") @PreAuthorize("@elp.single('sys:dataPermission:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysDataPermission sysDataPermission) { sysDataPermissionService.updateById(sysDataPermission); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除数据权限") @PreAuthorize("@elp.single('sys:dataPermission:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysDataPermissionService.removeByIds(Arrays.asList(idsArr)); } else { sysDataPermissionService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysFuncService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysFunc;/** * 功能Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/func")public class SysFuncController extends BaseController { @Autowired private SysFuncService sysFuncService; /** * 自定义查询列表 * * @param sysFunc * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:func:list')") @GetMapping(value = "/list") public Result list(SysFunc sysFunc, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysFunc> pageList = sysFuncService.list(new Page<SysFunc>(current, size), sysFunc); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:func:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysFunc sysFunc = sysFuncService.getById(id); return Result.ok(sysFunc); } /** * @param sysFunc * @return * @功能:新增 */ @Log(value = "新增功能按钮") @PreAuthorize("@elp.single('sys:func:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysFunc sysFunc) { sysFuncService.save(sysFunc); return Result.ok(); } /** * @param sysFunc * @return * @功能:修改 */ @Log(value = "修改功能按钮") @PreAuthorize("@elp.single('sys:func:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysFunc sysFunc) { sysFuncService.updateById(sysFunc); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除功能按钮") @PreAuthorize("@elp.single('sys:func:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysFuncService.removeByIds(Arrays.asList(idsArr)); } else { sysFuncService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysLogService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysLog;/** * 系统日志Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/log")public class SysLogController extends BaseController { @Autowired private SysLogService sysLogService; /** * 自定义查询列表 * * @param sysLog * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:log:list')") @GetMapping(value = "/list") public Result list(SysLog sysLog, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysLog> pageList = sysLogService.list(new Page<SysLog>(current, size), sysLog); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:log:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysLog sysLog = sysLogService.getById(id); return Result.ok(sysLog); } /** * @param sysLog * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:log:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysLog sysLog) { sysLogService.save(sysLog); return Result.ok(); } /** * @param sysLog * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:log:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysLog sysLog) { sysLogService.updateById(sysLog); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:log:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysLogService.removeByIds(Arrays.asList(idsArr)); } else { sysLogService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.List;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysMenuService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysMenu;import com.strongdata.workflow.modules.sys.entity.vo.ElTree;/** * 菜单Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/menu")public class SysMenuController extends BaseController { @Autowired private SysMenuService sysMenuService; /** * 自定义查询列表 * * @param sysMenu * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:menu:list')") @GetMapping(value = "/list") public Result list(SysMenu sysMenu, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysMenu> pageList = sysMenuService.list(new Page<SysMenu>(current, size), sysMenu); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:menu:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysMenu sysMenu = sysMenuService.getById(id); return Result.ok(sysMenu); } /** * @param sysMenu * @return * @功能:新增 */ @Log(value = "新增功能菜单") @PreAuthorize("@elp.single('sys:menu:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysMenu sysMenu) { sysMenuService.saveSysMenu(sysMenu); return Result.ok(sysMenu); } /** * @param sysMenu * @return * @功能:修改 */ @Log(value = "修改功能菜单") @PreAuthorize("@elp.single('sys:menu:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysMenu sysMenu) { sysMenuService.updateSysMenu(sysMenu); return Result.ok(sysMenu); } /** * @param id * @return * @功能:删除 */ @Log(value = "删除功能菜单") @PreAuthorize("@elp.single('sys:menu:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String id) { sysMenuService.delete(id); return Result.ok(); } /** * 菜单管理,菜单树数据 * * @return */ @PreAuthorize("@elp.single('sys:menu:getTreeData')") @GetMapping(value = "/getTreeData") public Result getTreeData() { List<ElTree> treeData = sysMenuService.getTreeData(); return Result.ok(treeData); }}
package com.strongdata.workflow.modules.sys.controller;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysOauthClientDetailsService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysOauthClientDetails;/** * 应用客户端Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/oauthClientDetails")public class SysOauthClientDetailsController extends BaseController { @Autowired private SysOauthClientDetailsService sysOauthClientDetailsService; /** * 自定义查询列表 * * @param sysOauthClientDetails * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:oauthClientDetails:list')") @GetMapping(value = "/list") public Result list(SysOauthClientDetails sysOauthClientDetails, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysOauthClientDetails> pageList = sysOauthClientDetailsService.list(new Page<SysOauthClientDetails>(current, size), sysOauthClientDetails); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:oauthClientDetails:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysOauthClientDetails sysOauthClientDetails = sysOauthClientDetailsService.getById(id); return Result.ok(sysOauthClientDetails); } /** * @param sysOauthClientDetails * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:oauthClientDetails:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { sysOauthClientDetailsService.saveSysOauthClientDetails(sysOauthClientDetails); return Result.ok(); } /** * @param sysOauthClientDetails * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:oauthClientDetails:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { sysOauthClientDetailsService.updateSysOauthClientDetails(sysOauthClientDetails); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:oauthClientDetails:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { sysOauthClientDetailsService.delete(ids); return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import java.util.List;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysOrgService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysOrg;import com.strongdata.workflow.modules.sys.entity.vo.ElTree;/** * 机构Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/org")public class SysOrgController extends BaseController { @Autowired private SysOrgService sysOrgService; /** * 自定义查询列表 * * @param sysOrg * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:org:list')") @GetMapping(value = "/list") public Result list(SysOrg sysOrg, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysOrg> pageList = sysOrgService.list(new Page<SysOrg>(current, size), sysOrg); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:org:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysOrg sysOrg = sysOrgService.getById(id); return Result.ok(sysOrg); } /** * @param sysOrg * @return * @功能:新增 */ @Log(value = "新增机构") @PreAuthorize("@elp.single('sys:org:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysOrg sysOrg) { sysOrgService.saveSysOrg(sysOrg); return Result.ok(sysOrg); } /** * @param sysOrg * @return * @功能:修改 */ @Log(value = "修改机构") @PreAuthorize("@elp.single('sys:org:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysOrg sysOrg) { sysOrgService.updateSysOrg(sysOrg); return Result.ok(sysOrg); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除机构") @PreAuthorize("@elp.single('sys:org:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysOrgService.removeByIds(Arrays.asList(idsArr)); } else { sysOrgService.removeById(idsArr[0]); } return Result.ok(); } /** * 机构管理,机构树数据 * * @return */ @PreAuthorize("@elp.single('sys:org:getTreeData')") @GetMapping(value = "/getTreeData") public Result getTreeData() { List<ElTree> treeData = sysOrgService.getTreeData(); return Result.ok(treeData); } /** * 公共机构选择树 * * @param type 不同机构选择树策略(预留字段,可根据不同应用场景新增type,由前端输入) * @return */ @GetMapping(value = "/getSelectTreeData") public Result getSelectTreeData(String type) { // 默认返回当前用户数据权限范围的机构树 List<ElTree> treeData = sysOrgService.getTreeData(); return Result.ok(treeData); }}
package com.strongdata.workflow.modules.sys.controller;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysPostService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysPost;import com.strongdata.workflow.modules.sys.entity.SysPostUser;import com.strongdata.workflow.modules.sys.entity.SysUser;/** * 岗位Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/post")public class SysPostController extends BaseController { @Autowired private SysPostService sysPostService; /** * 自定义查询列表 * * @param sysPost * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:post:list')") @GetMapping(value = "/list") public Result list(SysPost sysPost, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysPost> pageList = sysPostService.list(new Page<SysPost>(current, size), sysPost); return Result.ok(pageList); } /** * 公共选岗查询 * * @param sysPost * @param current * @param size * @param selectPostIds 前端所选岗位id * @return */ @PreAuthorize("@elp.or('sys:post:listSelectPost')") @GetMapping(value = "/listSelectPost") public Result listSelectPost(SysPost sysPost, @RequestParam Integer current, @RequestParam Integer size,@RequestParam(required = false) String selectPostIds) { IPage<SysPost> pageList = sysPostService.listSelectPost(new Page<SysPost>(current, size), sysPost,selectPostIds); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:post:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysPost sysPost = sysPostService.getById(id); return Result.ok(sysPost); } /** * @param sysPost * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:post:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysPost sysPost) { sysPostService.save(sysPost); return Result.ok(); } /** * @param sysPost * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:post:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysPost sysPost) { sysPostService.updateById(sysPost); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:post:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } this.sysPostService.delete(ids); return Result.ok(); } /** * 获取岗位用户 * * @param sysPostUser * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:post:getPostUser')") @GetMapping(value = "/getPostUser") public Result getPostUser(SysPostUser sysPostUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysUser> pageList = this.sysPostService.getPostUser(new Page<SysUser>(current, size), sysPostUser); return Result.ok(pageList); } /** * 获取用户的岗位 * * @param sysPostUser * @param current * @param size * @param selectPostIds 前端所选岗位id * @return */ @PreAuthorize("@elp.or('sys:post:getUserPost')") @GetMapping(value = "/getUserPost") public Result getUserPost(SysPostUser sysPostUser, @RequestParam Integer current, @RequestParam Integer size,@RequestParam(required = false) String selectPostIds) { IPage<SysPost> pageList = this.sysPostService.getUserPost(new Page<SysPost>(current, size), sysPostUser,selectPostIds); return Result.ok(pageList); } /** * 保存岗位用户 * * @param sysPostUser * @return */ @Log(value = "保存岗位用户") @PreAuthorize("@elp.single('sys:post:savePostUsers')") @PostMapping(value = "/savePostUsers") public Result savePostUsers(@RequestBody SysPostUser sysPostUser) { this.sysPostService.savePostUsers(sysPostUser.getPostId(), sysPostUser.getUserId()); return Result.ok(); } /** * 删除岗位用户 * * @param postId * @param userIds * @return */ @Log(value = "删除岗位用户") @PreAuthorize("@elp.single('sys:post:deletePostUsers')") @DeleteMapping(value = "/deletePostUsers") public Result deletePostUsers(String postId, String userIds) { this.sysPostService.deletePostUsers(postId, userIds); return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysPostUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysPostUser;/** * 岗位和用户关系Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/postUser")public class SysPostUserController extends BaseController { @Autowired private SysPostUserService sysPostUserService; /** * 自定义查询列表 * * @param sysPostUser * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:postUser:list')") @GetMapping(value = "/list") public Result list(SysPostUser sysPostUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysPostUser> pageList = sysPostUserService.list(new Page<SysPostUser>(current, size), sysPostUser); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:postUser:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysPostUser sysPostUser = sysPostUserService.getById(id); return Result.ok(sysPostUser); } /** * @param sysPostUser * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:postUser:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysPostUser sysPostUser) { sysPostUserService.save(sysPostUser); return Result.ok(); } /** * @param sysPostUser * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:postUser:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysPostUser sysPostUser) { sysPostUserService.updateById(sysPostUser); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:postUser:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysPostUserService.removeByIds(Arrays.asList(idsArr)); } else { sysPostUserService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.List;import java.util.Map;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysRoleService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysRole;import com.strongdata.workflow.modules.sys.entity.SysRolePermission;import com.strongdata.workflow.modules.sys.entity.SysRoleUser;import com.strongdata.workflow.modules.sys.entity.SysUser;/** * 角色Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/role")public class SysRoleController extends BaseController { @Autowired private SysRoleService sysRoleService; /** * 自定义查询列表 * * @param sysRole * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:role:list')") @GetMapping(value = "/list") public Result list(SysRole sysRole, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysRole> pageList = sysRoleService.list(new Page<SysRole>(current, size), sysRole); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:role:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysRole sysRole = sysRoleService.getById(id); return Result.ok(sysRole); } /** * @param sysRole * @return * @功能:新增 */ @Log(value = "新增角色") @PreAuthorize("@elp.single('sys:role:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysRole sysRole) { sysRoleService.save(sysRole); return Result.ok(); } /** * @param sysRole * @return * @功能:修改 */ @Log(value = "修改角色") @PreAuthorize("@elp.single('sys:role:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysRole sysRole) { sysRoleService.updateById(sysRole); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除角色") @PreAuthorize("@elp.single('sys:role:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } this.sysRoleService.delete(ids); return Result.ok(); } /** * 查询角色权限 * * @param roleId * @return */ @PreAuthorize("@elp.single('sys:role:getRolePermissions')") @GetMapping(value = "/getRolePermissions") public Result getRolePermissions(String roleId) { Map<String, Object> data = this.sysRoleService.getRolePermissions(roleId); return Result.ok(data); } /** * 保存角色权限 * * @param roleId * @param menuOrFuncIds 菜单或者按钮ID * @param permissionTypes 权限类型 1-菜单 2-按钮 * @return */ @Log(value = "保存角色权限") @PreAuthorize("@elp.single('sys:role:saveRolePermissions')") @PostMapping(value = "/saveRolePermissions") public Result saveRolePermissions(@RequestBody SysRolePermission sysRolePermission) { this.sysRoleService.saveRolePermissions(sysRolePermission.getRoleId(), sysRolePermission.getMenuOrFuncId(), sysRolePermission.getPermissionType()); return Result.ok(); } /** * 获取角色用户 * * @param roleId * @return */ @PreAuthorize("@elp.single('sys:role:getRoleUser')") @GetMapping(value = "/getRoleUser") public Result getRoleUser(SysRoleUser sysRoleUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysUser> pageList = this.sysRoleService.getRoleUser(new Page<SysUser>(current, size), sysRoleUser); return Result.ok(pageList); } /** * 保存角色用户 * * @param sysRoleUser * @return */ @Log(value = "保存角色用户") @PreAuthorize("@elp.single('sys:role:saveRoleUsers')") @PostMapping(value = "/saveRoleUsers") public Result saveRoleUsers(@RequestBody SysRoleUser sysRoleUser) { this.sysRoleService.saveRoleUsers(sysRoleUser.getRoleId(), sysRoleUser.getUserId()); return Result.ok(); } /** * 删除角色用户 * * @param sysRoleUser * @return */ @Log(value = "删除角色用户") @PreAuthorize("@elp.single('sys:role:deleteRoleUsers')") @DeleteMapping(value = "/deleteRoleUsers") public Result deleteRoleUsers(String roleId, String userIds) { this.sysRoleService.deleteRoleUsers(roleId, userIds); return Result.ok(); } /** * 校验删除的角色用户的当前角色 * * @param roleId * @param userIds * @return */ @PreAuthorize("@elp.single('sys:role:verifyDeleteRoleUsers')") @GetMapping(value = "/verifyDeleteRoleUsers") public Result verifyDeleteRoleUsers(String roleId, String userIds) { return this.sysRoleService.verifyDeleteRoleUsers(roleId, userIds); } /** * 查询所有角色 * * @return */ @PreAuthorize("@elp.single('sys:role:listAll')") @GetMapping(value = "/listAll") public Result listAll() { QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>(); List<SysRole> roles = sysRoleService.list(queryWrapper.orderByAsc("sort_no")); return Result.ok(roles); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysRolePermissionService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysRolePermission;/** * 操作权限Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/rolePermission")public class SysRolePermissionController extends BaseController { @Autowired private SysRolePermissionService sysRolePermissionService; /** * 自定义查询列表 * * @param sysRolePermission * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:rolePermission:list')") @GetMapping(value = "/list") public Result list(SysRolePermission sysRolePermission, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysRolePermission> pageList = sysRolePermissionService.list(new Page<SysRolePermission>(current, size), sysRolePermission); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:rolePermission:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysRolePermission sysRolePermission = sysRolePermissionService.getById(id); return Result.ok(sysRolePermission); } /** * @param sysRolePermission * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:rolePermission:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysRolePermission sysRolePermission) { sysRolePermissionService.save(sysRolePermission); return Result.ok(); } /** * @param sysRolePermission * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:rolePermission:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysRolePermission sysRolePermission) { sysRolePermissionService.updateById(sysRolePermission); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:rolePermission:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysRolePermissionService.removeByIds(Arrays.asList(idsArr)); } else { sysRolePermissionService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import com.strongdata.workflow.modules.sys.service.SysRoleUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysRoleUser;/** * 角色和用户关系Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/roleUser")public class SysRoleUserController extends BaseController { @Autowired private SysRoleUserService sysRoleUserService; /** * 自定义查询列表 * * @param sysRoleUser * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:roleUser:list')") @GetMapping(value = "/list") public Result list(SysRoleUser sysRoleUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysRoleUser> pageList = sysRoleUserService.list(new Page<SysRoleUser>(current, size), sysRoleUser); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:roleUser:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysRoleUser sysRoleUser = sysRoleUserService.getById(id); return Result.ok(sysRoleUser); } /** * @param sysRoleUser * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:roleUser:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysRoleUser sysRoleUser) { sysRoleUserService.save(sysRoleUser); return Result.ok(); } /** * @param sysRoleUser * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:roleUser:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysRoleUser sysRoleUser) { sysRoleUserService.updateById(sysRoleUser); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:roleUser:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysRoleUserService.removeByIds(Arrays.asList(idsArr)); } else { sysRoleUserService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import java.util.Arrays;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysTenantApi;import com.strongdata.workflow.modules.sys.service.SysTenantApiService;/** * 租户Api接口服务Controller * * @author 王杰 */@RestController@RequestMapping("/sys/tenantApi")public class SysTenantApiController extends BaseController { @Autowired private SysTenantApiService sysTenantApiService; /** * 自定义查询列表 * * @param sysTenantApi * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:tenantApi:list')") @GetMapping(value = "/list") public Result list(SysTenantApi sysTenantApi, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysTenantApi> pageList = sysTenantApiService.list(new Page<SysTenantApi>(current, size), sysTenantApi); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:tenantApi:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysTenantApi sysTenantApi = sysTenantApiService.getById(id); return Result.ok(sysTenantApi); } /** * @功能:新增 * @param sysTenantApi * @return */ @PreAuthorize("@elp.single('sys:tenantApi:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysTenantApi sysTenantApi) { sysTenantApiService.save(sysTenantApi); return Result.ok(); } /** * @功能:修改 * @param sysTenantApi * @return */ @PreAuthorize("@elp.single('sys:tenantApi:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysTenantApi sysTenantApi) { sysTenantApiService.updateById(sysTenantApi); return Result.ok(); } /** * @功能:批量删除 * @param ids * @return */ @PreAuthorize("@elp.single('sys:tenantApi:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysTenantApiService.removeByIds(Arrays.asList(idsArr)); } else { sysTenantApiService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysTenantUser;import com.strongdata.workflow.modules.sys.entity.SysTenant;import com.strongdata.workflow.modules.sys.entity.SysUser;import com.strongdata.workflow.modules.sys.service.SysTenantService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.Arrays;/** * 租户主Controller * * @author 王杰 */@RestController@RequestMapping("/sys/tenant")public class SysTenantController extends BaseController { @Autowired private SysTenantService sysTenantService; /** * 自定义查询列表 * * @param sysTenant * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:tenant:list')") @GetMapping(value = "/list") public Result list(SysTenant sysTenant, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysTenant> pageList = sysTenantService.list(new Page<SysTenant>(current, size), sysTenant); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:tenant:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysTenant sysTenant = sysTenantService.getById(id); return Result.ok(sysTenant); } /** * @功能:新增 * @param sysTenant * @return */ @PreAuthorize("@elp.single('sys:tenant:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysTenant sysTenant) { sysTenantService.save(sysTenant); return Result.ok(); } /** * @功能:修改 * @param sysTenant * @return */ @PreAuthorize("@elp.single('sys:tenant:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysTenant sysTenant) { sysTenantService.updateById(sysTenant); return Result.ok(); } /** * @功能:批量删除 * @param ids * @return */ @PreAuthorize("@elp.single('sys:tenant:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); //修改为逻辑删除 sysTenantService.delete(Arrays.asList(idsArr)); return Result.ok(); } /** * 获取租户用户 * * @param sysTenantUser * @param current * @param size * @return */ @PreAuthorize("@elp.or('sys:tenant:getTenantUser')") @GetMapping(value = "/getTenantUser") public Result getTenantUser(SysTenantUser sysTenantUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysUser> pageList = this.sysTenantService.getTenantUser(new Page<SysUser>(current, size), sysTenantUser); return Result.ok(pageList); } /** * 保存租户用户 * * @param sysTenantUser * @return */ @Log(value = "保存租户用户") @PreAuthorize("@elp.or('sys:tenant:saveTenantUsers')") @PostMapping(value = "/saveTenantUsers") public Result saveTenantUsers(@RequestBody SysTenantUser sysTenantUser) { this.sysTenantService.saveTenantUsers(sysTenantUser.getTenantId(), sysTenantUser.getUserId()); return Result.ok(); } /** * 删除租户用户 * * @param tenantId * @param userIds * @return */ @Log(value = "删除岗位用户") @PreAuthorize("@elp.or('sys:tenant:deleteTenantUsers')") @DeleteMapping(value = "/deleteTenantUsers") public Result deleteTenantUsers(String tenantId, String userIds) { this.sysTenantService.deleteTenantUsers(tenantId, userIds); return Result.ok(); } /** * 公共选租户查询 * * @param sysTenant * @param current * @param size * @param selectTenantIds 前端所选租户id * @return */ @PreAuthorize("@elp.or('sys:post:listSelectTenant')") @GetMapping(value = "/listSelectTenant") public Result listSelectTenant(SysTenant sysTenant,@RequestParam Integer current, @RequestParam Integer size,@RequestParam(required = false) String selectTenantIds) { IPage<SysTenant> pageList = sysTenantService.listSelectTenant(new Page<SysTenant>(current, size), sysTenant,selectTenantIds); return Result.ok(pageList); } /** * 获取用户下的租户 * * @param sysTenant * @param current * @param size * @param selectTenantIds 前端所选租户id * @return */ @PreAuthorize("@elp.or('sys:post:getUserTenant')") @GetMapping(value = "/getUserTenant") public Result getUserTenant(SysTenant sysTenant,@RequestParam Integer current, @RequestParam Integer size,@RequestParam(required = false) String selectTenantIds) { IPage<SysTenant> pageList = sysTenantService.getUserTenant(new Page<SysTenant>(current, size), sysTenant,selectTenantIds); return Result.ok(pageList); }}
package com.strongdata.workflow.modules.sys.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.modules.sys.entity.SysTenantUser;import com.strongdata.workflow.modules.sys.service.SysTenantUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.Arrays;/** * 租户和用户关系Controller * * @author 王杰 */@RestController@RequestMapping("/sys/tenantUser")public class SysTenantUserController extends BaseController { @Autowired private SysTenantUserService sysTenantUserService; /** * 自定义查询列表 * * @param sysTenantUser * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:tenantUser:list')") @GetMapping(value = "/list") public Result list(SysTenantUser sysTenantUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysTenantUser> pageList = sysTenantUserService.list(new Page<SysTenantUser>(current, size), sysTenantUser); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:tenantUser:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysTenantUser sysTenantUser = sysTenantUserService.getById(id); return Result.ok(sysTenantUser); } /** * @param sysTenantUser * @return * @功能:新增 */ @PreAuthorize("@elp.single('sys:tenantUser:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysTenantUser sysTenantUser) { sysTenantUserService.save(sysTenantUser); return Result.ok(); } /** * @param sysTenantUser * @return * @功能:修改 */ @PreAuthorize("@elp.single('sys:tenantUser:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysTenantUser sysTenantUser) { sysTenantUserService.updateById(sysTenantUser); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @PreAuthorize("@elp.single('sys:tenantUser:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { if (ids == null || ids.trim().length() == 0) { return Result.error("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { sysTenantUserService.removeByIds(Arrays.asList(idsArr)); } else { sysTenantUserService.removeById(idsArr[0]); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.controller;import com.alibaba.excel.EasyExcel;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseController;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.SecurityUtils;import com.strongdata.workflow.common.log.annotation.Log;import com.strongdata.workflow.modules.sys.entity.SysUser;import com.strongdata.workflow.modules.sys.entity.vo.SysPasswordForm;import com.strongdata.workflow.modules.sys.entity.vo.SysUserInfo;import com.strongdata.workflow.modules.sys.service.SysUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.validation.Valid;import java.io.IOException;/** * 用户Controller * * @author 庄金明 */@RestController@RequestMapping("/sys/user")public class SysUserController extends BaseController { @Autowired private SysUserService sysUserService; /** * 自定义查询列表 * * @param sysUser * @param current * @param size * @return */ @PreAuthorize("@elp.single('sys:user:list')") @GetMapping(value = "/list") public Result list(SysUser sysUser, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysUser> pageList = sysUserService.list(new Page<SysUser>(current, size), sysUser); // QueryWrapper<SysUser> queryWrapper = QueryWrapperGenerator.initQueryWrapperSimple(sysUser); // IPage<SysUser> pageList = sysUserService.getBaseMapper().selectPage(new Page<SysUser>(current, size), // queryWrapper); return Result.ok(pageList); } /** * 公共选人查询 * * @param sysUser * @param current * @param size * @param type 区分哪个列表的选人 * @return */ @GetMapping(value = "/listSelectUser") public Result listSelectUser(SysUser sysUser,@RequestParam String type, @RequestParam Integer current, @RequestParam Integer size) { IPage<SysUser> pageList = sysUserService.listSelectUser(new Page<SysUser>(current, size), sysUser,type); return Result.ok(pageList); } @PreAuthorize("@elp.single('sys:user:list')") @GetMapping(value = "/queryById") public Result queryById(@RequestParam String id) { SysUser sysUser = sysUserService.getById(id); return Result.ok(sysUser); } /** * @param sysUser * @return * @功能:新增 */ @Log(value = "新增用户") @PreAuthorize("@elp.single('sys:user:save')") @PostMapping(value = "/save") public Result save(@Valid @RequestBody SysUser sysUser) { sysUserService.saveSysUser(sysUser); return Result.ok(); } /** * @param sysUser * @return * @功能:修改 */ @Log(value = "修改用户") @PreAuthorize("@elp.single('sys:user:update')") @PutMapping(value = "/update") public Result update(@Valid @RequestBody SysUser sysUser) { sysUserService.updateSysUser(sysUser); return Result.ok(); } /** * @param ids * @return * @功能:批量删除 */ @Log(value = "删除用户") @PreAuthorize("@elp.single('sys:user:delete')") @DeleteMapping(value = "/delete") public Result delete(@RequestParam String ids) { sysUserService.delete(ids); return Result.ok(); } @Log(value = "获取用户信息") @GetMapping(value = "/getUserInfo") public Result getUserInfo(@RequestParam(required = false) String roleId, HttpServletRequest request) { SysUserInfo sysUserInfo = sysUserService.saveGetUserInfo(SecurityUtils.getUserId(), roleId); return Result.ok(sysUserInfo); } @PostMapping(value = "/updatePassword") public Result updatePassword(@RequestBody SysPasswordForm sysPasswordForm) { boolean success = sysUserService.updatePassword(sysPasswordForm); if (!success) { return Result.error("原密码错误"); } return Result.ok(); } @Log(value = "导出用户信息") @PreAuthorize("@elp.single('sys:user:export')") @GetMapping(value = "/export") public void export(SysUser sysUser, HttpServletResponse response) throws IOException { try { IPage<SysUser> page = sysUserService.list(null, sysUser); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=SysUserExport.xlsx"); EasyExcel.write(response.getOutputStream(), SysUser.class).sheet("SysUser").doWrite(page.getRecords()); } catch (Exception e) { throw new SysException("下载文件失败:" + e.getMessage()); } }}
package com.strongdata.workflow.modules.sys.controller;import cn.hutool.core.map.MapUtil;import cn.hutool.core.util.StrUtil;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.constant.Constants;import com.strongdata.workflow.common.core.util.SpringContextUtils;import com.strongdata.workflow.common.security.component.authorization.controller.MarkController;import com.strongdata.workflow.modules.sys.entity.SysOauthClientDetails;import com.strongdata.workflow.modules.sys.service.SysOauthClientDetailsService;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.cache.CacheManager;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.http.HttpHeaders;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.security.authentication.event.LogoutSuccessEvent;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.common.OAuth2RefreshToken;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.web.bind.annotation.*;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;/** * @author zjm * @author wangjie */@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/token")public class TokenController extends MarkController { private final TokenStore tokenStore; private final RedisTemplate<String, Object> redisTemplate; private final CacheManager cacheManager; private final CheckTokenEndpoint checkTokenEndpoint; private final SysOauthClientDetailsService sysOauthClientDetailsService; /** * 退出并删除token * @param authHeader * @return */ @DeleteMapping("/logout") public Result logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { if (StrUtil.isBlank(authHeader)) { return Result.ok(); } String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim(); return removeToken(tokenValue); } /** * 校验租户token * @param value token值 * @param tenantId 租户id * @return */ @GetMapping("/check_token") public Result checkToken(@RequestParam("token") String value, @RequestHeader("tenantId") String tenantId) { Map<String, ?> stringMap = checkTokenEndpoint.checkToken(value); LambdaQueryWrapper<SysOauthClientDetails> queryWrapper = Wrappers.lambdaQuery(SysOauthClientDetails.class).eq(SysOauthClientDetails::getTenantId, tenantId); List<SysOauthClientDetails> list = sysOauthClientDetailsService.list(queryWrapper); String clientId = (list != null && !list.isEmpty()) ? list.get(0).getClientId() : null; if(StringUtils.isNotBlank(clientId)){ Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId(clientId); List<OAuth2AccessToken> collect = tokens.stream().filter(token -> value.equals(token.getValue())).collect(Collectors.toList()); if(collect != null && !collect.isEmpty()){ return Result.ok(stringMap); } } return Result.error("The token is not that of the current tenant"); } /** * 删除token * 令牌管理调用 * @param token token */ @PreAuthorize("@elp.single('sys:tokenList:delete')") @DeleteMapping("/{token}") public Result<Boolean> removeToken(@PathVariable("token") String token) { OAuth2AccessToken accessToken = tokenStore.readAccessToken(token); if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) { return Result.ok(); } OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken); // 清空用户信息 cacheManager.getCache(CacheConstants.USER_DETAILS).evict(auth2Authentication.getName()); // 清空access token tokenStore.removeAccessToken(accessToken); // 清空 refresh token OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); tokenStore.removeRefreshToken(refreshToken); // 处理自定义退出事件,保存相关日志 SpringContextUtils.publishEvent(new LogoutSuccessEvent(auth2Authentication)); return Result.ok(); } /** * 查询token * @param params 分页参数 * @return */ @PreAuthorize("@elp.single('sys:tokenList:list')") @PostMapping("/page") public Result<Page> tokenList(@RequestBody Map<String, Object> params) { // 根据分页参数获取对应数据 String key = String.format("%sauth_to_access:*", CacheConstants.OAUTH_ACCESS); int current = MapUtil.getInt(params, Constants.CURRENT); int size = MapUtil.getInt(params, Constants.SIZE); Set<String> keys = redisTemplate.keys(key); List<String> pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); Page result = new Page(current, size); result.setRecords(redisTemplate.opsForValue().multiGet(pages)); result.setTotal(keys.size()); return Result.ok(result); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.redis.util.RedisUtil;import com.strongdata.workflow.common.core.util.CommonUtil;import com.strongdata.workflow.modules.sys.entity.SysCodeInfo;import com.strongdata.workflow.modules.sys.mapper.SysCodeInfoMapper;import com.strongdata.workflow.modules.sys.service.SysCodeInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.*;/** * 代码信息ServiceImpl * * @author 庄金明 */@Servicepublic class SysCodeInfoServiceImpl extends BaseServiceImpl<SysCodeInfoMapper, SysCodeInfo> implements SysCodeInfoService { @Autowired private RedisUtil redisUtil; @Override public IPage<SysCodeInfo> list(IPage<SysCodeInfo> page, SysCodeInfo sysCodeInfo) { return page.setRecords(baseMapper.list(page, sysCodeInfo)); } /** * 加载数据字典进redis * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 */ @Override public void loadSysCodeInfoToRedis(String codeTypeIds) { if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { String[] codeTypeIdsArr = codeTypeIds.split(","); for (String codeTypeId : codeTypeIdsArr) { // 先清除 redisUtil.del(CacheConstants.SYS_CODE_TYPE + codeTypeId); } } else { // 先清除 redisUtil.delPattern(CacheConstants.SYS_CODE_TYPE + "*"); } Map<String, List<SysCodeInfo>> codeInfoMap = getSysCodeInfosFromDb(codeTypeIds); for (String codeInfoMapKey : codeInfoMap.keySet()) { redisUtil.set(CacheConstants.SYS_CODE_TYPE + codeInfoMapKey, codeInfoMap.get(codeInfoMapKey)); } } /** * 从数据库查询数据字典 * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 * @return */ @Override public Map<String, List<SysCodeInfo>> getSysCodeInfosFromDb(String codeTypeIds) { Map<String, List<SysCodeInfo>> codeInfoMap = new HashMap<String, List<SysCodeInfo>>(16); QueryWrapper<SysCodeInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("IS_OK", "1"); if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { queryWrapper.in("CODE_TYPE_ID", (Object[]) codeTypeIds.split(",")); } queryWrapper.orderByAsc("CODE_TYPE_ID", "SORT_NO"); List<SysCodeInfo> codeInfoList = this.list(queryWrapper); for (SysCodeInfo sysCodeInfo : codeInfoList) { List<SysCodeInfo> subList = null; if (!codeInfoMap.containsKey(sysCodeInfo.getCodeTypeId())) { subList = new ArrayList<SysCodeInfo>(); SysCodeInfo emptySysCodeInfo = new SysCodeInfo(); emptySysCodeInfo.setCodeInfoId(""); emptySysCodeInfo.setCodeTypeId(sysCodeInfo.getCodeTypeId()); emptySysCodeInfo.setContent(""); emptySysCodeInfo.setValue(""); emptySysCodeInfo.setSortNo(-999); subList.add(emptySysCodeInfo); } else { subList = codeInfoMap.get(sysCodeInfo.getCodeTypeId()); } subList.add(sysCodeInfo); codeInfoMap.put(sysCodeInfo.getCodeTypeId(), subList); } return codeInfoMap; } /** * 查询数据字典 * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 * @return */ @Override @SuppressWarnings("unchecked") public Map<String, List<SysCodeInfo>> getSysCodeInfosFromRedis(String codeTypeIds) { Set<String> keys = null; if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { keys = new HashSet<>(); String[] codeTypeIdsArr = codeTypeIds.split(","); for (String codeTypeId : codeTypeIdsArr) { keys.add(CacheConstants.SYS_CODE_TYPE + codeTypeId); } } else { keys = redisUtil.keysPattern(CacheConstants.SYS_CODE_TYPE + "*"); } Map<String, List<SysCodeInfo>> codeInfoMap = null; if (keys != null && keys.size() > 0) { codeInfoMap = new HashMap<String, List<SysCodeInfo>>(16); for (String key : keys) { codeInfoMap.put(key.replace(CacheConstants.SYS_CODE_TYPE, ""), (List<SysCodeInfo>) redisUtil.get(key)); } } return codeInfoMap; } /** * 新增代码信息,并加载进redis缓存 * * @param sysCodeInfo */ @Override @Transactional(rollbackFor = Exception.class) public void saveSysCodeInfo(SysCodeInfo sysCodeInfo) { this.save(sysCodeInfo); this.loadSysCodeInfoToRedis(sysCodeInfo.getCodeTypeId()); } /** * 修改代码信息,并加载进redis缓存 * * @param sysCodeInfo */ @Override @Transactional(rollbackFor = Exception.class) public void updateSysCodeInfo(SysCodeInfo sysCodeInfo) { this.updateById(sysCodeInfo); this.loadSysCodeInfoToRedis(sysCodeInfo.getCodeTypeId()); } /** * 删除代码信息,并重新加载redis缓存 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void deleteSysCodeInfo(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { this.removeByIds(Arrays.asList(idsArr)); } else { this.removeById(idsArr[0]); } this.loadSysCodeInfoToRedis(null); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.redis.util.RedisUtil;import com.strongdata.workflow.modules.sys.entity.SysCodeInfo;import com.strongdata.workflow.modules.sys.entity.SysCodeType;import com.strongdata.workflow.modules.sys.mapper.SysCodeTypeMapper;import com.strongdata.workflow.modules.sys.service.SysCodeInfoService;import com.strongdata.workflow.modules.sys.service.SysCodeTypeService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Arrays;/** * 代码类别Service * * @author 庄金明 */@Servicepublic class SysCodeTypeServiceImpl extends BaseServiceImpl<SysCodeTypeMapper, SysCodeType> implements SysCodeTypeService { @Autowired private SysCodeInfoService sysCodeInfoService; @Autowired private RedisUtil redisUtil; @Override public IPage<SysCodeType> list(IPage<SysCodeType> page, SysCodeType sysCodeType) { return page.setRecords(baseMapper.list(page, sysCodeType)); } /** * 删除数据字典信息 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void deleteSysCodeType(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { removeByIds(Arrays.asList(idsArr)); } else { removeById(idsArr[0]); } sysCodeInfoService.remove(new QueryWrapper<SysCodeInfo>().in("code_type_id", (Object[]) idsArr)); for (String codeTypeId : idsArr) { redisUtil.del(CacheConstants.SYS_CODE_TYPE + codeTypeId); } }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.redis.util.RedisUtil;import com.strongdata.workflow.common.core.util.CommonUtil;import com.strongdata.workflow.modules.sys.entity.SysConfig;import com.strongdata.workflow.modules.sys.mapper.SysConfigMapper;import com.strongdata.workflow.modules.sys.service.SysConfigService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Arrays;import java.util.List;/** * 系统参数Service * * @author 庄金明 */@Servicepublic class SysConfigServiceImpl extends BaseServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService { @Autowired private RedisUtil redisUtil; @Override public IPage<SysConfig> list(IPage<SysConfig> page, SysConfig sysConfig) { return page.setRecords(baseMapper.list(page, sysConfig)); } @Override public void loadSysConfigToRedis(String configIds) { String[] configIdsArr = null; if (CommonUtil.isNotEmptyAfterTrim(configIds)) { configIdsArr = configIds.split(","); for (String configId : configIdsArr) { // 先清除 redisUtil.del(CacheConstants.SYS_CONFIG + configId); } } else { // 先清除 redisUtil.delPattern(CacheConstants.SYS_CONFIG + "*"); } QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>(); if (configIdsArr != null && configIdsArr.length > 0) { queryWrapper.in("config_id", (Object[]) configIdsArr); } queryWrapper.orderByAsc("SORT_NO"); List<SysConfig> list = this.list(queryWrapper); for (SysConfig sysConfig : list) { redisUtil.set(CacheConstants.SYS_CONFIG + sysConfig.getConfigId(), sysConfig.getConfigValue()); } } /** * 保存系统参数,并加载进redis缓存 * * @param sysConfig */ @Override @Transactional(rollbackFor = Exception.class) public void saveSysConfig(SysConfig sysConfig) { this.save(sysConfig); this.loadSysConfigToRedis(sysConfig.getConfigId()); } /** * 修改系统参数,并加载进redis缓存 * * @param sysConfig */ @Override @Transactional(rollbackFor = Exception.class) public void updateSysConfig(SysConfig sysConfig) { this.updateById(sysConfig); this.loadSysConfigToRedis(sysConfig.getConfigId()); } /** * 删除系统参数,并重新加载redis缓存 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void deleteSysConfig(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { this.removeByIds(Arrays.asList(idsArr)); } else { this.removeById(idsArr[0]); } this.loadSysConfigToRedis(null); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.strongdata.workflow.modules.sys.mapper.SysDataPermissionMapper;import com.strongdata.workflow.modules.sys.service.SysDataPermissionService;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysDataPermission;/** * 数据权限Service * * @author 庄金明 */@Servicepublic class SysDataPermissionServiceImpl extends BaseServiceImpl<SysDataPermissionMapper, SysDataPermission> implements SysDataPermissionService { @Override public IPage<SysDataPermission> list(IPage<SysDataPermission> page, SysDataPermission sysDataPermission) { return page.setRecords(baseMapper.list(page, sysDataPermission)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.strongdata.workflow.modules.sys.mapper.SysFuncMapper;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysFunc;import com.strongdata.workflow.modules.sys.service.SysFuncService;/** * 功能Service * * @author 庄金明 */@Servicepublic class SysFuncServiceImpl extends BaseServiceImpl<SysFuncMapper, SysFunc> implements SysFuncService { @Override public IPage<SysFunc> list(IPage<SysFunc> page, SysFunc sysFunc) { return page.setRecords(baseMapper.list(page, sysFunc)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.base.LogInfo;import com.strongdata.workflow.modules.sys.entity.SysLog;import com.strongdata.workflow.modules.sys.mapper.SysLogMapper;import com.strongdata.workflow.modules.sys.service.SysLogService;import com.strongdata.workflow.common.core.base.LogService;import org.springframework.beans.BeanUtils;import org.springframework.stereotype.Service;/** * 系统日志Service * * @author 庄金明 */@Servicepublic class SysLogServiceImpl extends BaseServiceImpl<SysLogMapper, SysLog> implements SysLogService, LogService { @Override public IPage<SysLog> list(IPage<SysLog> page, SysLog sysLog) { return page.setRecords(baseMapper.list(page, sysLog)); } @Override public Result save(LogInfo logInfo, String inner) { SysLog sysLog = new SysLog(); BeanUtils.copyProperties(logInfo, sysLog); save(sysLog); return Result.ok(); }}
package com.strongdata.workflow.modules.sys.service.impl;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import com.strongdata.workflow.modules.sys.common.SysConstants;import com.strongdata.workflow.modules.sys.mapper.SysMenuMapper;import com.strongdata.workflow.modules.sys.service.SysFuncService;import com.strongdata.workflow.modules.sys.service.SysMenuService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.CommonUtil;import com.strongdata.workflow.modules.sys.entity.SysFunc;import com.strongdata.workflow.modules.sys.entity.SysMenu;import com.strongdata.workflow.modules.sys.entity.vo.ElTree;/** * 菜单Service * * @author 庄金明 */@Servicepublic class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService { @Autowired private SysFuncService sysFuncService; @Override public IPage<SysMenu> list(IPage<SysMenu> page, SysMenu sysMenu) { return page.setRecords(baseMapper.list(page, sysMenu)); } /** * 新增菜单,自动计算是否叶子 * * @param sysMenu * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean saveSysMenu(SysMenu sysMenu) { // 【1】 判断是否有上级菜单 if (!CommonUtil.isEmptyStr(sysMenu.getParentMenuId())) { // 父节点 SysMenu parentSysMenu = this.getById(sysMenu.getParentMenuId()); if (parentSysMenu == null) { throw new SysException("保存失败,上级菜单ID【" + sysMenu.getParentMenuId() + "】不存在!"); } // 【2】设置新增菜单的父菜单是否叶子为否 if (!SysConstants.IS_LEAF_0.equals(parentSysMenu.getIsLeaf())) { parentSysMenu.setIsLeaf(SysConstants.IS_LEAF_0); this.updateById(parentSysMenu); } } // 【3】设置新增菜单是否叶子为 是 sysMenu.setIsLeaf("1"); return this.save(sysMenu); } /** * 修改菜单 * * @param sysMenu * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean updateSysMenu(SysMenu sysMenu) { SysMenu sysMenuDb = this.getById(sysMenu.getMenuId()); if (sysMenuDb == null) { throw new SysException("保存失败,菜单ID【" + sysMenu.getMenuId() + "】不存在!"); } String parentMenuIdDb = sysMenuDb.getParentMenuId() == null ? "" : sysMenuDb.getParentMenuId().toString(); String parentMenuId = sysMenu.getParentMenuId() == null ? "" : sysMenu.getParentMenuId().toString(); if (!parentMenuIdDb.equals(parentMenuId)) { throw new SysException("不允许修改父菜单!"); } // 【1】 判断是否有上级菜单 if (!CommonUtil.isEmptyStr(parentMenuId)) { // 父节点 SysMenu parentSysMenu = this.getById(sysMenu.getParentMenuId()); if (parentSysMenu == null) { throw new SysException("保存失败,上级菜单ID【" + sysMenu.getParentMenuId() + "】不存在!"); } // 【2】设置新增菜单的父菜单是否叶子为否 if (!SysConstants.IS_LEAF_0.equals(parentSysMenu.getIsLeaf())) { parentSysMenu.setIsLeaf(SysConstants.IS_LEAF_0); this.updateById(parentSysMenu); } } return this.updateById(sysMenu); } /** * @param id * @return * @功能:批量删除 */ @Override @Transactional(rollbackFor = Exception.class) public boolean delete(String id) { int countChildren = this.count(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentMenuId, id)); if (countChildren > 0) { throw new SysException("请先删除叶子节点"); } SysMenu sysMenu = this.getById(id); boolean result = this.removeById(id); // 删除功能 sysFuncService.remove(new LambdaQueryWrapper<SysFunc>().eq(SysFunc::getMenuId, id)); if (!CommonUtil.isEmptyStr(sysMenu.getParentMenuId())) { // 若父菜单的下级菜单为空,则修改为是叶子节点 int countParentChildren = this.count(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentMenuId, sysMenu.getParentMenuId())); if (countParentChildren == 0) { SysMenu parentSysMenu = this.getById(sysMenu.getParentMenuId()); parentSysMenu.setIsLeaf("1"); this.updateById(parentSysMenu); } } return result; } /** * 菜单管理,菜单树数据 * * @return */ @Override public List<ElTree> getTreeData() { List<SysMenu> list = baseMapper.list(null, new SysMenu()); Map<String, ElTree> menuMap = new LinkedHashMap<String, ElTree>(); for (SysMenu sysMenu : list) { ElTree elTree = new ElTree(); elTree.setId(sysMenu.getMenuId()); elTree.setLabel(sysMenu.getMenuName()); elTree.setIsLeaf("1".equals(sysMenu.getIsLeaf())); elTree.setData(sysMenu); menuMap.put(sysMenu.getMenuId(), elTree); if (CommonUtil.isNotEmptyStr(sysMenu.getParentMenuId()) && menuMap.containsKey(sysMenu.getParentMenuId())) { elTree.setParentId(sysMenu.getParentMenuId()); ElTree parentElTree = menuMap.get(sysMenu.getParentMenuId()); parentElTree.addChildren(elTree); } } List<ElTree> result = new ArrayList<ElTree>(); menuMap.forEach((k, v) -> { if (CommonUtil.isEmptyStr(v.getParentId())) { result.add(v); } }); return result; }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.PasswordUtil;import com.strongdata.workflow.modules.sys.entity.SysOauthClientDetails;import com.strongdata.workflow.modules.sys.mapper.SysOauthClientDetailsMapper;import com.strongdata.workflow.modules.sys.service.SysOauthClientDetailsService;import org.springframework.cache.annotation.CacheEvict;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Arrays;/** * 应用客户端Service * * @author 庄金明 */@Servicepublic class SysOauthClientDetailsServiceImpl extends BaseServiceImpl<SysOauthClientDetailsMapper, SysOauthClientDetails> implements SysOauthClientDetailsService { @Override public IPage<SysOauthClientDetails> list(IPage<SysOauthClientDetails> page, SysOauthClientDetails sysOauthClientDetails) { return page.setRecords(baseMapper.list(page, sysOauthClientDetails)); } /** * 通过ID删除客户端 * * @param ids * @return */ @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.OAUTH_CLIENT_DETAILS, allEntries = true) public boolean delete(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { return removeByIds(Arrays.asList(idsArr)); } else { return removeById(idsArr[0]); } } @Override public boolean saveSysOauthClientDetails(SysOauthClientDetails clientDetails) { String clientSecret = PasswordUtil.encryptPassword(clientDetails.getClientSecret()); clientDetails.setClientSecret(clientSecret); return this.save(clientDetails); } /** * 根据客户端信息 * * @param clientDetails * @return */ @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.OAUTH_CLIENT_DETAILS, key = "#clientDetails.clientId") public boolean updateSysOauthClientDetails(SysOauthClientDetails clientDetails) { SysOauthClientDetails aSysOauthClientDetails = this.getById(clientDetails.getClientId()); if (!clientDetails.getClientSecret().equals(aSysOauthClientDetails.getClientSecret())) { String clientSecret = PasswordUtil.encryptPassword(clientDetails.getClientSecret()); clientDetails.setClientSecret(clientSecret); } return this.updateById(clientDetails); }}
package com.strongdata.workflow.modules.sys.service.impl;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import com.strongdata.workflow.modules.sys.common.SysConstants;import com.strongdata.workflow.modules.sys.mapper.SysOrgMapper;import com.strongdata.workflow.modules.sys.service.SysOrgService;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.CommonUtil;import com.strongdata.workflow.modules.sys.entity.SysOrg;import com.strongdata.workflow.modules.sys.entity.vo.ElTree;/** * 机构Service * * @author 庄金明 */@Servicepublic class SysOrgServiceImpl extends BaseServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService { @Override public IPage<SysOrg> list(IPage<SysOrg> page, SysOrg sysOrg) { return page.setRecords(baseMapper.list(page, sysOrg)); } /** * 新增机构,自动计算机构级别、机构级次码、是否叶子 * * @param sysOrg * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean saveSysOrg(SysOrg sysOrg) { // 【1】 校验id是否重复. if (CommonUtil.isEmptyStr(sysOrg.getParentOrgId())) { throw new SysException("保存失败,请先选择上级机构!"); } // 父节点 SysOrg parentSysOrg = this.getById(sysOrg.getParentOrgId()); if (parentSysOrg == null) { throw new SysException("保存失败,上级机构ID【" + sysOrg.getParentOrgId() + "】不存在!"); } // 【2】计算机构级次,机构级次码 // 【2-a】设置新增机构的父机构是否叶子为否 if (!SysConstants.IS_LEAF_0.equals(parentSysOrg.getIsLeaf())) { parentSysOrg.setIsLeaf(SysConstants.IS_LEAF_0); this.updateById(parentSysOrg); } Integer orgLevel = Integer.valueOf(parentSysOrg.getOrgLevel()) + 1; sysOrg.setOrgLevel(orgLevel.toString()); sysOrg.setOrgLevelCode(parentSysOrg.getOrgLevelCode() + "," + sysOrg.getOrgId()); // 【3】设置新增机构是否叶子为 是; sysOrg.setIsLeaf("1"); return this.save(sysOrg); } /** * 修改机构,自动计算机构级别、机构级次码、是否叶子 * * @param sysOrg * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean updateSysOrg(SysOrg sysOrg) { if (CommonUtil.isEmptyStr(sysOrg.getParentOrgId())) { sysOrg.setOrgLevel("1"); sysOrg.setOrgLevelCode(sysOrg.getOrgId()); return this.updateById(sysOrg); } // 父节点 SysOrg parentSysOrg = this.getById(sysOrg.getParentOrgId()); if (parentSysOrg == null) { throw new SysException("保存失败,上级机构ID【" + sysOrg.getParentOrgId() + "】不存在!"); } // 【2】计算机构级次,机构级次码 // 【2-a】设置新增机构的父机构是否叶子为否 if (!SysConstants.IS_LEAF_0.equals(parentSysOrg.getIsLeaf())) { parentSysOrg.setIsLeaf(SysConstants.IS_LEAF_0); this.updateById(parentSysOrg); } Integer orgLevel = Integer.valueOf(parentSysOrg.getOrgLevel()) + 1; sysOrg.setOrgLevel(orgLevel.toString()); sysOrg.setOrgLevelCode(parentSysOrg.getOrgLevelCode() + "," + sysOrg.getOrgId()); return this.updateById(sysOrg); } /** * 机构管理,机构树数据 * * @return */ @Override public List<ElTree> getTreeData() { List<SysOrg> orgList = baseMapper.list(null, new SysOrg()); return makeOrgTree(orgList); } /** * 生成机构树 * * @param orgList * @return */ @Override public List<ElTree> makeOrgTree(List<SysOrg> orgList) { Map<String, ElTree> orgMap = new LinkedHashMap<String, ElTree>(); for (SysOrg sysOrg : orgList) { ElTree elTree = new ElTree(); elTree.setId(sysOrg.getOrgId()); elTree.setLabel(sysOrg.getOrgName()); elTree.setIsLeaf("1".equals(sysOrg.getIsLeaf())); elTree.setData(sysOrg); orgMap.put(sysOrg.getOrgId(), elTree); if (CommonUtil.isNotEmptyStr(sysOrg.getParentOrgId()) && orgMap.containsKey(sysOrg.getParentOrgId())) { elTree.setParentId(sysOrg.getParentOrgId()); ElTree parentElTree = orgMap.get(sysOrg.getParentOrgId()); parentElTree.addChildren(elTree); } } List<ElTree> result = new ArrayList<ElTree>(); orgMap.forEach((k, v) -> { if (CommonUtil.isEmptyStr(v.getParentId())) { result.add(v); } }); return result; }}
package com.strongdata.workflow.modules.sys.service.impl;import java.util.Arrays;import java.util.List;import com.strongdata.workflow.modules.sys.mapper.SysPostMapper;import com.strongdata.workflow.modules.sys.service.SysPostService;import com.strongdata.workflow.modules.sys.service.SysPostUserService;import org.apache.commons.lang3.StringUtils;import org.flowable.idm.engine.impl.GroupQueryImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysPost;import com.strongdata.workflow.modules.sys.entity.SysPostUser;import com.strongdata.workflow.modules.sys.entity.SysUser;/** * 岗位Service * * @author 庄金明 */@Servicepublic class SysPostServiceImpl extends BaseServiceImpl<SysPostMapper, SysPost> implements SysPostService { @Autowired private SysPostUserService sysPostUserService; @Override public IPage<SysPost> list(IPage<SysPost> page, SysPost sysPost) { return page.setRecords(baseMapper.list(page, sysPost)); } /** * 查询岗位用户 * * @param page * @param sysPostUser * @return */ @Override public IPage<SysUser> getPostUser(Page<SysUser> page, SysPostUser sysPostUser) { return page.setRecords(baseMapper.getPostUser(page, sysPostUser)); } /** * 保存岗位用户 * * @param postId * @param userIds */ @Override @Transactional(rollbackFor = Exception.class) public void savePostUsers(String postId, String userIds) { String[] userIdArray = userIds.split(","); // 【1】先删除岗位用户 QueryWrapper<SysPostUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("POST_ID", postId).in("USER_ID", (Object[]) userIdArray); this.sysPostUserService.remove(queryWrapper); // 【2】保存岗位用户 for (int i = 0; i < userIdArray.length; i++) { SysPostUser sysPostUser = new SysPostUser(postId, userIdArray[i]); this.sysPostUserService.save(sysPostUser); } } /** * 删除岗位用户 * * @param postId * @param userIds */ @Override @Transactional(rollbackFor = Exception.class) public void deletePostUsers(String postId, String userIds) { QueryWrapper<SysPostUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("POST_ID", postId).in("USER_ID", (Object[]) userIds.split(",")); this.sysPostUserService.remove(queryWrapper); } /** * 删除岗位 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void delete(String ids) { String[] idsArr = ids.split(","); if (idsArr.length > 1) { this.removeByIds(Arrays.asList(idsArr)); } else { this.removeById(idsArr[0]); } this.sysPostUserService.remove(new QueryWrapper<SysPostUser>().in("POST_ID", (Object[]) idsArr)); } /** * 根据Flowable GroupQueryImpl查询岗位列表 * * @param query * @return */ @Override public List<SysPost> getPostsByFlowableGroupQueryImpl(GroupQueryImpl query) { return this.baseMapper.getPostsByFlowableGroupQueryImpl(query); } /** * 公共选岗查询 * @param sysPost * @param sysPost * @param selectPostIds 前端所选岗位id * @return */ @Override public IPage<SysPost> listSelectPost(IPage<SysPost> page, SysPost sysPost,String selectPostIds) { List<String> selectPostIdsList = StringUtils.isNotBlank(selectPostIds) ? Arrays.asList(selectPostIds.split(",")) : null; return page.setRecords(baseMapper.listSelectPost(page, sysPost, selectPostIdsList)); } /** * 获取用户的岗位 * @param page * @param sysPostUser * @param selectPostIds 前端所选岗位id * @return */ @Override public IPage<SysPost> getUserPost(IPage<SysPost> page, SysPostUser sysPostUser,String selectPostIds) { List<String> selectPostIdsList = StringUtils.isNotBlank(selectPostIds) ? Arrays.asList(selectPostIds.split(",")) : null; return page.setRecords(baseMapper.getUserPost(page, sysPostUser,selectPostIdsList)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.strongdata.workflow.modules.sys.mapper.SysPostUserMapper;import com.strongdata.workflow.modules.sys.service.SysPostUserService;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysPostUser;/** * 岗位和用户关系Service * * @author 庄金明 */@Servicepublic class SysPostUserServiceImpl extends BaseServiceImpl<SysPostUserMapper, SysPostUser> implements SysPostUserService { @Override public IPage<SysPostUser> list(IPage<SysPostUser> page, SysPostUser sysPostUser) { return page.setRecords(baseMapper.list(page, sysPostUser)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.strongdata.workflow.modules.sys.mapper.SysRolePermissionMapper;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysRolePermission;import com.strongdata.workflow.modules.sys.service.SysRolePermissionService;/** * 操作权限Service * * @author 庄金明 */@Servicepublic class SysRolePermissionServiceImpl extends BaseServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService { @Override public IPage<SysRolePermission> list(IPage<SysRolePermission> page, SysRolePermission sysRolePermission) { return page.setRecords(baseMapper.list(page, sysRolePermission)); }}
package com.strongdata.workflow.modules.sys.service.impl;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.stream.Collectors;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.modules.sys.mapper.SysFuncMapper;import com.strongdata.workflow.modules.sys.mapper.SysMenuMapper;import com.strongdata.workflow.modules.sys.mapper.SysRoleMapper;import com.strongdata.workflow.modules.sys.service.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.exception.AppException;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.CommonUtil;import com.strongdata.workflow.modules.sys.entity.SysFunc;import com.strongdata.workflow.modules.sys.entity.SysMenu;import com.strongdata.workflow.modules.sys.entity.SysRole;import com.strongdata.workflow.modules.sys.entity.SysRolePermission;import com.strongdata.workflow.modules.sys.entity.SysRoleUser;import com.strongdata.workflow.modules.sys.entity.SysUser;import com.strongdata.workflow.modules.sys.entity.vo.ElTree;/** * 角色Service * * @author 庄金明 */@Servicepublic class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { @Autowired private SysMenuService sysMenuService; @Autowired private SysFuncService sysFuncService; @Autowired private SysRolePermissionService sysRolePermissionService; @Autowired private SysRoleUserService sysRoleUserService; @Lazy @Autowired private SysUserService sysUserService; @Override public IPage<SysRole> list(IPage<SysRole> page, SysRole sysRole) { return page.setRecords(baseMapper.list(page, sysRole)); } /** * 查询角色权限 * * @param sysUser * @param roleId * @return */ @Override public Map<String, Object> getRolePermissions(String roleId) { List<SysMenu> menus = ((SysMenuMapper) sysMenuService.getBaseMapper()).list(null, new SysMenu()); List<SysFunc> funcs = ((SysFuncMapper) sysFuncService.getBaseMapper()).list(null, new SysFunc()); Map<String, List<ElTree>> funcMap = new LinkedHashMap<String, List<ElTree>>(); for (SysFunc sysFunc : funcs) { ElTree elTree = new ElTree(); elTree.setId(sysFunc.getFuncId()); elTree.setLabel(sysFunc.getFuncName()); elTree.setIsLeaf(true); SysRolePermission rolePermission = new SysRolePermission("2", sysFunc.getFuncId(), sysFunc.getFuncName()); elTree.setData(rolePermission); List<ElTree> funcsGroup = null; if (funcMap.containsKey(sysFunc.getMenuId())) { funcsGroup = funcMap.get(sysFunc.getMenuId()); } else { funcsGroup = new ArrayList<>(); } funcsGroup.add(elTree); funcMap.put(sysFunc.getMenuId(), funcsGroup); } Map<String, ElTree> menuMap = new LinkedHashMap<String, ElTree>(); for (SysMenu sysMenu : menus) { ElTree elTree = new ElTree(); elTree.setId(sysMenu.getMenuId()); elTree.setLabel(sysMenu.getMenuName()); SysRolePermission rolePermission = new SysRolePermission("1", sysMenu.getMenuId(), sysMenu.getMenuName()); elTree.setData(rolePermission); if (funcMap.containsKey(sysMenu.getMenuId())) { elTree.setIsLeaf(false); elTree.addChildrens(funcMap.get(sysMenu.getMenuId())); } menuMap.put(sysMenu.getMenuId(), elTree); if (CommonUtil.isNotEmptyStr(sysMenu.getParentMenuId()) && menuMap.containsKey(sysMenu.getParentMenuId())) { elTree.setParentId(sysMenu.getParentMenuId()); ElTree parentElTree = menuMap.get(sysMenu.getParentMenuId()); parentElTree.addChildren(elTree); } } List<ElTree> permissionTree = new ArrayList<ElTree>(); menuMap.forEach((k, v) -> { if (CommonUtil.isEmptyStr(v.getParentId())) { permissionTree.add(v); } }); Map<String, Object> result = new HashMap<>(2); result.put("permissionTree", permissionTree); List<String> permissions = baseMapper.listMenuOrFuncIdsByRoleId(roleId); result.put("permissions", permissions); return result; } /** * 保存角色权限 * * @param roleId * @param menuOrFuncIds * @param permissionTypes */ @Override @Transactional(rollbackFor = Exception.class) public void saveRolePermissions(String roleId, String menuOrFuncIds, String permissionTypes) { String[] menuOrFuncIdArray = null; if (CommonUtil.isNotEmptyStr(menuOrFuncIds)) { menuOrFuncIdArray = menuOrFuncIds.split(","); } String[] permissionTypeArray = null; if (CommonUtil.isNotEmptyStr(permissionTypes)) { permissionTypeArray = permissionTypes.split(","); } if (menuOrFuncIdArray.length != permissionTypeArray.length) { throw new AppException("系统错误,参数长度不一致,请联系管理员!"); } // 【1】先删除此角色的已有操作权限 Map<String, Object> columnMap = new HashMap<>(1); columnMap.put("ROLE_ID", roleId); this.sysRolePermissionService.removeByMap(columnMap); // 【2】保存新的操作权限 for (int i = 0; i < menuOrFuncIdArray.length; i++) { SysRolePermission sysRolePermission = new SysRolePermission(); sysRolePermission.setRoleId(roleId); sysRolePermission.setPermissionType(permissionTypeArray[i]); sysRolePermission.setMenuOrFuncId(menuOrFuncIdArray[i]); this.sysRolePermissionService.save(sysRolePermission); } } /** * 查询角色用户 * * @param page * @param roleId * @return */ @Override public IPage<SysUser> getRoleUser(Page<SysUser> page, SysRoleUser sysRoleUser) { return page.setRecords(baseMapper.getRoleUser(page, sysRoleUser)); } /** * 保存角色用户 * * @param sysRoleUser */ @Override @Transactional(rollbackFor = Exception.class) public void saveRoleUsers(String roleId, String userIds) { String[] userIdArray = userIds.split(","); // 【1】先删除角色用户 QueryWrapper<SysRoleUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("ROLE_ID", roleId).in("USER_ID", (Object[]) userIdArray); this.sysRoleUserService.remove(queryWrapper); // 【2】保存角色用户 for (int i = 0; i < userIdArray.length; i++) { SysRoleUser sysRoleUser = new SysRoleUser(roleId, userIdArray[i]); this.sysRoleUserService.save(sysRoleUser); } } /** * 删除角色用户 * * @param sysRoleUser */ @Override @Transactional(rollbackFor = Exception.class) public void deleteRoleUsers(String roleId, String userIds) { //如果删除的角色用户当前角色是当前roleId,将t_sys_user表中的role_id字段清空 sysUserService.deleteUserCurrentRole(roleId,Arrays.asList(userIds.split(","))); QueryWrapper<SysRoleUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("ROLE_ID", roleId).in("USER_ID", (Object[]) userIds.split(",")); this.sysRoleUserService.remove(queryWrapper); } /** * 删除角色 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void delete(String ids) { String[] idsArr = ids.split(","); for (int i = 0; i < idsArr.length; i++) { if ("admin".equals(idsArr[i])) { throw new SysException("不允许删除[admin]角色"); } } if (idsArr.length > 1) { this.removeByIds(Arrays.asList(idsArr)); } else { this.removeById(idsArr[0]); } this.sysRoleUserService.remove(new QueryWrapper<SysRoleUser>().in("ROLE_ID", (Object[]) idsArr)); this.sysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().in("ROLE_ID", (Object[]) idsArr)); } /** * 校验删除的角色用户的当前角色 * @param roleId * @param userIds */ @Override public Result verifyDeleteRoleUsers(String roleId, String userIds) { //判断所选用户的当前用户角色是否是删除的角色 QueryWrapper<SysUser> wrapper = new QueryWrapper<>(); wrapper.eq("ROLE_ID", roleId).in("USER_ID", (Object[]) userIds.split(",")); List<SysUser> list = sysUserService.list(wrapper); if(list != null && list.size() > 0){ return Result.error(504,"该角色为用户 ["+ list.stream().map(item -> item.getUserName()).collect(Collectors.joining(",")) + "] 当前角色,删除后用户将无法登录,请确认是否删除?"); } return Result.ok(); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.strongdata.workflow.modules.sys.mapper.SysRoleUserMapper;import com.strongdata.workflow.modules.sys.service.SysRoleUserService;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysRoleUser;/** * 角色和用户关系Service * * @author 庄金明 */@Servicepublic class SysRoleUserServiceImpl extends BaseServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService { @Override public IPage<SysRoleUser> list(IPage<SysRoleUser> page, SysRoleUser sysRoleUser) { return page.setRecords(baseMapper.list(page, sysRoleUser)); }}
package com.strongdata.workflow.modules.sys.service.impl;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysTenantApi;import com.strongdata.workflow.modules.sys.mapper.SysTenantApiMapper;import com.strongdata.workflow.modules.sys.service.SysTenantApiService;/** * 租户Api接口服务Service * * @author 王杰 */@Servicepublic class SysTenantApiServiceImpl extends BaseServiceImpl<SysTenantApiMapper, SysTenantApi> implements SysTenantApiService { @Override public IPage<SysTenantApi> list(IPage<SysTenantApi> page, SysTenantApi sysTenantApi) { return page.setRecords(baseMapper.list(page, sysTenantApi)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.util.SecurityUtils;import com.strongdata.workflow.modules.sys.entity.SysTenantApi;import com.strongdata.workflow.modules.sys.entity.SysTenantUser;import com.strongdata.workflow.modules.sys.entity.SysTenant;import com.strongdata.workflow.modules.sys.entity.SysUser;import com.strongdata.workflow.modules.sys.mapper.SysTenantMapper;import com.strongdata.workflow.modules.sys.service.SysTenantApiService;import com.strongdata.workflow.modules.sys.service.SysTenantUserService;import com.strongdata.workflow.modules.sys.service.SysTenantService;import com.strongdata.workflow.modules.sys.service.SysUserService;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.time.LocalDateTime;import java.time.ZoneId;import java.util.Arrays;import java.util.Date;import java.util.List;/** * 租户Service * * @author 王杰 */@Servicepublic class SysTenantServiceImpl extends BaseServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService { @Autowired private SysTenantUserService sysTenantUserService; @Autowired private SysTenantApiService sysTenantApiService; @Lazy @Autowired private SysUserService sysUserService; @Override public IPage<SysTenant> list(IPage<SysTenant> page, SysTenant sysTenant) { return page.setRecords(baseMapper.list(page, sysTenant)); } /** * 查询租户用户 * * @param page * @param sysTenantUser * @return */ @Override public IPage<SysUser> getTenantUser(Page<SysUser> page, SysTenantUser sysTenantUser) { return page.setRecords(baseMapper.getTenantUser(page, sysTenantUser)); } /** * 保存租户用户 * * @param tenantId * @param userIds */ @Override @Transactional(rollbackFor = Exception.class) public void saveTenantUsers(String tenantId, String userIds) { String[] userIdArray = userIds.split(","); // 【1】先删除租户用户 QueryWrapper<SysTenantUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("TENANT_ID", tenantId).in("USER_ID", (Object[]) userIdArray); this.sysTenantUserService.remove(queryWrapper); // 【2】保存租户用户 for (int i = 0; i < userIdArray.length; i++) { SysTenantUser sysTenantUser = new SysTenantUser(tenantId, userIdArray[i]); this.sysTenantUserService.save(sysTenantUser); } } /** * 删除租户用户 * * @param tenantId * @param userIds */ @Override @Transactional(rollbackFor = Exception.class) public void deleteTenantUsers(String tenantId, String userIds) { //如果删除的租户用户是用户的当前租户将t_sys_user的tenant字段清空 SysUser sysUser = new SysUser(); sysUser.setTenantId(""); QueryWrapper<SysUser> wrapper = new QueryWrapper<>(); wrapper.eq("TENANT_ID", tenantId).in("USER_ID", (Object[]) userIds.split(",")); sysUserService.update(sysUser,wrapper); QueryWrapper<SysTenantUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("TENANT_ID", tenantId).in("USER_ID", (Object[]) userIds.split(",")); this.sysTenantUserService.remove(queryWrapper); } /** * 删除租户 * @param tenantIds * @return */ @Override @Transactional(rollbackFor = Exception.class) public void delete(List<String> tenantIds) { String currUser = SecurityUtils.getUserId(); LocalDateTime now = LocalDateTime.now(); Date date = Date.from( now.atZone( ZoneId.systemDefault()).toInstant()); baseMapper.deleteTenantByIds(tenantIds,currUser,date); //同时删除租户用户关联关系和租户API服务 QueryWrapper<SysTenantUser> queryWrapper = new QueryWrapper<>(); queryWrapper.in("TENANT_ID", tenantIds); sysTenantUserService.remove(queryWrapper); QueryWrapper<SysTenantApi> wrapper = new QueryWrapper<>(); wrapper.in("TENANT_ID",tenantIds); sysTenantApiService.remove(wrapper); } /** * 公共选租户查询 * @param page * @param sysTenant * @param selectTenantIds 前端所选租户id * @return */ @Override public IPage<SysTenant> listSelectTenant(IPage<SysTenant> page, SysTenant sysTenant,String selectTenantIds) { List<String> selectTenantIdsList = StringUtils.isNotBlank(selectTenantIds) ? Arrays.asList(selectTenantIds.split(",")) : null; return page.setRecords(baseMapper.listSelectTenant(page, sysTenant,selectTenantIdsList)); } /** * 获取用户下的租户 * @param page * @param sysTenant * @param selectTenantIds 前端所选租户id * @return */ @Override public IPage<SysTenant> getUserTenant(IPage<SysTenant> page, SysTenant sysTenant,String selectTenantIds) { List<String> selectTenantIdsList = StringUtils.isNotBlank(selectTenantIds) ? Arrays.asList(selectTenantIds.split(",")) : null; return page.setRecords(baseMapper.getUserTenant(page, sysTenant,selectTenantIdsList)); } /** * 不分页获取用户下的租户信息 * @param userId * @return */ @Override public List<SysTenant> getTenantByUserId(String userId) { return baseMapper.getTenantByUserId(userId); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.metadata.IPage;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.modules.sys.entity.SysTenantUser;import com.strongdata.workflow.modules.sys.mapper.SysTenantUserMapper;import com.strongdata.workflow.modules.sys.service.SysTenantUserService;import org.springframework.stereotype.Service;/** * 岗位和用户关系Service * * @author 王杰 */@Servicepublic class SysTenantUserServiceImpl extends BaseServiceImpl<SysTenantUserMapper, SysTenantUser> implements SysTenantUserService { @Override public IPage<SysTenantUser> list(IPage<SysTenantUser> page, SysTenantUser sysTenantUser) { return page.setRecords(baseMapper.list(page, sysTenantUser)); }}
package com.strongdata.workflow.modules.sys.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Sets;import com.strongdata.workflow.common.core.Result;import com.strongdata.workflow.common.core.base.BaseServiceImpl;import com.strongdata.workflow.common.core.base.UserInfo;import com.strongdata.workflow.common.core.base.UserInfoService;import com.strongdata.workflow.common.core.constant.CacheConstants;import com.strongdata.workflow.common.core.constant.Constants;import com.strongdata.workflow.common.core.exception.SysException;import com.strongdata.workflow.common.core.redis.util.RedisUtil;import com.strongdata.workflow.common.core.security.SecurityUser;import com.strongdata.workflow.common.core.util.*;import com.strongdata.workflow.modules.sys.entity.*;import com.strongdata.workflow.modules.sys.entity.vo.*;import com.strongdata.workflow.modules.sys.mapper.SysUserMapper;import com.strongdata.workflow.modules.sys.service.*;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.time.LocalDateTime;import java.time.ZoneId;import java.util.*;import java.util.stream.Collectors;/** * 用户Service * * @author 庄金明 */@Servicepublic class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService, UserInfoService { @Autowired private SysRoleService sysRoleService; @Autowired private SysRoleUserService sysRoleUserService; @Autowired private SysPostUserService sysPostUserService; @Autowired private SysTenantUserService sysTenantUserService; @Autowired private SysTenantService sysTenantService; @Autowired private SysOrgService sysOrgService; @Autowired private RedisUtil redisUtil; @Override public IPage<SysUser> list(IPage<SysUser> page, SysUser sysUser) { List<SysUser> records = baseMapper.list(page, sysUser); if (page == null) { page = new Page<SysUser>(); page.setTotal(records != null ? records.size() : 0L); } return page.setRecords(records); } /** * 公共选人查询 * * @param page * @param sysUser * @param type * @return */ @Override public IPage<SysUser> listSelectUser(IPage<SysUser> page, SysUser sysUser,String type) { return page.setRecords(baseMapper.listSelectUser(page, sysUser,type)); } @Override public List<SysRole> getRoleByUserId(String userId) { return baseMapper.getRolesByUserId(userId); } /** * 获取用户信息 , * <p> * 若用户变更角色,则roleId不能为空,并且将变更后的roleId更新到T_SYS_USER表中 * * @param userId * @param roleId * @return */ @Override @Transactional(rollbackFor = Exception.class) public SysUserInfo saveGetUserInfo(String userId, String roleId) { SysUserInfo sysUserInfo = info(userId, roleId, true); SysUser sysUser = sysUserInfo.getSysUser(); SysRole sysRole = sysUserInfo.getSysRole(); // 切换角色获取用户信息,需要更新用户表角色ID if (!sysRole.getRoleId().equals(sysUser.getRoleId())) { SysUser updateRoleIdUser = new SysUser(); updateRoleIdUser.setUserId(sysUser.getUserId()); updateRoleIdUser.setRoleId(roleId); updateById(updateRoleIdUser); } if (roleId != null && !roleId.isEmpty()) { TokenStore tokenStore = SpringContextUtils.getBean(TokenStore.class); OAuth2Authentication authentication = (OAuth2Authentication) SecurityUtils.getAuthentication(); SecurityUser securityUser = (SecurityUser) authentication.getPrincipal(); SecurityUser newSecurityUser = new SecurityUser(sysRole.getRoleId(), sysUser.getOrgId(), sysUser.getUserName(), securityUser.getAdditionalInformation(), sysUser.getUserId(), "", true, true, true, true, sysUserInfo.getAuthorities()); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(newSecurityUser, authentication.getCredentials(), newSecurityUser.getAuthorities()); usernamePasswordAuthenticationToken.setDetails(authentication.getUserAuthentication().getDetails()); OAuth2Authentication newAuthentication = new OAuth2Authentication(authentication.getOAuth2Request(), usernamePasswordAuthenticationToken); newAuthentication.setDetails(authentication.getDetails()); OAuth2AccessToken token = tokenStore.getAccessToken(authentication); if (CommonUtil.isNotEmptyObject(token.getAdditionalInformation())) { token.getAdditionalInformation().put("roleId", roleId); } tokenStore.storeAccessToken(token, newAuthentication); } return sysUserInfo; } @Override public Result<UserInfo> info(String userId, String inner) { SysUserInfo sysUserInfo = info(userId, null, false); if(sysUserInfo != null) { SysUser sysUser = sysUserInfo.getSysUser(); String status = sysUser.getStatus(); boolean enable = true; if("2".equals(status)){ enable = false; } UserInfo userInfo = new UserInfo(userId, sysUser.getUserName(), sysUser.getPassword(), sysUser.getOrgId(), sysUserInfo.getSysRole().getRoleId(), ImmutableMap.of("orgLevelCode", sysUserInfo.getSysOrg().getOrgLevelCode()), sysUserInfo.getAuthorities(),enable); return Result.ok(userInfo); }else{ return null; } } private SysUserInfo info(String userId, String roleId, boolean loadRoutes) { SysUser sysUser = getById(userId); if(sysUser != null){ String status = sysUser.getStatus(); if ("3".equals(status)){ return null; } }else{ return null; } List<SysRole> sysRoles = getRoleByUserId(sysUser.getUserId()); if (sysRoles == null || sysRoles.size() == 0) { if (!Constants.USER_ADMIN.equals(sysUser.getUserId())) { throw new SysException("用户未配置角色权限,请联系管理员授权!"); } SysRole sysRoleAdmin = sysRoleService.getById(Constants.ROLE_ADMIN); if (sysRoleAdmin == null) { throw new SysException("系统未配置admin角色,请联系管理员!"); } sysRoles.add(sysRoleAdmin); } // 默认以T_SYS_USER表中的角色登录 if (CommonUtil.isEmptyStr(roleId)) { roleId = sysUser.getRoleId(); } SysRole sysRoleUser = null; if (CommonUtil.isEmptyStr(roleId)) { roleId = sysRoles.get(0).getRoleId(); sysRoleUser = sysRoles.get(0); } else { for (SysRole sysRole : sysRoles) { if (sysRole.getRoleId().equals(roleId)) { sysRoleUser = sysRole; break; } } } Collection<? extends GrantedAuthority> authorities = loadPermissions(sysUser, roleId); SysOrg sysOrg = this.sysOrgService.getById(sysUser.getOrgId()); List<Route> routes = null; if (loadRoutes) { routes = this.loadRoutes(sysUser, roleId); } //查询用户租户 //判断用户角色是否属于平台管理员、运营人员 List<SysTenant> sysTenants = new ArrayList<>(); if(Constants.ROLE_ADMIN.equals(sysRoleUser.getRoleId()) || Constants.ROLE_OPERATION.equals(sysRoleUser.getRoleId())){ sysTenants = sysTenantService.getTenantByUserId(null); SysTenant sysTenant = new SysTenant(); sysTenant.setTenantId(""); sysTenants.add(0,sysTenant); }else { sysTenants = sysTenantService.getTenantByUserId(userId); } return new SysUserInfo(sysUser, sysOrg, sysRoleUser, sysRoles, routes, authorities, sysTenants); } /** * @param sysUser * @param roleId * @return */ @Override public Collection<? extends GrantedAuthority> loadPermissions(SysUser sysUser, String roleId) { String userId = sysUser.getUserId(); List<SysRolePermissionVO> authList = null; if (Constants.USER_ADMIN.equals(userId)) { authList = baseMapper.getAdminPermissions(); } else { authList = baseMapper.getRolePermissions(roleId); } Set<String> permissions = Sets.newHashSet(); for (SysRolePermissionVO sysAuthOperVO : authList) { if ("1".equals(sysAuthOperVO.getPermissionType())) { if (CommonUtil.isNotEmptyStr(sysAuthOperVO.getMenuUrl())) { if (CommonUtil.isNotEmptyStr(sysAuthOperVO.getMenuPermissions())) { // 以逗号分隔 String[] menuPermissions = sysAuthOperVO.getMenuPermissions().split(","); for (String permission : menuPermissions) { permissions.add(permission); } } } } else if ("2".equals(sysAuthOperVO.getPermissionType())) { if (CommonUtil.isNotEmptyStr(sysAuthOperVO.getFuncPermissions())) { // 以逗号分隔 String[] funcPermissions = sysAuthOperVO.getFuncPermissions().split(","); for (String permission : funcPermissions) { permissions.add(permission); } } } } return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet()); } @Override public List<Route> loadRoutes(SysUser sysUser, String roleId) { String userId = sysUser.getUserId(); List<SysMenu> menuList = null; if (Constants.USER_ADMIN.equals(userId)) { menuList = baseMapper.getRoleMenus(""); } else { menuList = baseMapper.getRoleMenus(roleId); } Map<String, Route> routeMap = new LinkedHashMap<String, Route>(); for (SysMenu menu : menuList) { if (!"1".equals(menu.getIsRoute())) { continue; } Route route = new Route(); route.setRouteId(menu.getMenuId()); route.setPath(menu.getMenuUrl()); route.setComponent(menu.getComponent()); route.setHidden("1".equals(menu.getHidden())); route.setRedirect(menu.getRedirect()); if (CommonUtil.isNotEmptyStr(menu.getRouteName())) { route.setName(menu.getRouteName()); } else { route.setName(urlToRouteName(menu.getMenuUrl())); } Meta meta = new Meta(); meta.setTitle(menu.getMenuName()); meta.setIcon(menu.getMenuIcon()); meta.setIsCache("1".equals(menu.getIsCache())); meta.setAffix("1".equals(menu.getAffix())); route.setMeta(meta); routeMap.put(route.getRouteId(), route); if (CommonUtil.isNotEmptyStr(menu.getParentMenuId()) && routeMap.containsKey(menu.getParentMenuId())) { route.setRouteParentId(menu.getParentMenuId()); Route parentRoute = routeMap.get(menu.getParentMenuId()); parentRoute.addChildren(route); } } List<Route> result = new ArrayList<Route>(); routeMap.forEach((k, v) -> { if (CommonUtil.isEmptyStr(v.getRouteParentId())) { result.add(v); } }); return result; } /** * 通过URL生成路由name(去掉URL前缀斜杠,替换内容中的斜杠‘/’为-) * <p> * 举例: URL = /sys/config RouteName = sysConfig * * @return */ private String urlToRouteName(String url) { if (CommonUtil.isNotEmptyStr(url)) { if (url.startsWith(Constants.FORWARD_SLASH)) { url = url.substring(1); } url = url.replace(Constants.FORWARD_SLASH, Constants.CROSSBAR); return url; } else { return null; } } /** * 新增用户 * * @param sysUser */ @Override @Transactional(rollbackFor = Exception.class) public boolean saveSysUser(SysUser sysUser) { // String salt = PasswordUtil.randomGen(8); String defaultPassword = (String) redisUtil.get(CacheConstants.SYS_CONFIG + "defaultPassword", "1"); // 默认密码 String password = PasswordUtil.encryptPassword(defaultPassword); // sysUser.setSalt(salt); sysUser.setPassword(password); //保存岗位 String postId = sysUser.getPostId(); if (StringUtils.isNotBlank(postId)) { String[] postIds = postId.split(","); //保存岗位用户 for (int i = 0; i < postIds.length; i++) { SysPostUser sysPostUser = new SysPostUser(postIds[i], sysUser.getUserId()); this.sysPostUserService.save(sysPostUser); } } if(StringUtils.isNotBlank(sysUser.getTenantId())) { //保存租户用户 SysTenantUser sysTenantUser = new SysTenantUser(sysUser.getTenantId(), sysUser.getUserId()); this.sysTenantUserService.save(sysTenantUser); } SysRoleUser sysRoleUser = new SysRoleUser(sysUser.getRoleId(), sysUser.getUserId()); sysRoleUserService.saveOrUpdate(sysRoleUser); boolean result = this.save(sysUser); return result; } /** * 修改用户 * * @param sysUser */ @Override @Transactional(rollbackFor = Exception.class) public boolean updateSysUser(SysUser sysUser) { SysUser sysUserDb = this.getById(sysUser.getUserId()); if (!sysUser.getRoleId().equals(sysUserDb.getRoleId())) { SysRoleUser sysRoleUser = new SysRoleUser(sysUser.getRoleId(), sysUser.getUserId()); sysRoleUserService.saveOrUpdate(sysRoleUser); } if(StringUtils.isNotBlank(sysUser.getTenantId())) { if (!sysUser.getTenantId().equals(sysUserDb.getTenantId())) { SysTenantUser sysTenantUser = new SysTenantUser(sysUser.getTenantId(), sysUser.getUserId()); sysTenantUserService.saveOrUpdate(sysTenantUser); } } String postId = sysUser.getPostId(); // 【1】先删除用户下的岗位 QueryWrapper<SysPostUser> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("USER_ID", sysUser.getUserId()); this.sysPostUserService.remove(queryWrapper); if (StringUtils.isNotBlank(postId)) { String[] postIds = postId.split(","); // 【2】保存用户岗位 for (int i = 0; i < postIds.length; i++) { SysPostUser sysPostUser = new SysPostUser(postIds[i], sysUser.getUserId()); this.sysPostUserService.save(sysPostUser); } } // 密码设置为空,防止密码被恶意修改 sysUser.setPassword(null); // 密码盐设置为空,防止密码被恶意修改 sysUser.setSalt(null); boolean result = this.updateById(sysUser); return result; } /** * 删除用户 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void delete(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); for (int i = 0; i < idsArr.length; i++) { if (Constants.USER_ADMIN.equals(idsArr[i])) { throw new SysException("不允许删除[admin]用户"); } } if (idsArr.length > 1) { String currUser = SecurityUtils.getUserId(); LocalDateTime now = LocalDateTime.now(); Date date = Date.from( now.atZone( ZoneId.systemDefault()).toInstant()); baseMapper.updateBatchStatus(currUser,date,Arrays.asList(idsArr)); } else { SysUser sysUser = new SysUser(); //逻辑删除 sysUser.setStatus("3"); sysUser.setUserId(idsArr[0]); updateById(sysUser); } sysRoleUserService.remove(new QueryWrapper<SysRoleUser>().in("user_id", (Object[]) idsArr)); sysPostUserService.remove(new QueryWrapper<SysPostUser>().in("user_id", (Object[]) idsArr)); //删除用户时同时将租户用户删除 sysTenantUserService.remove(new QueryWrapper<SysTenantUser>().in("user_id", (Object[]) idsArr)); } /** * 修改密码 * * @param sysPasswordForm */ @Override @Transactional(rollbackFor = Exception.class) public boolean updatePassword(SysPasswordForm sysPasswordForm) { String userId = SecurityUtils.getUserId(); SysUser sysUser = this.getById(userId); if (sysUser == null) { throw new SysException("用户不存在"); } if (!PasswordUtil.matchesPassword(sysPasswordForm.getPassword(), sysUser.getPassword())) { throw new SysException("旧密码错误"); } // String salt = PasswordUtil.randomGen(8); String newPassword = PasswordUtil.encryptPassword(sysPasswordForm.getNewPassword()); sysUser.setPassword(newPassword); // sysUser.setSalt(salt); return this.update(sysUser, new QueryWrapper<SysUser>().eq("user_id", userId)); } /** * 删除当前用户的当前角色 * @param roleId * @param userIds */ @Override public void deleteUserCurrentRole(String roleId, List<String> userIds) { String currUser = SecurityUtils.getUserId(); LocalDateTime now = LocalDateTime.now(); Date date = Date.from( now.atZone( ZoneId.systemDefault()).toInstant()); baseMapper.deleteUserCurrentRole(roleId,userIds,currUser,date); } /** * 获取当前租户和所属租户集合 * @param userId * @return */ @Override public SysUser getTenants(String userId) { return baseMapper.getTenants(userId); }}
package com.strongdata.workflow.modules.flowable.common;import cn.hutool.core.map.MapUtil;import cn.hutool.json.JSONArray;import cn.hutool.json.JSONUtil;import com.strongdata.workflow.common.core.util.ObjectUtils;import com.strongdata.workflow.common.core.util.SpringContextUtils;import com.strongdata.workflow.common.core.xss.SqlFilter;import com.strongdata.workflow.modules.flowable.constant.FlowableConstant;import com.strongdata.workflow.modules.flowable.service.FlowableTaskService;import com.strongdata.workflow.modules.flowable.service.PermissionService;import com.strongdata.workflow.modules.flowable.vo.query.BaseQueryVo;import com.strongdata.workflow.modules.flowable.wapper.IListWrapper;import com.strongdata.workflow.modules.flowable.common.FlowablePage.Direction;import com.strongdata.workflow.modules.flowable.common.FlowablePage.Order;import org.apache.commons.lang3.StringUtils;import org.flowable.bpmn.model.ExtensionElement;import org.flowable.bpmn.model.Process;import org.flowable.bpmn.model.UserTask;import org.flowable.bpmn.model.ValuedDataObject;import org.flowable.common.engine.api.FlowableIllegalArgumentException;import org.flowable.common.engine.api.query.Query;import org.flowable.common.engine.api.query.QueryProperty;import org.flowable.engine.*;import org.flowable.task.api.Task;import org.springframework.beans.factory.annotation.Autowired;import java.text.MessageFormat;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;/** * @author 庄金明 * @date 2020年3月24日 */@SuppressWarnings({"rawtypes"})public abstract class BaseFlowableController { @Autowired protected ResponseFactory responseFactory; @Autowired protected RepositoryService repositoryService; @Autowired protected ManagementService managementService; @Autowired protected RuntimeService runtimeService; @Autowired protected FormService formService; @Autowired protected HistoryService historyService; @Autowired protected PermissionService permissionService; @Autowired protected FlowableTaskService flowableTaskService; @Autowired protected TaskService taskService; protected FlowablePage getFlowablePage(BaseQueryVo baseQueryVo) { int current = baseQueryVo.getCurrent() ; int size = baseQueryVo.getSize(); if (current < 0) { return null; } List<Order> orders = null; if (ObjectUtils.isNotEmpty(baseQueryVo.getOrderRule())) { // orderRule=column1|asc,column2|desc orders = new ArrayList<>(); String orderRule = baseQueryVo.getOrderRule(); // 处理排序 if (orderRule != null && orderRule.length() > 0) { String[] orderColumnRules = orderRule.split(","); for (String orderColumnRule : orderColumnRules) { if (orderColumnRule.length() == 0) { continue; } String[] rule = orderColumnRule.split("\\|"); String orderColumn = rule[0]; SqlFilter.sqlInject(orderColumn); Order orderTmp = null; if (rule.length == 2 && "DESC".equals(rule[1].toUpperCase())) { orderTmp = new Order(orderColumn, Direction.DESC); } else { orderTmp = new Order(orderColumn, Direction.ASC); } orders.add(orderTmp); } } } if (orders == null) { return FlowablePage.of(current - 1, size); } else { return FlowablePage.of(current - 1, size, orders); } } protected FlowablePage pageList(BaseQueryVo baseQueryVo, Query query, Class<? extends IListWrapper> listWrapperClass, Map<String, QueryProperty> allowedSortProperties) { return pageList(getFlowablePage(baseQueryVo), query, listWrapperClass, allowedSortProperties); } protected FlowablePage pageList(BaseQueryVo baseQueryVo, Query query, Class<? extends IListWrapper> listWrapperClass, Map<String, QueryProperty> allowedSortProperties, QueryProperty defaultDescSortProperty) { return pageList(getFlowablePage(baseQueryVo), query, listWrapperClass, allowedSortProperties, defaultDescSortProperty); } protected FlowablePage pageList(FlowablePage flowablePage, Query query, Class<? extends IListWrapper> listWrapperClass, Map<String, QueryProperty> allowedSortProperties) { return pageList(flowablePage, query, listWrapperClass, allowedSortProperties, null); } protected FlowablePage pageList(FlowablePage flowablePage, Query query, Class<? extends IListWrapper> listWrapperClass, Map<String, QueryProperty> allowedSortProperties, QueryProperty defaultDescSortProperty) { List list = null; if (flowablePage == null) { list = query.list(); flowablePage = FlowablePage.of(0, 0); } else { setQueryOrder(flowablePage.getOrders(), query, allowedSortProperties, defaultDescSortProperty); list = query.listPage((int) flowablePage.getOffset(), flowablePage.getSize()); } if (listWrapperClass != null) { IListWrapper listWrapper = SpringContextUtils.getBean(listWrapperClass); list = listWrapper.execute(list); } flowablePage.setRecords(list); flowablePage.setTotal(query.count()); return flowablePage; } protected List listWrapper(Class<? extends IListWrapper> listWrapperClass, List list) { IListWrapper listWrapper = SpringContextUtils.getBean(listWrapperClass); List result = listWrapper.execute(list); return result; } protected void setQueryOrder(List<Order> orders, Query query, Map<String, QueryProperty> properties, QueryProperty defaultDescSortProperty) { boolean orderByDefaultDescSortProperty = (orders == null || orders.size() == 0 || properties.isEmpty()) && defaultDescSortProperty != null; if (orderByDefaultDescSortProperty) { query.orderBy(defaultDescSortProperty).desc(); } else { if (orders != null && orders.size() > 0) { for (Order order : orders) { QueryProperty qp = properties.get(order.getProperty()); if (qp == null) { throw new FlowableIllegalArgumentException("Value for param 'orders' is not valid, '" + order.getProperty() + "' is not a valid property"); } query.orderBy(qp); if (order.getDirection() == Direction.ASC) { query.asc(); } else { query.desc(); } } } } } /** * 只接收字符串 * * @param message * @param arguments * @return */ protected String messageFormat(String message, String... arguments) { return MessageFormat.format(message, (Object[]) arguments); } protected boolean isShowBusinessKey(String processDefinitionId) { Process process = repositoryService.getBpmnModel(processDefinitionId).getMainProcess(); Map<String, List<ExtensionElement>> extensionElements = process.getExtensionElements(); if (extensionElements != null && !extensionElements.isEmpty() && extensionElements.get("properties") != null && extensionElements.get("properties").size() > 0) { List<ExtensionElement> properties = extensionElements.get("properties"); for (ExtensionElement extensionElement : properties) { List<ExtensionElement> property = extensionElement.getChildElements().get("property"); if (property != null && property.size() > 0) { for (ExtensionElement propertyElement : property) { String name = propertyElement.getAttributeValue(null, "name"); String value = propertyElement.getAttributeValue(null, "value"); if ("showBusinessKey".equals(name)) { if (Boolean.valueOf(value)) { return true; } else { return false; } } } } } } List<ValuedDataObject> dataObjects = repositoryService.getBpmnModel(processDefinitionId).getMainProcess().getDataObjects(); if (dataObjects != null && dataObjects.size() > 0) { for (ValuedDataObject valuedDataObject : dataObjects) { if ("showBusinessKey".equals(valuedDataObject.getId())) { if (valuedDataObject.getValue() instanceof String) { return Boolean.valueOf((String) valuedDataObject.getValue()); } else if (valuedDataObject.getValue() instanceof Boolean) { return (Boolean) valuedDataObject.getValue(); } else { return false; } } } } return false; } /** * 为表单json串的defaultValue字段设置默认值 * @param formJson 表单json * @param userTask 当前用户节点的element信息 * @param variables 流程参数 * @param task 流程参数 */ protected void setFormDataDefaultValue(Map formJson, UserTask userTask, Map<String, Object> variables, Task task){ Map<String, List<ExtensionElement>> extensionElements = userTask.getExtensionElements(); //是否可编辑 if(extensionElements != null && !extensionElements.isEmpty() && extensionElements.get("formConfig") != null){ List<ExtensionElement> formConfig = extensionElements.get("formConfig"); if(formConfig != null && !formConfig.isEmpty()){ ExtensionElement extensionElement = formConfig.get(0); String formIsEditable = extensionElement.getAttributeValue(null, "formIsEditable"); formJson.put("disabled", StringUtils.isNotBlank(formIsEditable) ? !Boolean.valueOf(formIsEditable) : true); } }else{ formJson.put("disabled",true); } // 当前任务是发起者 if (FlowableConstant.INITIATOR.equals(task.getTaskDefinitionKey())) { //启用表单按钮 formJson.put("formBtns",true); }else{ //禁用表单按钮 formJson.put("formBtns",false); } JSONArray fields = JSONUtil.parseArray(formJson.get("fields")); fields.stream().map(item -> { Map<String, Object> i = (Map) item; String vModel = MapUtil.getStr(i, "__vModel__"); Object value = variables.get(vModel); Map<String, Object> config = (Map<String, Object>)i.get("__config__"); config.put("defaultValue",value); i.put("__config__", config); return i; }).collect(Collectors.toList()); }}
package com.strongdata.workflow.modules.flowable.common.cmd;import com.strongdata.workflow.modules.flowable.constant.FlowableConstant;import com.strongdata.workflow.modules.flowable.vo.CcToVo;import org.flowable.common.engine.api.FlowableIllegalArgumentException;import org.flowable.common.engine.api.FlowableObjectNotFoundException;import org.flowable.common.engine.impl.interceptor.Command;import org.flowable.common.engine.impl.interceptor.CommandContext;import org.flowable.engine.impl.persistence.entity.CommentEntity;import org.flowable.engine.impl.persistence.entity.CommentEntityManager;import org.flowable.engine.impl.persistence.entity.ExecutionEntity;import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;import org.flowable.engine.impl.util.CommandContextUtil;import org.flowable.engine.impl.util.IdentityLinkUtil;import org.springframework.util.StringUtils;import java.io.Serializable;/** * @author 庄金明 */public class AddCcIdentityLinkCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String processInstanceId; protected String taskId; protected String userId; protected CcToVo[] ccToVos; public AddCcIdentityLinkCmd(String processInstanceId, String taskId, String userId, CcToVo[] ccToVos) { validateParams(processInstanceId, taskId, userId, ccToVos); this.processInstanceId = processInstanceId; this.taskId = taskId; this.userId = userId; this.ccToVos = ccToVos; } protected void validateParams(String processInstanceId, String taskId, String userId, CcToVo[] ccTo) { if (processInstanceId == null) { throw new FlowableIllegalArgumentException("processInstanceId is null"); } if (taskId == null) { throw new FlowableIllegalArgumentException("taskId is null"); } if (userId == null) { throw new FlowableIllegalArgumentException("userId is null"); } if (ccTo == null || ccTo.length == 0) { throw new FlowableIllegalArgumentException("ccTo is null or empty"); } } @Override public Void execute(CommandContext commandContext) { ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); ExecutionEntity processInstance = executionEntityManager.findById(processInstanceId); if (processInstance == null) { throw new FlowableObjectNotFoundException("Cannot find process instance with id " + processInstanceId, ExecutionEntity.class); } for (CcToVo ccTo : ccToVos) { IdentityLinkUtil.createProcessInstanceIdentityLink(processInstance, ccTo.getUserId(), null, FlowableConstant.CC); } this.createCcComment(commandContext); return null; } protected void createCcComment(CommandContext commandContext) { CommentEntityManager commentEntityManager = CommandContextUtil.getCommentEntityManager(commandContext); CommentEntity comment = (CommentEntity) commentEntityManager.create(); comment.setProcessInstanceId(processInstanceId); comment.setUserId(userId); comment.setType(FlowableConstant.CC); comment.setTime(CommandContextUtil.getProcessEngineConfiguration(commandContext).getClock().getCurrentTime()); comment.setTaskId(taskId); comment.setAction("AddCcTo"); String ccToStr = StringUtils.arrayToCommaDelimitedString((Object [])ccToVos); comment.setMessage(ccToStr); comment.setFullMessage(ccToStr); commentEntityManager.insert(comment); }}
package com.strongdata.workflow.modules.flowable.common.cmd;import java.io.Serializable;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import org.flowable.bpmn.model.FlowNode;import org.flowable.bpmn.model.Process;import org.flowable.bpmn.model.UserTask;import org.flowable.common.engine.api.FlowableException;import org.flowable.common.engine.api.FlowableObjectNotFoundException;import org.flowable.common.engine.impl.interceptor.Command;import org.flowable.common.engine.impl.interceptor.CommandContext;import org.flowable.engine.RuntimeService;import org.flowable.engine.impl.delegate.ActivityBehavior;import org.flowable.engine.impl.persistence.entity.ExecutionEntity;import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;import org.flowable.engine.impl.util.CommandContextUtil;import org.flowable.engine.impl.util.ProcessDefinitionUtil;import org.flowable.task.api.Task;import org.flowable.task.service.impl.persistence.entity.TaskEntity;import com.google.common.collect.Sets;import com.strongdata.workflow.modules.flowable.constant.FlowableConstant;import com.strongdata.workflow.modules.flowable.util.FlowableUtils;/** * @author 庄金明 * @date 2020年3月23日 */public class BackUserTaskCmd implements Command<String>, Serializable { public static final long serialVersionUID = 1L; protected RuntimeService runtimeService; protected String taskId; protected String targetActivityId; public BackUserTaskCmd(RuntimeService runtimeService, String taskId, String targetActivityId) { this.runtimeService = runtimeService; this.taskId = taskId; this.targetActivityId = targetActivityId; } @Override public String execute(CommandContext commandContext) { if (targetActivityId == null || targetActivityId.length() == 0) { throw new FlowableException("TargetActivityId cannot be empty"); } /// TaskEntity task = CommandContextUtil.getTaskService().getTask(taskId); /// v6.5.1.28 TaskEntity task = CommandContextUtil.getProcessEngineConfiguration().getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("task " + taskId + " doesn't exist", Task.class); } String sourceActivityId = task.getTaskDefinitionKey(); String processInstanceId = task.getProcessInstanceId(); String processDefinitionId = task.getProcessDefinitionId(); Process process = ProcessDefinitionUtil.getProcess(processDefinitionId); FlowNode sourceFlowElement = (FlowNode) process.getFlowElement(sourceActivityId, true); // 只支持从用户任务退回 if (!(sourceFlowElement instanceof UserTask)) { throw new FlowableException("Task with id:" + taskId + " is not a UserTask"); } FlowNode targetFlowElement = (FlowNode) process.getFlowElement(targetActivityId, true); // 退回节点到当前节点不可达到,不允许退回 if (!FlowableUtils.isReachable(process, targetFlowElement, sourceFlowElement)) { throw new FlowableException("Cannot back to [" + targetActivityId + "]"); } // ps:目标节点如果相对当前节点是在子流程内部,则无法直接退回,目前处理是只能退回到子流程开始节点 String[] sourceAndTargetRealActivityId = FlowableUtils.getSourceAndTargetRealActivityId(sourceFlowElement, targetFlowElement); // 实际应操作的当前节点ID String sourceRealActivityId = sourceAndTargetRealActivityId[0]; // 实际应操作的目标节点ID String targetRealActivityId = sourceAndTargetRealActivityId[1]; Map<String, Set<String>> specialGatewayNodes = FlowableUtils.getSpecialGatewayElements(process); // 当前节点处在的并行网关list List<String> sourceInSpecialGatewayList = new ArrayList<>(); // 目标节点处在的并行网关list List<String> targetInSpecialGatewayList = new ArrayList<>(); setSpecialGatewayList(sourceRealActivityId, targetRealActivityId, specialGatewayNodes, sourceInSpecialGatewayList, targetInSpecialGatewayList); // 实际应筛选的节点ID Set<String> sourceRealAcitivtyIds = null; // 若退回目标节点相对当前节点在并行网关中,则要找到相对当前节点最近的这个并行网关,后续做特殊处理 String targetRealSpecialGateway = null; // 1.目标节点和当前节点都不在并行网关中 if (targetInSpecialGatewayList.isEmpty() && sourceInSpecialGatewayList.isEmpty()) { sourceRealAcitivtyIds = Sets.newHashSet(sourceRealActivityId); } // 2.目标节点不在并行网关中、当前节点在并行网关中 else if (targetInSpecialGatewayList.isEmpty() && !sourceInSpecialGatewayList.isEmpty()) { sourceRealAcitivtyIds = specialGatewayNodes.get(sourceInSpecialGatewayList.get(0)); } // 3.目标节点在并行网关中、当前节点不在并行网关中 else if (!targetInSpecialGatewayList.isEmpty() && sourceInSpecialGatewayList.isEmpty()) { sourceRealAcitivtyIds = Sets.newHashSet(sourceRealActivityId); targetRealSpecialGateway = targetInSpecialGatewayList.get(0); } // 4.目标节点和当前节点都在并行网关中 else { int diffSpecialGatewayLevel = FlowableUtils.getDiffLevel(sourceInSpecialGatewayList, targetInSpecialGatewayList); // 在并行网关同一层且在同一分支 if (diffSpecialGatewayLevel == -1) { sourceRealAcitivtyIds = Sets.newHashSet(sourceRealActivityId); } else { // 当前节点最内层并行网关不被目标节点最内层并行网关包含 // 或理解为当前节点相对目标节点在并行网关外 // 只筛选当前节点的execution if (sourceInSpecialGatewayList.size() == diffSpecialGatewayLevel) { sourceRealAcitivtyIds = Sets.newHashSet(sourceRealActivityId); } // 当前节点相对目标节点在并行网关内,应筛选相对目标节点最近的并行网关的所有节点的execution else { sourceRealAcitivtyIds = specialGatewayNodes.get(sourceInSpecialGatewayList.get(diffSpecialGatewayLevel)); } // 目标节点最内层并行网关包含当前节点最内层并行网关 // 或理解为目标节点相对当前节点在并行网关外 // 不做处理 if (targetInSpecialGatewayList.size() == diffSpecialGatewayLevel) { } // 目标节点相对当前节点在并行网关内 else { targetRealSpecialGateway = targetInSpecialGatewayList.get(diffSpecialGatewayLevel); } } } // 筛选需要处理的execution List<ExecutionEntity> realExecutions = this.getRealExecutions(commandContext, processInstanceId, task.getExecutionId(), sourceRealActivityId, sourceRealAcitivtyIds); // 执行退回,直接跳转到实际的 targetRealActivityId List<String> realExecutionIds = realExecutions.stream().map(ExecutionEntity::getId).collect(Collectors.toList()); runtimeService.createChangeActivityStateBuilder().processInstanceId(processInstanceId).moveExecutionsToSingleActivityId(realExecutionIds, targetRealActivityId).changeState(); // 目标节点相对当前节点处于并行网关内,需要特殊处理,需要手动生成并行网关汇聚节点(_end)的execution数据 if (targetRealSpecialGateway != null) { createTargetInSpecialGatewayEndExecutions(commandContext, realExecutions, process, targetInSpecialGatewayList, targetRealSpecialGateway); } return targetRealActivityId; } private void setSpecialGatewayList(String sourceActivityId, String targetActivityId, Map<String, Set<String>> specialGatewayNodes, List<String> sourceInSpecialGatewayList, List<String> targetInSpecialGatewayList) { for (Map.Entry<String, Set<String>> entry : specialGatewayNodes.entrySet()) { if (entry.getValue().contains(sourceActivityId)) { sourceInSpecialGatewayList.add(entry.getKey()); } if (entry.getValue().contains(targetActivityId)) { targetInSpecialGatewayList.add(entry.getKey()); } } } private void createTargetInSpecialGatewayEndExecutions(CommandContext commandContext, List<ExecutionEntity> excutionEntitys, Process process, List<String> targetInSpecialGatewayList, String targetRealSpecialGateway) { // 目标节点相对当前节点处于并行网关,需要手动生成并行网关汇聚节点(_end)的execution数据 String parentExecutionId = excutionEntitys.iterator().next().getParentId(); ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); ExecutionEntity parentExecutionEntity = executionEntityManager.findById(parentExecutionId); int index = targetInSpecialGatewayList.indexOf(targetRealSpecialGateway); for (; index < targetInSpecialGatewayList.size(); index++) { String targetInSpecialGateway = targetInSpecialGatewayList.get(index); String targetInSpecialGatewayEndId = targetInSpecialGateway + FlowableConstant.SPECIAL_GATEWAY_END_SUFFIX; FlowNode targetInSpecialGatewayEnd = (FlowNode) process.getFlowElement(targetInSpecialGatewayEndId, true); int nbrOfExecutionsToJoin = targetInSpecialGatewayEnd.getIncomingFlows().size(); // 处理目标节点所处的分支以外的分支,即 总分枝数-1 = nbrOfExecutionsToJoin - 1 for (int i = 0; i < nbrOfExecutionsToJoin - 1; i++) { ExecutionEntity childExecution = executionEntityManager.createChildExecution(parentExecutionEntity); childExecution.setCurrentFlowElement(targetInSpecialGatewayEnd); ActivityBehavior activityBehavior = (ActivityBehavior) targetInSpecialGatewayEnd.getBehavior(); activityBehavior.execute(childExecution); } } } private List<ExecutionEntity> getRealExecutions(CommandContext commandContext, String processInstanceId, String taskExecutionId, String sourceRealActivityId, Set<String> activityIds) { ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); ExecutionEntity taskExecution = executionEntityManager.findById(taskExecutionId); List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId); Set<String> parentExecutionIds = FlowableUtils.getParentExecutionIdsByActivityId(executions, sourceRealActivityId); String realParentExecutionId = FlowableUtils.getParentExecutionIdFromParentIds(taskExecution, parentExecutionIds); List<ExecutionEntity> childExecutions = executionEntityManager.findExecutionsByParentExecutionAndActivityIds(realParentExecutionId, activityIds); return childExecutions; }}
package com.strongdata.workflow.modules.flowable.common.cmd;import com.strongdata.workflow.modules.flowable.common.CommentTypeEnum;import com.strongdata.workflow.modules.flowable.constant.FlowableConstant;import org.flowable.common.engine.api.FlowableException;import org.flowable.common.engine.api.FlowableIllegalArgumentException;import org.flowable.common.engine.impl.interceptor.CommandContext;import org.flowable.engine.impl.cmd.AddCommentCmd;import org.flowable.engine.impl.cmd.NeedsActiveTaskCmd;import org.flowable.engine.impl.util.TaskHelper;import org.flowable.task.service.impl.persistence.entity.TaskEntity;/** * @author 庄金明 */public class CompleteTaskReadCmd extends NeedsActiveTaskCmd<Void> { private static final long serialVersionUID = 1L; private String userId; public CompleteTaskReadCmd(String taskId, String userId) { super(taskId); this.userId = userId; } @Override protected Void execute(CommandContext commandContext, TaskEntity task) { if (userId == null || userId.length() == 0) { throw new FlowableIllegalArgumentException("userId is null or empty"); } if (!FlowableConstant.CATEGORY_TO_READ.equals(task.getCategory())) { throw new FlowableException("task category must be 'toRead'"); } if (!userId.equals(task.getOwner()) && !userId.equals(task.getAssignee())) { throw new FlowableException("User does not have permission"); } commandContext.getCommandExecutor().execute(new AddCommentCmd(taskId, task.getProcessInstanceId(), CommentTypeEnum.YY.toString(), "已阅!")); TaskHelper.completeTask(task, null, null, null, null, commandContext); return null; } @Override protected String getSuspendedTaskException() { return "Cannot complete a suspended task"; }}
package com.strongdata.workflow.modules.flowable.common.cmd;import com.strongdata.workflow.common.core.util.SpringContextUtils;import com.strongdata.workflow.modules.flowable.entity.FlowableForm;import com.strongdata.workflow.modules.flowable.service.FlowableFormService;import org.apache.commons.lang3.StringUtils;import org.flowable.bpmn.converter.BpmnXMLConverter;import org.flowable.bpmn.model.BpmnModel;import org.flowable.bpmn.model.FlowElement;import org.flowable.bpmn.model.StartEvent;import org.flowable.bpmn.model.UserTask;import org.flowable.common.engine.api.FlowableException;import org.flowable.common.engine.api.FlowableObjectNotFoundException;import org.flowable.common.engine.impl.interceptor.Command;import org.flowable.common.engine.impl.interceptor.CommandContext;import org.flowable.engine.RepositoryService;import org.flowable.engine.impl.util.CommandContextUtil;import org.flowable.engine.repository.Deployment;import org.flowable.engine.repository.DeploymentBuilder;import org.flowable.engine.repository.Model;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLStreamReader;import java.io.ByteArrayInputStream;import java.io.InputStreamReader;import java.io.Serializable;import java.util.Collection;import java.util.HashMap;import java.util.Map;/** * 部署模型 * * @author 庄金明 * @date 2020/08/30 */public class DeployModelCmd implements Command<Deployment>, Serializable { private static final long serialVersionUID = 1L; protected String modelId; public DeployModelCmd(String modelId) { this.modelId = modelId; } @Override public Deployment execute(CommandContext commandContext) { RepositoryService repositoryService = CommandContextUtil.getProcessEngineConfiguration(commandContext).getRepositoryService(); Model model = repositoryService.getModel(modelId); if (model == null) { throw new FlowableObjectNotFoundException("Could not find a model with id '" + modelId + "'.", Model.class); } if (model.getDeploymentId() != null && model.getDeploymentId().length() > 0) { throw new FlowableException("The model is already deployed"); } if (!model.hasEditorSource()) { throw new FlowableObjectNotFoundException("Model with id '" + modelId + "' does not have source " + "available" + ".", String.class); } byte[] bpmnBytes = CommandContextUtil.getProcessEngineConfiguration(commandContext).getModelEntityManager().findEditorSourceByModelId(modelId); if (bpmnBytes == null) { throw new FlowableObjectNotFoundException("Model with id '" + modelId + "' does not have source " + "available" + ".", String.class); } try { DeploymentBuilder deploymentBuilder = repositoryService.createDeployment(); String fileName = model.getId() + ".bpmn20.xml"; ByteArrayInputStream bis = new ByteArrayInputStream(bpmnBytes); deploymentBuilder.addInputStream(fileName, bis); deploymentBuilder.name(fileName); deploymentBuilder.category(model.getCategory()); XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader xmlIn = new InputStreamReader(new ByteArrayInputStream(bpmnBytes), "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn); BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr); org.flowable.bpmn.model.Process process = bpmnModel.getMainProcess(); Collection<FlowElement> flowElements = process.getFlowElements(); Map<String, String> formKeyMap = new HashMap<String, String>(16); for (FlowElement flowElement : flowElements) { String formKey = null; if (flowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) flowElement; if (startEvent.getFormKey() != null && startEvent.getFormKey().length() > 0) { formKey = startEvent.getFormKey(); } } else if (flowElement instanceof UserTask) { UserTask userTask = (UserTask) flowElement; if (userTask.getFormKey() != null && userTask.getFormKey().length() > 0) { formKey = userTask.getFormKey(); } } if (formKey != null && formKey.length() > 0) { if (formKeyMap.containsKey(formKey)) { continue; } else { String formKeyDefinition = formKey.replace(".form", ""); FlowableFormService flowableFormService = SpringContextUtils.getBean(FlowableFormService.class); FlowableForm form = flowableFormService.getById(formKeyDefinition); if (form != null && "json".equals(form.getFormType()) && form.getFormJson() != null && form.getFormJson().length() > 0) { byte[] formJson = form.getFormJson().getBytes("UTF-8"); ByteArrayInputStream bi = new ByteArrayInputStream(formJson); deploymentBuilder.addInputStream(formKey, bi); formKeyMap.put(formKey, formKey); }else if(form != null && "url".equals(form.getFormType()) && StringUtils.isNotBlank(form.getFormUrl())){ byte[] formUrl = form.getFormUrl().getBytes("UTF-8"); ByteArrayInputStream bi = new ByteArrayInputStream(formUrl); deploymentBuilder.addInputStream(formKey, bi); formKeyMap.put(formKey, formKey); } else { throw new FlowableObjectNotFoundException("Cannot find formJson with formKey " + formKeyDefinition); } } } } if (model.getTenantId() != null) { deploymentBuilder.tenantId(model.getTenantId()); } Deployment deployment = deploymentBuilder.deploy(); if (deployment != null) { model.setDeploymentId(deployment.getId()); } return deployment; } catch (Exception e) { if (e instanceof FlowableException) { throw (FlowableException) e; } throw new FlowableException(e.getMessage(), e); } }}