Skip to content

Commit

Permalink
Add more rules for checkstyle (apache#24886)
Browse files Browse the repository at this point in the history
* Add more rule for checkstyle

* Add more rule for checkstyle

* Add more rule for checkstyle
  • Loading branch information
terrymanu authored Mar 28, 2023
1 parent d7d3863 commit d852884
Show file tree
Hide file tree
Showing 23 changed files with 326 additions and 278 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.invocation.InvocationOnMock;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
Expand Down Expand Up @@ -74,17 +75,7 @@ public void prepare() {
when(connection.getMetaData()).thenReturn(databaseMetaData);
when(statement.getConnection()).thenReturn(connection);
executionUnit = new JDBCExecutionUnit(new ExecutionUnit(DATA_SOURCE_NAME, new SQLUnit(SQL, Collections.emptyList())), null, statement);
JDBCExecutorCallback mockedJDBCExecutorCallback = mock(JDBCExecutorCallback.class, invocation -> {
switch (invocation.getMethod().getName()) {
case "getAttachment":
return attachment;
case "setAttachment":
attachment = invocation.getArguments()[0];
return null;
default:
return invocation.callRealMethod();
}
});
JDBCExecutorCallback mockedJDBCExecutorCallback = mock(JDBCExecutorCallback.class, this::mockAttachment);
Map<String, DataSourceMetaData> cachedDatasourceMetaData = (Map<String, DataSourceMetaData>) Plugins.getMemberAccessor()
.get(JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA"), mockedJDBCExecutorCallback);
cachedDatasourceMetaData.put("mock_url", mock(DataSourceMetaData.class));
Expand All @@ -93,6 +84,20 @@ public void prepare() {
targetObject = (TargetAdviceObject) mockedJDBCExecutorCallback;
}

// CHECKSTYLE:OFF
private Object mockAttachment(final InvocationOnMock invocation) throws Throwable {
// CHECKSTYLE:ON
switch (invocation.getMethod().getName()) {
case "getAttachment":
return attachment;
case "setAttachment":
attachment = invocation.getArguments()[0];
return null;
default:
return invocation.callRealMethod();
}
}

/**
* Get database type.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.apache.shardingsphere.agent.plugin.tracing.TracingAgentExtension;
import org.apache.shardingsphere.infra.parser.ShardingSphereSQLParserEngine;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.invocation.InvocationOnMock;

import static org.mockito.Mockito.mock;

Expand All @@ -36,17 +37,21 @@ public abstract class AbstractSQLParserEngineAdviceTest implements AdviceTestBas
@SuppressWarnings("ConstantConditions")
@Override
public final void prepare() {
Object parserEngine = mock(ShardingSphereSQLParserEngine.class, invocation -> {
switch (invocation.getMethod().getName()) {
case "getAttachment":
return attachment;
case "setAttachment":
attachment = invocation.getArguments()[0];
return null;
default:
return invocation.callRealMethod();
}
});
Object parserEngine = mock(ShardingSphereSQLParserEngine.class, this::mockAttachment);
targetObject = (TargetAdviceObject) parserEngine;
}

// CHECKSTYLE:OFF
private Object mockAttachment(final InvocationOnMock invocation) throws Throwable {
// CHECKSTYLE:ON
switch (invocation.getMethod().getName()) {
case "getAttachment":
return attachment;
case "setAttachment":
attachment = invocation.getArguments()[0];
return null;
default:
return invocation.callRealMethod();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -171,21 +171,20 @@ private Collection<String> decodeText(final String value) {
Preconditions.checkArgument(value.length() >= 2, "value length less than 2");
Preconditions.checkArgument('{' == value.charAt(0) && '}' == value.charAt(value.length() - 1), "value not start with '{' or not end with '}'");
String[] elements = value.substring(1, value.length() - 1).split(",");
return Arrays.stream(elements).map(each -> {
if ("NULL".equals(each)) {
return null;
}
String result = each;
if ('"' == result.charAt(0) && '"' == result.charAt(result.length() - 1)) {
result = result.substring(1, result.length() - 1);
}
while (result.contains("\\\"")) {
result = result.replace("\\\"", "\"");
}
while (result.contains("\\\\")) {
result = result.replace("\\\\", "\\");
}
return result;
}).collect(Collectors.toList());
return Arrays.stream(elements).map(each -> "NULL".equals(each) ? null : decodeElementText(each)).collect(Collectors.toList());
}

private static String decodeElementText(final String element) {
String result = element;
if ('"' == result.charAt(0) && '"' == result.charAt(result.length() - 1)) {
result = result.substring(1, result.length() - 1);
}
while (result.contains("\\\"")) {
result = result.replace("\\\"", "\"");
}
while (result.contains("\\\\")) {
result = result.replace("\\\\", "\\");
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,40 +65,40 @@ public void rewrite(final ParameterBuilder paramBuilder, final InsertStatementCo
OnDuplicateUpdateContext onDuplicateKeyUpdateValueContext = insertStatementContext.getOnDuplicateKeyUpdateValueContext();
String schemaName = insertStatementContext.getTablesContext().getSchemaName().orElseGet(() -> DatabaseTypeEngine.getDefaultSchemaName(insertStatementContext.getDatabaseType(), databaseName));
for (int index = 0; index < onDuplicateKeyUpdateValueContext.getValueExpressions().size(); index++) {
int columnIndex = index;
String encryptLogicColumnName = onDuplicateKeyUpdateValueContext.getColumn(columnIndex).getIdentifier().getValue();
String encryptLogicColumnName = onDuplicateKeyUpdateValueContext.getColumn(index).getIdentifier().getValue();
EncryptContext encryptContext = EncryptContextBuilder.build(databaseName, schemaName, tableName, encryptLogicColumnName);
Optional<StandardEncryptAlgorithm> encryptor = encryptRule.findEncryptor(tableName, encryptLogicColumnName);
encryptor.ifPresent(optional -> {
Object plainColumnValue = onDuplicateKeyUpdateValueContext.getValue(columnIndex);
if (plainColumnValue instanceof FunctionSegment && "VALUES".equalsIgnoreCase(((FunctionSegment) plainColumnValue).getFunctionName())) {
return;
if (!encryptor.isPresent()) {
continue;
}
Object plainColumnValue = onDuplicateKeyUpdateValueContext.getValue(index);
if (plainColumnValue instanceof FunctionSegment && "VALUES".equalsIgnoreCase(((FunctionSegment) plainColumnValue).getFunctionName())) {
return;
}
Object cipherColumnValue = encryptor.get().encrypt(plainColumnValue, encryptContext);
groupedParamBuilder.getGenericParameterBuilder().addReplacedParameters(index, cipherColumnValue);
Collection<Object> addedParams = new LinkedList<>();
Optional<StandardEncryptAlgorithm> assistedQueryEncryptor = encryptRule.findAssistedQueryEncryptor(tableName, encryptLogicColumnName);
if (assistedQueryEncryptor.isPresent()) {
Optional<String> assistedColumnName = encryptRule.findAssistedQueryColumn(tableName, encryptLogicColumnName);
Preconditions.checkArgument(assistedColumnName.isPresent(), "Can not find assisted query Column Name");
addedParams.add(assistedQueryEncryptor.get().encrypt(plainColumnValue, encryptContext));
}
Optional<LikeEncryptAlgorithm> likeQueryEncryptor = encryptRule.findLikeQueryEncryptor(tableName, encryptLogicColumnName);
if (likeQueryEncryptor.isPresent()) {
Optional<String> likeColumnName = encryptRule.findLikeQueryColumn(tableName, encryptLogicColumnName);
Preconditions.checkArgument(likeColumnName.isPresent(), "Can not find assisted query Column Name");
addedParams.add(likeQueryEncryptor.get().encrypt(plainColumnValue, encryptContext));
}
if (encryptRule.findPlainColumn(tableName, encryptLogicColumnName).isPresent()) {
addedParams.add(plainColumnValue);
}
if (!addedParams.isEmpty()) {
if (!groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().containsKey(index)) {
groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().put(index, new LinkedList<>());
}
Object cipherColumnValue = encryptor.get().encrypt(plainColumnValue, encryptContext);
groupedParamBuilder.getGenericParameterBuilder().addReplacedParameters(columnIndex, cipherColumnValue);
Collection<Object> addedParams = new LinkedList<>();
Optional<StandardEncryptAlgorithm> assistedQueryEncryptor = encryptRule.findAssistedQueryEncryptor(tableName, encryptLogicColumnName);
if (assistedQueryEncryptor.isPresent()) {
Optional<String> assistedColumnName = encryptRule.findAssistedQueryColumn(tableName, encryptLogicColumnName);
Preconditions.checkArgument(assistedColumnName.isPresent(), "Can not find assisted query Column Name");
addedParams.add(assistedQueryEncryptor.get().encrypt(plainColumnValue, encryptContext));
}
Optional<LikeEncryptAlgorithm> likeQueryEncryptor = encryptRule.findLikeQueryEncryptor(tableName, encryptLogicColumnName);
if (likeQueryEncryptor.isPresent()) {
Optional<String> likeColumnName = encryptRule.findLikeQueryColumn(tableName, encryptLogicColumnName);
Preconditions.checkArgument(likeColumnName.isPresent(), "Can not find assisted query Column Name");
addedParams.add(likeQueryEncryptor.get().encrypt(plainColumnValue, encryptContext));
}
if (encryptRule.findPlainColumn(tableName, encryptLogicColumnName).isPresent()) {
addedParams.add(plainColumnValue);
}
if (!addedParams.isEmpty()) {
if (!groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().containsKey(columnIndex)) {
groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().put(columnIndex, new LinkedList<>());
}
groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().get(columnIndex).addAll(addedParams);
}
});
groupedParamBuilder.getGenericParameterBuilder().getAddedIndexAndParameters().get(index).addAll(addedParams);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,25 @@ private Collection<LocalDataQueryResultRow> buildData(final EncryptRuleConfigura
private Collection<LocalDataQueryResultRow> buildColumnData(final EncryptTableRuleConfiguration tableRuleConfig, final Map<String, AlgorithmConfiguration> algorithmMap,
final boolean queryWithCipherColumn) {
Collection<LocalDataQueryResultRow> result = new LinkedList<>();
tableRuleConfig.getColumns().forEach(each -> {
for (EncryptColumnRuleConfiguration each : tableRuleConfig.getColumns()) {
AlgorithmConfiguration encryptorAlgorithmConfig = algorithmMap.get(each.getEncryptorName());
AlgorithmConfiguration assistedQueryEncryptorAlgorithmConfig = algorithmMap.get(each.getAssistedQueryEncryptorName());
AlgorithmConfiguration likeQueryEncryptorAlgorithmConfig = algorithmMap.get(each.getLikeQueryEncryptorName());
result.add(new LocalDataQueryResultRow(Arrays.asList(tableRuleConfig.getName(), each.getLogicColumn(),
result.add(new LocalDataQueryResultRow(Arrays.asList(
tableRuleConfig.getName(),
each.getLogicColumn(),
each.getCipherColumn(),
nullToEmptyString(each.getPlainColumn()),
nullToEmptyString(each.getAssistedQueryColumn()),
nullToEmptyString(each.getLikeQueryColumn()),
encryptorAlgorithmConfig.getType(), PropertiesConverter.convert(encryptorAlgorithmConfig.getProps()),
encryptorAlgorithmConfig.getType(),
PropertiesConverter.convert(encryptorAlgorithmConfig.getProps()),
Objects.isNull(assistedQueryEncryptorAlgorithmConfig) ? nullToEmptyString(null) : assistedQueryEncryptorAlgorithmConfig.getType(),
Objects.isNull(assistedQueryEncryptorAlgorithmConfig) ? nullToEmptyString(null) : PropertiesConverter.convert(assistedQueryEncryptorAlgorithmConfig.getProps()),
Objects.isNull(likeQueryEncryptorAlgorithmConfig) ? nullToEmptyString(null) : likeQueryEncryptorAlgorithmConfig.getType(),
Objects.isNull(likeQueryEncryptorAlgorithmConfig) ? nullToEmptyString(null) : PropertiesConverter.convert(likeQueryEncryptorAlgorithmConfig.getProps()),
isQueryWithCipherColumn(queryWithCipherColumn, tableRuleConfig, each).toString())));
});
}
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
Expand Down Expand Up @@ -83,22 +82,24 @@ void assertMultipleReadwriteSplittingRuleSegments() {
assertThat(actualMultipleRuleSegmentConvertResultDataSources.size(), is(expectedMultipleReadwriteSplittingRuleSegments.size()));
assertThat(actualMultipleRuleSegmentConvertResultLoadBalancers.size(), is(expectedMultipleReadwriteSplittingRuleSegments.size()));
List<ReadwriteSplittingDataSourceRuleConfiguration> actualRuleConfigs = new ArrayList<>(actualMultipleRuleSegmentConvertResultDataSources);
Stream.iterate(0, i -> i + 1)
.limit(expectedMultipleReadwriteSplittingRuleSegments.size())
.forEach(each -> {
ReadwriteSplittingRuleSegment expectedReadwriteSplittingRuleSegment = expectedMultipleReadwriteSplittingRuleSegments.get(each);
ReadwriteSplittingDataSourceRuleConfiguration actualRuleConfig = actualRuleConfigs.get(each);
assertThat(actualRuleConfig.getName(), is(expectedReadwriteSplittingRuleSegment.getName()));
String expectedLoadBalancerName = String.format("%s_%s", expectedReadwriteSplittingRuleSegment.getName(), expectedReadwriteSplittingRuleSegment.getLoadBalancer().getName());
assertThat(actualRuleConfig.getLoadBalancerName(), is(expectedLoadBalancerName));
assertThat(getWriteDataSourceName(actualRuleConfig), is(expectedReadwriteSplittingRuleSegment.getWriteDataSource()));
assertThat(getReadDataSourceNames(actualRuleConfig), is(
null == expectedReadwriteSplittingRuleSegment.getReadDataSources() ? Collections.emptyList() : expectedReadwriteSplittingRuleSegment.getReadDataSources()));
assertTrue(actualMultipleRuleSegmentConvertResultLoadBalancers.containsKey(expectedLoadBalancerName));
AlgorithmConfiguration actualSphereAlgorithmConfig = actualMultipleRuleSegmentConvertResultLoadBalancers.get(actualRuleConfig.getLoadBalancerName());
assertThat(actualSphereAlgorithmConfig.getType(), is(expectedReadwriteSplittingRuleSegment.getLoadBalancer().getName()));
assertThat(actualSphereAlgorithmConfig.getProps(), is(expectedReadwriteSplittingRuleSegment.getLoadBalancer().getProps()));
});
long limit = expectedMultipleReadwriteSplittingRuleSegments.size();
for (int i = 0;; i = i + 1) {
if (0 == limit--) {
break;
}
ReadwriteSplittingRuleSegment expectedReadwriteSplittingRuleSegment = expectedMultipleReadwriteSplittingRuleSegments.get(i);
ReadwriteSplittingDataSourceRuleConfiguration actualRuleConfig = actualRuleConfigs.get(i);
assertThat(actualRuleConfig.getName(), is(expectedReadwriteSplittingRuleSegment.getName()));
String expectedLoadBalancerName = String.format("%s_%s", expectedReadwriteSplittingRuleSegment.getName(), expectedReadwriteSplittingRuleSegment.getLoadBalancer().getName());
assertThat(actualRuleConfig.getLoadBalancerName(), is(expectedLoadBalancerName));
assertThat(getWriteDataSourceName(actualRuleConfig), is(expectedReadwriteSplittingRuleSegment.getWriteDataSource()));
assertThat(getReadDataSourceNames(actualRuleConfig),
is(null == expectedReadwriteSplittingRuleSegment.getReadDataSources() ? Collections.emptyList() : expectedReadwriteSplittingRuleSegment.getReadDataSources()));
assertTrue(actualMultipleRuleSegmentConvertResultLoadBalancers.containsKey(expectedLoadBalancerName));
AlgorithmConfiguration actualSphereAlgorithmConfig = actualMultipleRuleSegmentConvertResultLoadBalancers.get(actualRuleConfig.getLoadBalancerName());
assertThat(actualSphereAlgorithmConfig.getType(), is(expectedReadwriteSplittingRuleSegment.getLoadBalancer().getName()));
assertThat(actualSphereAlgorithmConfig.getProps(), is(expectedReadwriteSplittingRuleSegment.getLoadBalancer().getProps()));
}
}

private String getWriteDataSourceName(final ReadwriteSplittingDataSourceRuleConfiguration ruleConfig) {
Expand Down
Loading

0 comments on commit d852884

Please sign in to comment.