add derby database (#6996)

This commit is contained in:
Wuyunfan-BUPT 2021-09-27 00:41:44 -05:00 committed by GitHub
parent 3c0508d2da
commit fea9d7271b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 1498 additions and 74 deletions

View File

@ -71,6 +71,11 @@
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
@ -80,6 +85,7 @@
<artifactId>jjwt-impl</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>

View File

@ -0,0 +1,35 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.configuration;
import com.alibaba.nacos.auth.util.AuthPropertyUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Judge whether to user EmbeddedStorage by condition.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionOnEmbeddedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return AuthPropertyUtil.isEmbeddedStorage();
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.configuration;
import com.alibaba.nacos.auth.util.AuthPropertyUtil;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Judge whether to user StandaloneEmbedStorage by condition.
* When embeddedStorage==false.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionStandaloneEmbedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return AuthPropertyUtil.isEmbeddedStorage() && EnvUtil.getStandaloneMode();
}
}

View File

@ -0,0 +1,94 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.model.PermissionInfo;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* There is no self-augmented primary key.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class AuthEmbeddedPermissionPersistServiceImpl implements PermissionPersistService {
public static final PermissionRowMapper PERMISSION_ROW_MAPPER = new PermissionRowMapper();
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private AuthEmbeddedStoragePersistServiceImpl persistService;
@Override
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
PaginationHelper<PermissionInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM permissions WHERE ";
String sqlFetchRows = "SELECT role,resource,action FROM permissions WHERE ";
String where = " role= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(role)) {
params = Collections.singletonList(role);
} else {
where = " 1=1 ";
}
Page<PermissionInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public static final class PermissionRowMapper implements RowMapper<PermissionInfo> {
@Override
public PermissionInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
PermissionInfo info = new PermissionInfo();
info.setResource(rs.getString("resource"));
info.setAction(rs.getString("action"));
info.setRole(rs.getString("role"));
return info;
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.auth.roles.RoleInfo;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* There is no self-augmented primary key.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class AuthEmbeddedRolePersistServiceImpl implements RolePersistService {
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private AuthEmbeddedStoragePersistServiceImpl persistService;
public static final RoleInfoRowMapper ROLE_INFO_ROW_MAPPER = new RoleInfoRowMapper();
@Override
public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM roles WHERE ";
String sqlFetchRows = "SELECT role,username FROM roles WHERE ";
String where = " username= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(username)) {
params = Collections.singletonList(username);
} else {
where = " 1=1 ";
}
return helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
}
public static final class RoleInfoRowMapper implements RowMapper<RoleInfo> {
@Override
public RoleInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
RoleInfo roleInfo = new RoleInfo();
roleInfo.setRole(rs.getString("role"));
roleInfo.setUsername(rs.getString("username"));
return roleInfo;
}
}
}

View File

@ -0,0 +1,107 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.sql.EmbeddedStorageContextUtils;
import com.alibaba.nacos.auth.users.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* There is no self-augmented primary key.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class AuthEmbeddedUserPersistServiceImpl implements UserPersistService {
public static final RowMapper<User> USER_ROW_MAPPER = new UserRowMapper();
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private AuthEmbeddedStoragePersistServiceImpl persistService;
@Override
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
return databaseOperate.queryOne(sql, new Object[] {username}, USER_ROW_MAPPER);
}
/**
* Execute create user operation.
*
* @param username username string value.
* @param password password string value.
*/
@Override
public void createUser(String username, String password) {
String sql = "INSERT INTO users (username, password, enabled) VALUES (?, ?, ?)";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, username, password, true);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
@Override
public Page<User> getUsers(int pageNo, int pageSize) {
PaginationHelper<User> helper = persistService.createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM users WHERE ";
String sqlFetchRows = "SELECT username,password FROM users WHERE ";
String where = " 1=1 ";
Page<User> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, USER_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public static final class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
}
}

View File

@ -20,7 +20,7 @@ import com.alibaba.nacos.auth.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.model.PermissionInfo;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.util.LogUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -44,12 +44,12 @@ import java.util.List;
*/
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalPermissionPersistServiceImpl implements PermissionPersistService {
public class AuthExternalPermissionPersistServiceImpl implements PermissionPersistService {
public static final PermissionRowMapper PERMISSION_ROW_MAPPER = new PermissionRowMapper();
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private AuthExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;

View File

@ -19,7 +19,7 @@ package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.roles.RoleInfo;
import com.alibaba.nacos.auth.util.LogUtil;
import com.alibaba.nacos.common.utils.StringUtils;
@ -44,12 +44,12 @@ import java.util.List;
*/
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalRolePersistServiceImpl implements RolePersistService {
public class AuthExternalRolePersistServiceImpl implements RolePersistService {
public static final RoleInfoRowMapper ROLE_INFO_ROW_MAPPER = new RoleInfoRowMapper();
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private AuthExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;

View File

@ -19,7 +19,7 @@ package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.users.User;
import com.alibaba.nacos.auth.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
@ -42,12 +42,12 @@ import java.util.ArrayList;
*/
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalUserPersistServiceImpl implements UserPersistService {
public class AuthExternalUserPersistServiceImpl implements UserPersistService {
public static final RowMapper<User> USER_ROW_MAPPER = new UserRowMapper();
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private AuthExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;

View File

@ -25,15 +25,15 @@ import org.springframework.stereotype.Component;
* @author Nacos
*/
@Component
public class DynamicDataSource {
public class AuthDynamicDataSource {
private DataSourceService localDataSourceService = null;
private DataSourceService basicDataSourceService = null;
private static final DynamicDataSource INSTANCE = new DynamicDataSource();
private static final AuthDynamicDataSource INSTANCE = new AuthDynamicDataSource();
public static DynamicDataSource getInstance() {
public static AuthDynamicDataSource getInstance() {
return INSTANCE;
}

View File

@ -103,13 +103,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
FATAL_LOG.error("[ExternalDataSourceService] dats source reload error", e);
throw new RuntimeException(DB_LOAD_ERROR_MSG);
}
/*
if (this.dataSourceList.size() > DB_MASTER_SELECT_THRESHOLD) {
ConfigExecutor.scheduleConfigTask(new SelectMasterTask(), 10, 10, TimeUnit.SECONDS);
}
ConfigExecutor.scheduleConfigTask(new CheckDbHealthTask(), 10, 10, TimeUnit.SECONDS);
*/
}
}
@ -125,7 +118,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
isHealthList.add(Boolean.TRUE);
});
new SelectMasterTask().run();
//new CheckDbHealthTask().run();
} catch (RuntimeException e) {
FATAL_LOG.error(DB_LOAD_ERROR_MSG, e);
throw new IOException(e);
@ -222,39 +214,8 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
if (!isFound) {
FATAL_LOG.error("[master-db] master db not found.");
//MetricsMonitor.getDbException().increment();
}
}
}
/*
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
class CheckDbHealthTask implements Runnable {
@Override
public void run() {
if (DEFAULT_LOG.isDebugEnabled()) {
DEFAULT_LOG.debug("check db health.");
}
String sql = "SELECT * FROM config_info_beta WHERE id = 1";
for (int i = 0; i < testJtList.size(); i++) {
JdbcTemplate jdbcTemplate = testJtList.get(i);
try {
jdbcTemplate.query(sql, CONFIG_INFO4BETA_ROW_MAPPER);
isHealthList.set(i, Boolean.TRUE);
} catch (DataAccessException e) {
if (i == masterIndex) {
FATAL_LOG.error("[db-error] master db {} down.",
InternetAddressUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
} else {
FATAL_LOG.error("[db-error] slave db {} down.",
InternetAddressUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
}
isHealthList.set(i, Boolean.FALSE);
MetricsMonitor.getDbException().increment();
}
}
}
}*/
}

View File

@ -0,0 +1,47 @@
package com.alibaba.nacos.auth.persist.repository.embedded;
import com.alibaba.nacos.auth.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.auth.persist.datasource.DataSourceService;
import com.alibaba.nacos.auth.persist.datasource.AuthDynamicDataSource;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class AuthEmbeddedStoragePersistServiceImpl {
private DataSourceService dataSourceService;
private final DatabaseOperate databaseOperate;
public AuthEmbeddedStoragePersistServiceImpl(DatabaseOperate databaseOperate) {
this.databaseOperate = databaseOperate;
}
/**
* init datasource.
*/
@PostConstruct
public void init() {
dataSourceService = AuthDynamicDataSource.getInstance().getDataSource();
}
public <E> PaginationHelper<E> createPaginationHelper() {
return new EmbeddedPaginationHelperImpl<E>(databaseOperate);
}
/**
* For unit testing.
*/
public JdbcTemplate getJdbcTemplate() {
return this.dataSourceService.getJdbcTemplate();
}
public DatabaseOperate getDatabaseOperate() {
return databaseOperate;
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.repository.embedded;
import com.alibaba.nacos.auth.configuration.ConditionStandaloneEmbedStorage;
import com.alibaba.nacos.auth.persist.datasource.DataSourceService;
import com.alibaba.nacos.auth.persist.datasource.AuthDynamicDataSource;
import com.alibaba.nacos.auth.persist.sql.ModifyRequest;
import com.alibaba.nacos.auth.util.LogUtil;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* Derby operation in stand-alone mode.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@Conditional(ConditionStandaloneEmbedStorage.class)
@Component
public class AuthStandaloneDatabaseOperateImpl implements BaseDatabaseOperate {
private JdbcTemplate jdbcTemplate;
private TransactionTemplate transactionTemplate;
@PostConstruct
protected void init() {
DataSourceService dataSourceService = AuthDynamicDataSource.getInstance().getDataSource();
jdbcTemplate = dataSourceService.getJdbcTemplate();
transactionTemplate = dataSourceService.getTransactionTemplate();
LogUtil.DEFAULT_LOG.info("use StandaloneDatabaseOperateImpl");
}
@Override
public <R> R queryOne(String sql, Class<R> cls) {
return queryOne(jdbcTemplate, sql, cls);
}
@Override
public <R> R queryOne(String sql, Object[] args, Class<R> cls) {
return queryOne(jdbcTemplate, sql, args, cls);
}
@Override
public <R> R queryOne(String sql, Object[] args, RowMapper<R> mapper) {
return queryOne(jdbcTemplate, sql, args, mapper);
}
@Override
public <R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper) {
return queryMany(jdbcTemplate, sql, args, mapper);
}
@Override
public <R> List<R> queryMany(String sql, Object[] args, Class<R> rClass) {
return queryMany(jdbcTemplate, sql, args, rClass);
}
@Override
public List<Map<String, Object>> queryMany(String sql, Object[] args) {
return queryMany(jdbcTemplate, sql, args);
}
@Override
public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) {
return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer);
}
}

View File

@ -0,0 +1,242 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.repository.embedded;
import com.alibaba.nacos.auth.persist.sql.ModifyRequest;
import com.alibaba.nacos.auth.util.LogUtil;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.LoggerUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import static com.alibaba.nacos.auth.util.LogUtil.FATAL_LOG;
/**
* The Derby database basic operation.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("PMD.AbstractMethodOrInterfaceMethodMustUseJavadocRule")
public interface BaseDatabaseOperate extends DatabaseOperate {
/**
* query one result by sql then convert result to target type.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param cls target type
* @param <R> target type
* @return R
*/
default <R> R queryOne(JdbcTemplate jdbcTemplate, String sql, Class<R> cls) {
try {
return jdbcTemplate.queryForObject(sql, cls);
} catch (IncorrectResultSizeDataAccessException e) {
return null;
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] can't get connection : {}", ExceptionUtil.getAllExceptionMsg(e));
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException : {}", ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* query one result by sql and args then convert result to target type.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param args args
* @param cls target type
* @param <R> target type
* @return R
*/
default <R> R queryOne(JdbcTemplate jdbcTemplate, String sql, Object[] args, Class<R> cls) {
try {
return jdbcTemplate.queryForObject(sql, args, cls);
} catch (IncorrectResultSizeDataAccessException e) {
return null;
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] {}", e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", sql, args,
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* query one result by sql and args then convert result to target type through {@link RowMapper}.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param args args
* @param mapper {@link RowMapper}
* @param <R> target type
* @return R
*/
default <R> R queryOne(JdbcTemplate jdbcTemplate, String sql, Object[] args, RowMapper<R> mapper) {
try {
return jdbcTemplate.queryForObject(sql, args, mapper);
} catch (IncorrectResultSizeDataAccessException e) {
return null;
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] {}", e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", sql, args,
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* query many result by sql and args then convert result to target type through {@link RowMapper}.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param args args
* @param mapper {@link RowMapper}
* @param <R> target type
* @return result list
*/
default <R> List<R> queryMany(JdbcTemplate jdbcTemplate, String sql, Object[] args, RowMapper<R> mapper) {
try {
return jdbcTemplate.query(sql, args, mapper);
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] {}", e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", sql, args,
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* query many result by sql and args then convert result to target type.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param args args
* @param rClass target type class
* @param <R> target type
* @return result list
*/
default <R> List<R> queryMany(JdbcTemplate jdbcTemplate, String sql, Object[] args, Class<R> rClass) {
try {
return jdbcTemplate.queryForList(sql, args, rClass);
} catch (IncorrectResultSizeDataAccessException e) {
return null;
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] {}", e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", sql, args,
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* query many result by sql and args then convert result to List&lt;Map&lt;String, Object&gt;&gt;.
*
* @param jdbcTemplate {@link JdbcTemplate}
* @param sql sql
* @param args args
* @return List&lt;Map&lt;String, Object&gt;&gt;
*/
default List<Map<String, Object>> queryMany(JdbcTemplate jdbcTemplate, String sql, Object[] args) {
try {
return jdbcTemplate.queryForList(sql, args);
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] {}", e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", sql, args,
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
}
/**
* execute update operation.
*
* @param transactionTemplate {@link TransactionTemplate}
* @param jdbcTemplate {@link JdbcTemplate}
* @param contexts {@link List} ModifyRequest list
* @return {@link Boolean}
*/
default Boolean update(TransactionTemplate transactionTemplate, JdbcTemplate jdbcTemplate,
List<ModifyRequest> contexts) {
return update(transactionTemplate, jdbcTemplate, contexts, null);
}
/**
* execute update operation, to fix #3617.
*
* @param transactionTemplate {@link TransactionTemplate}
* @param jdbcTemplate {@link JdbcTemplate}
* @param contexts {@link List} ModifyRequest list
* @return {@link Boolean}
*/
default Boolean update(TransactionTemplate transactionTemplate, JdbcTemplate jdbcTemplate,
List<ModifyRequest> contexts, BiConsumer<Boolean, Throwable> consumer) {
return transactionTemplate.execute(status -> {
String[] errSql = new String[] {null};
Object[][] args = new Object[][] {null};
try {
contexts.forEach(pair -> {
errSql[0] = pair.getSql();
args[0] = pair.getArgs();
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "current sql : {}", errSql[0]);
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "current args : {}", args[0]);
jdbcTemplate.update(pair.getSql(), pair.getArgs());
});
if (consumer != null) {
consumer.accept(Boolean.TRUE, null);
}
return Boolean.TRUE;
} catch (BadSqlGrammarException | DataIntegrityViolationException e) {
FATAL_LOG.error("[db-error] sql : {}, args : {}, error : {}", errSql[0], args[0], e.toString());
if (consumer != null) {
consumer.accept(Boolean.FALSE, e);
}
return Boolean.FALSE;
} catch (CannotGetJdbcConnectionException e) {
FATAL_LOG.error("[db-error] sql : {}, args : {}, error : {}", errSql[0], args[0], e.toString());
throw e;
} catch (DataAccessException e) {
FATAL_LOG.error("[db-error] DataAccessException sql : {}, args : {}, error : {}", errSql[0], args[0],
ExceptionUtil.getAllExceptionMsg(e));
throw e;
}
});
}
}

View File

@ -0,0 +1,131 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.repository.embedded;
import com.alibaba.nacos.auth.persist.sql.EmbeddedStorageContextUtils;
import com.alibaba.nacos.auth.persist.sql.ModifyRequest;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* Derby database operation.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public interface DatabaseOperate {
/**
* Data query transaction.
*
* @param sql sqk text
* @param cls target type
* @param <R> return type
* @return query result
*/
<R> R queryOne(String sql, Class<R> cls);
/**
* Data query transaction.
*
* @param sql sqk text
* @param args sql parameters
* @param cls target type
* @param <R> return type
* @return query result
*/
<R> R queryOne(String sql, Object[] args, Class<R> cls);
/**
* Data query transaction.
*
* @param sql sqk text
* @param args sql parameters
* @param mapper Database query result converter
* @param <R> return type
* @return query result
*/
<R> R queryOne(String sql, Object[] args, RowMapper<R> mapper);
/**
* Data query transaction.
*
* @param sql sqk text
* @param args sql parameters
* @param mapper Database query result converter
* @param <R> return type
* @return query result
*/
<R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper);
/**
* Data query transaction.
*
* @param sql sqk text
* @param args sql parameters
* @param rClass target type
* @param <R> return type
* @return query result
*/
<R> List<R> queryMany(String sql, Object[] args, Class<R> rClass);
/**
* Data query transaction.
*
* @param sql sqk text
* @param args sql parameters
* @return query result
*/
List<Map<String, Object>> queryMany(String sql, Object[] args);
/**
* data modify transaction The SqlContext to be executed in the current thread will be executed and automatically
* cleared.
*
* @return is success
*/
default Boolean blockUpdate() {
return blockUpdate(null);
}
/**
* data modify transaction The SqlContext to be executed in the current thread will be executed and automatically
* cleared.
* @author klw(213539@qq.com)
* 2020/8/24 18:16
* @param consumer the consumer
* @return java.lang.Boolean
*/
default Boolean blockUpdate(BiConsumer<Boolean, Throwable> consumer) {
try {
return update(EmbeddedStorageContextUtils.getCurrentSqlContext(), consumer);
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
/**
* data modify transaction.
*
* @param modifyRequests {@link List}
* @param consumer {@link BiConsumer}
* @return is success
*/
Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer);
}

View File

@ -0,0 +1,186 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.repository.embedded;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
/**
* Pagination Utils For Apache Derby.
*
* @param <E> Generic class
* @author boyan
* @date 2010-5-6
*/
class EmbeddedPaginationHelperImpl<E> implements PaginationHelper {
private final DatabaseOperate databaseOperate;
public EmbeddedPaginationHelperImpl(DatabaseOperate databaseOperate) {
this.databaseOperate = databaseOperate;
}
/**
* Take paging.
*
* @param sqlCountRows Query total SQL
* @param sqlFetchRows Query data sql
* @param args query args
* @param pageNo page number
* @param pageSize page size
* @param rowMapper Entity mapping
* @return Paging data
*/
@Override
public Page<E> fetchPage(final String sqlCountRows, final String sqlFetchRows, final Object[] args,
final int pageNo, final int pageSize, final RowMapper rowMapper) {
return fetchPage(sqlCountRows, sqlFetchRows, args, pageNo, pageSize, null, rowMapper);
}
@Override
public Page<E> fetchPage(final String sqlCountRows, final String sqlFetchRows, final Object[] args,
final int pageNo, final int pageSize, final Long lastMaxId, final RowMapper rowMapper) {
if (pageNo <= 0 || pageSize <= 0) {
throw new IllegalArgumentException("pageNo and pageSize must be greater than zero");
}
// Query the total number of current records
Integer rowCountInt = databaseOperate.queryOne(sqlCountRows, args, Integer.class);
if (rowCountInt == null) {
throw new IllegalArgumentException("fetchPageLimit error");
}
// Count pages
int pageCount = rowCountInt / pageSize;
if (rowCountInt > pageSize * pageCount) {
pageCount++;
}
// Create Page object
final Page<E> page = new Page<E>();
page.setPageNumber(pageNo);
page.setPagesAvailable(pageCount);
page.setTotalCount(rowCountInt);
if (pageNo > pageCount) {
return page;
}
final int startRow = (pageNo - 1) * pageSize;
String selectSql = sqlFetchRows + " OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
List<E> result = databaseOperate.queryMany(selectSql, args, rowMapper);
for (E item : result) {
page.getPageItems().add(item);
}
return page;
}
@Override
public Page<E> fetchPageLimit(final String sqlCountRows, final String sqlFetchRows, final Object[] args,
final int pageNo, final int pageSize, final RowMapper rowMapper) {
if (pageNo <= 0 || pageSize <= 0) {
throw new IllegalArgumentException("pageNo and pageSize must be greater than zero");
}
// Query the total number of current records
Integer rowCountInt = databaseOperate.queryOne(sqlCountRows, Integer.class);
if (rowCountInt == null) {
throw new IllegalArgumentException("fetchPageLimit error");
}
// Count pages
int pageCount = rowCountInt / pageSize;
if (rowCountInt > pageSize * pageCount) {
pageCount++;
}
// Create Page object
final Page<E> page = new Page<E>();
page.setPageNumber(pageNo);
page.setPagesAvailable(pageCount);
page.setTotalCount(rowCountInt);
if (pageNo > pageCount) {
return page;
}
String selectSql = sqlFetchRows.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
List<E> result = databaseOperate.queryMany(selectSql, args, rowMapper);
for (E item : result) {
page.getPageItems().add(item);
}
return page;
}
@Override
public Page<E> fetchPageLimit(final String sqlCountRows, final Object[] args1, final String sqlFetchRows,
final Object[] args2, final int pageNo, final int pageSize, final RowMapper rowMapper) {
if (pageNo <= 0 || pageSize <= 0) {
throw new IllegalArgumentException("pageNo and pageSize must be greater than zero");
}
// Query the total number of current records
Integer rowCountInt = databaseOperate.queryOne(sqlCountRows, args1, Integer.class);
if (rowCountInt == null) {
throw new IllegalArgumentException("fetchPageLimit error");
}
// Count pages
int pageCount = rowCountInt / pageSize;
if (rowCountInt > pageSize * pageCount) {
pageCount++;
}
// Create Page object
final Page<E> page = new Page<E>();
page.setPageNumber(pageNo);
page.setPagesAvailable(pageCount);
page.setTotalCount(rowCountInt);
if (pageNo > pageCount) {
return page;
}
String selectSql = sqlFetchRows.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
List<E> result = databaseOperate.queryMany(selectSql, args2, rowMapper);
for (E item : result) {
page.getPageItems().add(item);
}
return page;
}
@Override
public Page<E> fetchPageLimit(final String sqlFetchRows, final Object[] args, final int pageNo, final int pageSize,
final RowMapper rowMapper) {
if (pageNo <= 0 || pageSize <= 0) {
throw new IllegalArgumentException("pageNo and pageSize must be greater than zero");
}
// Create Page object
final Page<E> page = new Page<E>();
String selectSql = sqlFetchRows.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
List<E> result = databaseOperate.queryMany(selectSql, args, rowMapper);
for (E item : result) {
page.getPageItems().add(item);
}
return page;
}
}

View File

@ -18,7 +18,7 @@ package com.alibaba.nacos.auth.persist.repository.externel;
import com.alibaba.nacos.auth.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.auth.persist.datasource.DataSourceService;
import com.alibaba.nacos.auth.persist.datasource.DynamicDataSource;
import com.alibaba.nacos.auth.persist.datasource.AuthDynamicDataSource;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.JdbcTemplate;
@ -29,7 +29,7 @@ import javax.annotation.PostConstruct;
@SuppressWarnings(value = {"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"})
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalStoragePersistServiceImpl {
public class AuthExternalStoragePersistServiceImpl {
private DataSourceService dataSourceService;
@ -40,7 +40,7 @@ public class ExternalStoragePersistServiceImpl {
*/
@PostConstruct
public void init() {
dataSourceService = DynamicDataSource.getInstance().getDataSource();
dataSourceService = AuthDynamicDataSource.getInstance().getDataSource();
jt = getJdbcTemplate();
}

View File

@ -0,0 +1,100 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.sql;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Temporarily saves all insert, update, and delete statements under a transaction in the order in which they occur.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class EmbeddedStorageContextUtils {
private static final ThreadLocal<ArrayList<ModifyRequest>> SQL_CONTEXT = ThreadLocal.withInitial(ArrayList::new);
private static final ThreadLocal<Map<String, String>> EXTEND_INFO_CONTEXT = ThreadLocal.withInitial(HashMap::new);
/**
* Add sql context.
*
* @param sql sql
* @param args argument list
*/
public static void addSqlContext(String sql, Object... args) {
ArrayList<ModifyRequest> requests = SQL_CONTEXT.get();
ModifyRequest context = new ModifyRequest();
context.setExecuteNo(requests.size());
context.setSql(sql);
context.setArgs(args);
requests.add(context);
SQL_CONTEXT.set(requests);
}
/**
* Put extend info.
*
* @param key key
* @param value value
*/
public static void putExtendInfo(String key, String value) {
Map<String, String> old = EXTEND_INFO_CONTEXT.get();
old.put(key, value);
EXTEND_INFO_CONTEXT.set(old);
}
/**
* Put all extend info.
*
* @param map all extend info
*/
public static void putAllExtendInfo(Map<String, String> map) {
Map<String, String> old = EXTEND_INFO_CONTEXT.get();
old.putAll(map);
EXTEND_INFO_CONTEXT.set(old);
}
/**
* Determine if key is included.
*
* @param key key
* @return {@code true} if contains key
*/
public static boolean containsExtendInfo(String key) {
Map<String, String> extendInfo = EXTEND_INFO_CONTEXT.get();
boolean exist = extendInfo.containsKey(key);
EXTEND_INFO_CONTEXT.set(extendInfo);
return exist;
}
public static List<ModifyRequest> getCurrentSqlContext() {
return SQL_CONTEXT.get();
}
public static Map<String, String> getCurrentExtendInfo() {
return EXTEND_INFO_CONTEXT.get();
}
public static void cleanAllContext() {
SQL_CONTEXT.remove();
EXTEND_INFO_CONTEXT.remove();
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist.sql;
import java.io.Serializable;
import java.util.Arrays;
/**
* Represents a database UPDATE or INSERT or DELETE statement.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class ModifyRequest implements Serializable {
private static final long serialVersionUID = 4548851816596520564L;
private int executeNo;
private String sql;
private Object[] args;
public ModifyRequest() {
}
public ModifyRequest(String sql) {
this.sql = sql;
}
public int getExecuteNo() {
return executeNo;
}
public void setExecuteNo(int executeNo) {
this.executeNo = executeNo;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
@Override
public String toString() {
return "SQL{" + "executeNo=" + executeNo + ", sql='" + sql + '\'' + ", args=" + Arrays.toString(args) + '}';
}
}

View File

@ -0,0 +1,2 @@
org.springframework.context.ApplicationContextInitializer=\
com.alibaba.nacos.auth.util.AuthPropertyUtil

View File

@ -0,0 +1,70 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.model.PermissionInfo;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class AuthEmbeddedPermissionPersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
@Mock
private PaginationHelper paginationHelper;
@Mock
private AuthEmbeddedStoragePersistServiceImpl embeddedStoragePersistService;
private AuthEmbeddedPermissionPersistServiceImpl embeddedPermissionPersistService;
@Before
public void setUp() throws Exception {
embeddedPermissionPersistService = new AuthEmbeddedPermissionPersistServiceImpl();
Class<AuthEmbeddedPermissionPersistServiceImpl> embeddedPermissionPersistServiceClass = AuthEmbeddedPermissionPersistServiceImpl.class;
Field databaseOperateF = embeddedPermissionPersistServiceClass.getDeclaredField("databaseOperate");
databaseOperateF.setAccessible(true);
databaseOperateF.set(embeddedPermissionPersistService, databaseOperate);
Field persistService = embeddedPermissionPersistServiceClass.getDeclaredField("persistService");
persistService.setAccessible(true);
persistService.set(embeddedPermissionPersistService, embeddedStoragePersistService);
Mockito.when(embeddedStoragePersistService.createPaginationHelper()).thenReturn(paginationHelper);
}
@Test
public void testGetPermissions() {
String role = "role";
Page<PermissionInfo> permissions = embeddedPermissionPersistService.getPermissions(role, 1, 10);
Assert.assertNotNull(permissions);
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.auth.roles.RoleInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class AuthEmbeddedRolePersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
@Mock
private AuthEmbeddedStoragePersistServiceImpl persistService;
@Mock
private PaginationHelper paginationHelper;
private AuthEmbeddedRolePersistServiceImpl embeddedRolePersistService;
@Before
public void setUp() throws Exception {
embeddedRolePersistService = new AuthEmbeddedRolePersistServiceImpl();
Class<AuthEmbeddedRolePersistServiceImpl> embeddedRolePersistServiceClass = AuthEmbeddedRolePersistServiceImpl.class;
Field databaseOperateFields = embeddedRolePersistServiceClass.getDeclaredField("databaseOperate");
databaseOperateFields.setAccessible(true);
databaseOperateFields.set(embeddedRolePersistService, databaseOperate);
Field persistServiceField = embeddedRolePersistServiceClass.getDeclaredField("persistService");
persistServiceField.setAccessible(true);
persistServiceField.set(embeddedRolePersistService, persistService);
Mockito.when(persistService.createPaginationHelper()).thenReturn(paginationHelper);
}
@Test
public void testGetRolesByUserName() {
Page<RoleInfo> page = embeddedRolePersistService.getRolesByUserName("userName", 1, 10);
Assert.assertNull(page);
}
}

View File

@ -0,0 +1,85 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.auth.persist.repository.embedded.AuthEmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.auth.users.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class AuthEmbeddedUserPersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
@Mock
private AuthEmbeddedStoragePersistServiceImpl persistService;
@Mock
private PaginationHelper paginationHelper;
private AuthEmbeddedUserPersistServiceImpl embeddedUserPersistService;
@Before
public void setUp() throws Exception {
embeddedUserPersistService = new AuthEmbeddedUserPersistServiceImpl();
Class<AuthEmbeddedUserPersistServiceImpl> embeddedUserPersistServiceClass = AuthEmbeddedUserPersistServiceImpl.class;
Field databaseOperateField = embeddedUserPersistServiceClass.getDeclaredField("databaseOperate");
databaseOperateField.setAccessible(true);
databaseOperateField.set(embeddedUserPersistService, databaseOperate);
Field persistServiceClassDeclaredField = embeddedUserPersistServiceClass.getDeclaredField("persistService");
persistServiceClassDeclaredField.setAccessible(true);
persistServiceClassDeclaredField.set(embeddedUserPersistService, persistService);
Mockito.when(persistService.createPaginationHelper()).thenReturn(paginationHelper);
}
@Test
public void testCreateUser() {
embeddedUserPersistService.createUser("username", "password");
Mockito.verify(databaseOperate).blockUpdate();
}
@Test
public void testFindUserByUsername() {
User user = embeddedUserPersistService.findUserByUsername("username");
Assert.assertNull(user);
}
@Test
public void testGetUsers() {
Page<User> users = embeddedUserPersistService.getUsers(1, 10);
Assert.assertNotNull(users);
}
}

View File

@ -19,7 +19,7 @@ package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.model.PermissionInfo;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@ -32,10 +32,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class ExternalPermissionPersistServiceImplTest {
public class AuthExternalPermissionPersistServiceImplTest {
@Mock
private ExternalStoragePersistServiceImpl externalStoragePersistService;
private AuthExternalStoragePersistServiceImpl externalStoragePersistService;
@Mock
private JdbcTemplate jdbcTemplate;
@ -43,13 +43,13 @@ public class ExternalPermissionPersistServiceImplTest {
@Mock
private PaginationHelper paginationHelper;
private ExternalPermissionPersistServiceImpl externalPermissionPersistService;
private AuthExternalPermissionPersistServiceImpl externalPermissionPersistService;
@Before
public void setUp() throws Exception {
externalPermissionPersistService = new ExternalPermissionPersistServiceImpl();
externalPermissionPersistService = new AuthExternalPermissionPersistServiceImpl();
Class<ExternalPermissionPersistServiceImpl> externalPermissionPersistServiceClass = ExternalPermissionPersistServiceImpl.class;
Class<AuthExternalPermissionPersistServiceImpl> externalPermissionPersistServiceClass = AuthExternalPermissionPersistServiceImpl.class;
Field persistServiceClassDeclaredField = externalPermissionPersistServiceClass
.getDeclaredField("persistService");
persistServiceClassDeclaredField.setAccessible(true);

View File

@ -18,7 +18,7 @@ package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.roles.RoleInfo;
import org.junit.Assert;
import org.junit.Before;
@ -32,10 +32,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class ExternalRolePersistServiceImplTest {
public class AuthExternalRolePersistServiceImplTest {
@Mock
private ExternalStoragePersistServiceImpl persistService;
private AuthExternalStoragePersistServiceImpl persistService;
@Mock
private JdbcTemplate jt;
@ -43,12 +43,12 @@ public class ExternalRolePersistServiceImplTest {
@Mock
private PaginationHelper paginationHelper;
private ExternalRolePersistServiceImpl externalRolePersistService;
private AuthExternalRolePersistServiceImpl externalRolePersistService;
@Before
public void setUp() throws Exception {
externalRolePersistService = new ExternalRolePersistServiceImpl();
Class<ExternalRolePersistServiceImpl> externalRolePersistServiceClass = ExternalRolePersistServiceImpl.class;
externalRolePersistService = new AuthExternalRolePersistServiceImpl();
Class<AuthExternalRolePersistServiceImpl> externalRolePersistServiceClass = AuthExternalRolePersistServiceImpl.class;
Field persistServiceClassDeclaredField = externalRolePersistServiceClass.getDeclaredField("persistService");
persistServiceClassDeclaredField.setAccessible(true);
persistServiceClassDeclaredField.set(externalRolePersistService, persistService);

View File

@ -19,7 +19,7 @@ package com.alibaba.nacos.auth.persist;
import com.alibaba.nacos.auth.model.Page;
import com.alibaba.nacos.auth.users.User;
import com.alibaba.nacos.auth.persist.repository.PaginationHelper;
import com.alibaba.nacos.auth.persist.repository.externel.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.auth.persist.repository.externel.AuthExternalStoragePersistServiceImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@ -32,10 +32,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Field;
@RunWith(MockitoJUnitRunner.class)
public class ExternalUserPersistServiceImplTest {
public class AuthExternalUserPersistServiceImplTest {
@Mock
private ExternalStoragePersistServiceImpl persistService;
private AuthExternalStoragePersistServiceImpl persistService;
@Mock
private JdbcTemplate jdbcTemplate;
@ -43,13 +43,13 @@ public class ExternalUserPersistServiceImplTest {
@Mock
private PaginationHelper paginationHelper;
private ExternalUserPersistServiceImpl externalUserPersistService;
private AuthExternalUserPersistServiceImpl externalUserPersistService;
@Before
public void setUp() throws Exception {
externalUserPersistService = new ExternalUserPersistServiceImpl();
externalUserPersistService = new AuthExternalUserPersistServiceImpl();
Class<ExternalUserPersistServiceImpl> externalUserPersistServiceClass = ExternalUserPersistServiceImpl.class;
Class<AuthExternalUserPersistServiceImpl> externalUserPersistServiceClass = AuthExternalUserPersistServiceImpl.class;
Field persistServiceClassDeclaredField = externalUserPersistServiceClass.getDeclaredField("persistService");
persistServiceClassDeclaredField.setAccessible(true);
persistServiceClassDeclaredField.set(externalUserPersistService, persistService);

View File

@ -52,7 +52,7 @@ public class DataSourcePoolPropertiesTest {
public void testBuild() {
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
poolProperties.setJdbcUrl(JDBC_URL);
// poolProperties.setDriverClassName(JDBC_DRIVER_CLASS_NAME);
poolProperties.setDriverClassName(JDBC_DRIVER_CLASS_NAME);
poolProperties.setUsername(USERNAME);
poolProperties.setPassword(PASSWORD);
HikariDataSource actual = poolProperties.getDataSource();