Skip to content

Commit

Permalink
Fill ut for common module (#11247)
Browse files Browse the repository at this point in the history
* Do some refactor and add UT for common package.

* Do some refactor and add UT for common package.

* Do some refactor and add UT for common package.

* Fix UT.
  • Loading branch information
KomachiSion authored Oct 13, 2023
1 parent 49f3486 commit c4aac2b
Show file tree
Hide file tree
Showing 59 changed files with 2,508 additions and 628 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private static class LimiterHttpClientRequestInterceptor implements HttpClientRe

@Override
public boolean isIntercept(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) {
final String body = requestHttpEntity.getBody() == null ? "" : JacksonUtils.toJson(requestHttpEntity.getBody());
final String body = requestHttpEntity.isEmptyBody() ? "" : JacksonUtils.toJson(requestHttpEntity.getBody());
return Limiter.isLimit(MD5Utils.md5Hex(uri + body, Constants.ENCODE));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,21 +102,18 @@ private void initAbilityTable() {
public void enableCurrentNodeAbility(AbilityKey abilityKey) {
Map<String, Boolean> abilities = this.currentNodeAbilities.get(abilityKey.getMode());
if (abilities != null) {
doTurn(abilities, abilityKey, true, abilityKey.getMode());
doTurn(abilities, abilityKey, true);
}
}

protected void doTurn(Map<String, Boolean> abilities, AbilityKey key, boolean turn, AbilityMode mode) {
if (!key.getMode().equals(mode)) {
throw new IllegalStateException("Except " + mode + " but " + key.getMode());
}
protected void doTurn(Map<String, Boolean> abilities, AbilityKey key, boolean turn) {
LOGGER.info("Turn current node ability: {}, turn: {}", key, turn);
abilities.put(key.getName(), turn);
// notify event
AbilityUpdateEvent abilityUpdateEvent = new AbilityUpdateEvent();
abilityUpdateEvent.setTable(Collections.unmodifiableMap(abilities));
abilityUpdateEvent.isOn = turn;
abilityUpdateEvent.abilityKey = key;
abilityUpdateEvent.setOn(turn);
abilityUpdateEvent.setAbilityKey(key);
NotifyCenter.publishEvent(abilityUpdateEvent);
}

Expand All @@ -128,7 +125,7 @@ protected void doTurn(Map<String, Boolean> abilities, AbilityKey key, boolean tu
public void disableCurrentNodeAbility(AbilityKey abilityKey) {
Map<String, Boolean> abilities = this.currentNodeAbilities.get(abilityKey.getMode());
if (abilities != null) {
doTurn(abilities, abilityKey, false, abilityKey.getMode());
doTurn(abilities, abilityKey, false);
}
}

Expand Down Expand Up @@ -180,7 +177,7 @@ public Map<String, Boolean> getCurrentNodeAbilities(AbilityMode mode) {
/**
* notify when current node ability changing.
*/
public class AbilityUpdateEvent extends Event {
public static class AbilityUpdateEvent extends Event {

private static final long serialVersionUID = -1232411212311111L;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,68 +24,65 @@
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.stream.Collectors;

/**
* This class is used to discover {@link AbstractAbilityControlManager} implements. All the
* ability operation will be finish in this singleton.
* This class is used to discover {@link AbstractAbilityControlManager} implements. All the ability operation will be
* finish in this singleton.
*
* @author Daydreamer
* @date 2022/7/14 19:58
**/
public class NacosAbilityManagerHolder {

/**.
* private constructor
/**
* . private constructor
*/
private NacosAbilityManagerHolder() {
}

private static final Logger LOGGER = LoggerFactory.getLogger(NacosAbilityManagerHolder.class);

/**.
* singleton
/**
* . singleton
*/
private static AbstractAbilityControlManager abstractAbilityControlManager;

static {
// spi discover implement
Collection<AbstractAbilityControlManager> load = null;
try {
// if server
load = NacosServiceLoader.load(AbstractAbilityControlManager.class);
} catch (ServiceConfigurationError e) {
throw new RuntimeException("[AbilityControlManager] Cannot find AbilityControlManger");
}
// the priority of the server is higher
List<AbstractAbilityControlManager> collect = load.stream()
.sorted(Comparator.comparingInt(AbstractAbilityControlManager::getPriority))
.collect(Collectors.toList());
// get the highest priority one
if (load.size() > 0) {
abstractAbilityControlManager = collect.get(collect.size() - 1);
LOGGER.info("[AbilityControlManager] Successfully initialize AbilityControlManager");
}
}

/**.
* get nacos ability control manager
/**
* . get nacos ability control manager
*
* @return BaseAbilityControlManager
*/
public static AbstractAbilityControlManager getInstance() {
public static synchronized AbstractAbilityControlManager getInstance() {
if (null == abstractAbilityControlManager) {
initAbilityControlManager();
}
return abstractAbilityControlManager;
}

/**.
* Return the target type of ability manager
/**
* . Return the target type of ability manager
*
* @param clazz clazz
* @param <T> target type
* @param <T> target type
* @return AbilityControlManager
*/
public static <T extends AbstractAbilityControlManager> T getInstance(Class<T> clazz) {
return clazz.cast(abstractAbilityControlManager);
}

private static void initAbilityControlManager() {
// spi discover implement
Collection<AbstractAbilityControlManager> load = null;
load = NacosServiceLoader.load(AbstractAbilityControlManager.class);
// the priority of the server is higher
List<AbstractAbilityControlManager> collect = load.stream()
.sorted(Comparator.comparingInt(AbstractAbilityControlManager::getPriority))
.collect(Collectors.toList());
// get the highest priority one
if (load.size() > 0) {
abstractAbilityControlManager = collect.get(collect.size() - 1);
LOGGER.info("[AbilityControlManager] Successfully initialize AbilityControlManager");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

/**
* A wrapper that automatically expires the cache.
*
* @author zzq
* @date 2021/7/30
*/
Expand All @@ -48,25 +49,26 @@ public void put(K key, V val) {

@Override
public V get(K key) {
if (keyProp.get(key) != null && isExpire(keyProp.get(key))) {
CacheItemProperties itemProperties = keyProp.get(key);
if (itemProperties != null && isExpire(itemProperties)) {
this.keyProp.remove(key);
this.delegate.remove(key);
return null;
}
return this.delegate.get(key);
}

@Override
public V get(K key, Callable<? extends V> call) throws Exception {
V cachedValue = this.get(key);
if (null == cachedValue) {
V v2 = call.call();
this.put(key, v2);
return v2;

}
return cachedValue;

}

@Override
Expand All @@ -87,9 +89,6 @@ public int getSize() {
}

private boolean isExpire(CacheItemProperties itemProperties) {
if (itemProperties == null) {
return true;
}
return expireNanos != -1 && (System.nanoTime() - itemProperties.getExpireNanos() > expireNanos);
}

Expand Down
62 changes: 8 additions & 54 deletions common/src/main/java/com/alibaba/nacos/common/codec/Base64.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@

package com.alibaba.nacos.common.codec;

import java.nio.charset.StandardCharsets;

/**
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
* From apache common codec, and remove some useless method. Provides Base64 encoding and decoding as defined by <a
* href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*
* <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045
*
Expand Down Expand Up @@ -168,28 +167,16 @@ public Base64() {
* work!
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
chunkSeparatorLength = lineSeparator == null ? 0 : lineSeparator.length;
private Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
chunkSeparatorLength = lineSeparator.length;
unencodedBlockSize = BYTES_PER_UNENCODED_BLOCK;
encodedBlockSize = BYTES_PER_ENCODED_BLOCK;
this.lineLength =
(lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
// TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
// @see test case Base64Test.testConstructors()
if (lineSeparator != null) {
if (containsAlphabetOrPad(lineSeparator)) {
String sep = null;
sep = new String(lineSeparator, StandardCharsets.UTF_8);
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
}
if (lineLength > 0) {
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
} else {
this.encodeSize = BYTES_PER_ENCODED_BLOCK;
this.lineSeparator = null;
}
if (lineLength > 0) {
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
} else {
this.encodeSize = BYTES_PER_ENCODED_BLOCK;
this.lineSeparator = null;
Expand All @@ -206,9 +193,6 @@ public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
*/
private byte[] encode(byte[] pArray) {
reset();
if (pArray == null || pArray.length == 0) {
return pArray;
}
encode(pArray, 0, pArray.length);
encode(pArray, 0, -1);
byte[] buf = new byte[pos - readPos];
Expand Down Expand Up @@ -431,16 +415,6 @@ public static byte[] decodeBase64(byte[] base64Data) {
return new Base64().decode(base64Data);
}

/**
* Returns whether or not the <code>octet</code> is in the Base32 alphabet.
*
* @param octet The value to test
* @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> otherwise.
*/
protected boolean isInAlphabet(byte octet) {
return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
}

/**
* MIME chunk size per RFC 2045 section 6.8.
*
Expand Down Expand Up @@ -578,26 +552,6 @@ private void reset() {
eof = false;
}

/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* <p>Intended for use in checking line-ending arrays
*
* @param arrayOctet byte array to test
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
*/
private boolean containsAlphabetOrPad(byte[] arrayOctet) {
if (arrayOctet == null) {
return false;
}
for (int i = 0; i < arrayOctet.length; i++) {
if (PAD == arrayOctet[i] || isInAlphabet(arrayOctet[i])) {
return true;
}
}
return false;
}

/**
* Calculates the amount of space needed to encode the supplied array.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public RequestHttpEntity(Header header, Query query) {
}

public RequestHttpEntity(Header header, Object body) {
this(null, header, null, body);
this(null, header, body);
}

public RequestHttpEntity(Header header, Query query, Object body) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
/**
* Rest result.
*
* <p>TODO replaced or extend by {@link com.alibaba.nacos.api.model.v2.Result}.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class RestResult<T> implements Serializable {
Expand All @@ -42,16 +44,6 @@ public RestResult(int code, String message, T data) {
this.data = data;
}

public RestResult(int code, T data) {
this.code = code;
this.data = data;
}

public RestResult(int code, String message) {
this.code = code;
this.setMessage(message);
}

public int getCode() {
return code;
}
Expand Down Expand Up @@ -114,7 +106,7 @@ public ResResultBuilder<T> withData(T data) {
this.data = data;
return this;
}

/**
* Build result.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ public void init(Class<? extends Event> type, int bufferSize) {
setName("nacos.publisher-" + type.getName());
this.eventType = type;
this.queueMaxSize = bufferSize;
this.queue = new ArrayBlockingQueue<>(bufferSize);
if (this.queueMaxSize == -1) {
this.queueMaxSize = ringBufferSize;
}
this.queue = new ArrayBlockingQueue<>(this.queueMaxSize);
start();
}

Expand All @@ -78,9 +81,6 @@ public synchronized void start() {
if (!initialized) {
// start just called once
super.start();
if (queueMaxSize == -1) {
queueMaxSize = ringBufferSize;
}
initialized = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,13 @@ public static Map<String, EventPublisher> getPublisherMap() {
return INSTANCE.publisherMap;
}

@JustForTest
public static EventPublisher getPublisher(Class<? extends Event> topic) {
if (ClassUtils.isAssignableFrom(SlowEvent.class, topic)) {
return INSTANCE.sharePublisher;
}
return INSTANCE.publisherMap.get(topic.getCanonicalName());
}

@JustForTest
public static EventPublisher getSharePublisher() {
return INSTANCE.sharePublisher;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,8 @@ public <T> Set<Class<T>> getTypesAnnotatedWith(String pkg, Class<? extends Annot
set.add((Class<T>) scanClass);
}
}
} catch (IOException e) {
} catch (IOException | ClassNotFoundException e) {
LOGGER.error("scan path: {} failed", packageSearchPath, e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return set;
}
Expand Down
Loading

0 comments on commit c4aac2b

Please sign in to comment.