diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml
index e6edb1a1f..0bbaba8d5 100644
--- a/.github/workflows/maven-build.yml
+++ b/.github/workflows/maven-build.yml
@@ -22,21 +22,21 @@ jobs:
java: [ '8', '11' , '17' , '21' , '25' ]
steps:
- name: Checkout Source
- uses: actions/checkout@v4
+ uses: actions/checkout@v5
- name: Setup JDK ${{ matrix.Java }}
- uses: actions/setup-java@v4
+ uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
- cache: maven
- name: Build with Maven
- run: mvn
+ run: ./mvnw
--batch-mode
--update-snapshots
--file pom.xml
-Drevision=0.0.1-SNAPSHOT
+ -Dsurefire.useSystemClassLoader=false
test
--activate-profiles test,coverage
diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml
index 6d40bcd43..61db0dc6d 100644
--- a/.github/workflows/maven-publish.yml
+++ b/.github/workflows/maven-publish.yml
@@ -24,10 +24,10 @@ jobs:
if: ${{ inputs.revision }}
steps:
- name: Checkout Source
- uses: actions/checkout@v4
+ uses: actions/checkout@v5
- name: Setup Maven Central Repository
- uses: actions/setup-java@v4
+ uses: actions/setup-java@v5
with:
java-version: '11'
distribution: 'temurin'
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
deleted file mode 100755
index bf82ff01c..000000000
Binary files a/.mvn/wrapper/maven-wrapper.jar and /dev/null differ
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
index d83cf1363..423c23e5e 100644
--- a/.mvn/wrapper/maven-wrapper.properties
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -1,16 +1,3 @@
-# Copyright 2013-2023 the original author or authors.
-#
-# 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
-#
-# https://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.
-
-distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.0/apache-maven-3.9.0-bin.zip
-wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
\ No newline at end of file
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://maven.aliyun.com/repository/public/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
diff --git a/microsphere-annotation-processor/pom.xml b/microsphere-annotation-processor/pom.xml
index 0af57d196..26473f3d3 100644
--- a/microsphere-annotation-processor/pom.xml
+++ b/microsphere-annotation-processor/pom.xml
@@ -18,11 +18,6 @@
Microsphere :: Java :: Annotation ProcessorMicrosphere Annotation Processor
-
- 2.1
- 2.3.1
-
-
@@ -32,6 +27,13 @@
${revision}
+
+
+ io.github.microsphere-projects
+ microsphere-lang-model
+ ${revision}
+
+
org.junit.jupiter
@@ -45,6 +47,22 @@
test
+
+
+ io.github.microsphere-projects
+ microsphere-jdk-tools
+ ${revision}
+ test
+
+
+
+
+ io.github.microsphere-projects
+ microsphere-java-test
+ ${revision}
+ test
+
+
ch.qos.logback
@@ -56,7 +74,6 @@
javax.ws.rsjavax.ws.rs-api
- ${javax.ws.rs.version}test
@@ -64,7 +81,6 @@
javax.xml.wsjaxws-api
- ${jaxws-api.version}test
diff --git a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessor.java b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessor.java
index 547c702a2..4523a1e42 100644
--- a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessor.java
+++ b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessor.java
@@ -18,7 +18,7 @@
package io.microsphere.annotation.processor;
import io.microsphere.annotation.ConfigurationProperty;
-import io.microsphere.annotation.processor.model.util.ConfigurationPropertyJSONElementVisitor;
+import io.microsphere.constants.ResourceConstants;
import io.microsphere.json.JSONArray;
import io.microsphere.metadata.ConfigurationPropertyGenerator;
@@ -35,12 +35,12 @@
import java.util.List;
import java.util.Set;
-import static io.microsphere.annotation.processor.model.util.ConfigurationPropertyJSONElementVisitor.CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printNote;
+import static io.microsphere.annotation.processor.ConfigurationPropertyJSONElementVisitor.CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME;
import static io.microsphere.constants.ResourceConstants.CONFIGURATION_PROPERTY_METADATA_RESOURCE;
import static io.microsphere.constants.SymbolConstants.COMMA_CHAR;
import static io.microsphere.constants.SymbolConstants.LEFT_SQUARE_BRACKET_CHAR;
import static io.microsphere.constants.SymbolConstants.RIGHT_SQUARE_BRACKET_CHAR;
+import static io.microsphere.lang.model.util.MessagerUtils.printNote;
import static io.microsphere.metadata.ConfigurationPropertyLoader.loadAll;
import static javax.lang.model.SourceVersion.latestSupported;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
@@ -62,7 +62,7 @@
*
*
{@link #resolveMetadata(RoundEnvironment)} traverses all root elements to extract configuration property metadata.
*
{@link #writeMetadata()} writes the generated metadata into a JSON file under
- * {@value #CONFIGURATION_PROPERTY_METADATA_RESOURCE_NAME} using a writer.
+ * {@value ResourceConstants#CONFIGURATION_PROPERTY_METADATA_RESOURCE} using a writer.
*
*
* @author Mercy
@@ -106,24 +106,28 @@ public boolean process(Set extends TypeElement> annotations, RoundEnvironment
private void resolveMetadata(RoundEnvironment roundEnv) {
Set extends Element> elements = roundEnv.getRootElements();
- if (!elements.isEmpty()) {
+ resolveMetadata(elements);
+ }
+
+ void resolveMetadata(Set extends Element> elements) {
+ jsonBuilder.append(LEFT_SQUARE_BRACKET_CHAR);
+ // Resolve the content
+ if (!elements.isEmpty()) {
Iterator extends Element> iterator = elements.iterator();
- jsonBuilder.append(LEFT_SQUARE_BRACKET_CHAR);
while (iterator.hasNext()) {
Element element = iterator.next();
element.accept(jsonElementVisitor, jsonBuilder);
}
-
// append the JSON content generated by ConfigurationPropertyGenerator SPI
appendGeneratedConfigurationPropertyJSON(jsonBuilder);
+ }
- int lastIndex = jsonBuilder.length() - 1;
- if (COMMA_CHAR == jsonBuilder.charAt(lastIndex)) {
- jsonBuilder.setCharAt(lastIndex, RIGHT_SQUARE_BRACKET_CHAR);
- } else {
- jsonBuilder.append(RIGHT_SQUARE_BRACKET_CHAR);
- }
+ int lastIndex = jsonBuilder.length() - 1;
+ if (COMMA_CHAR == jsonBuilder.charAt(lastIndex)) {
+ jsonBuilder.setCharAt(lastIndex, RIGHT_SQUARE_BRACKET_CHAR);
+ } else {
+ jsonBuilder.append(RIGHT_SQUARE_BRACKET_CHAR);
}
}
@@ -151,9 +155,12 @@ private void writeMetadata() {
});
}
+ String toJSON() {
+ return jsonBuilder.toString();
+ }
+
@Override
public SourceVersion getSupportedSourceVersion() {
return latestSupported();
}
}
-
\ No newline at end of file
diff --git a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/model/util/ConfigurationPropertyJSONElementVisitor.java b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitor.java
similarity index 79%
rename from microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/model/util/ConfigurationPropertyJSONElementVisitor.java
rename to microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitor.java
index 963392408..e30972026 100644
--- a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/model/util/ConfigurationPropertyJSONElementVisitor.java
+++ b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitor.java
@@ -15,10 +15,11 @@
* limitations under the License.
*/
-package io.microsphere.annotation.processor.model.util;
+package io.microsphere.annotation.processor;
import io.microsphere.annotation.ConfigurationProperty;
import io.microsphere.beans.ConfigurationProperty.Metadata;
+import io.microsphere.lang.model.util.AnnotatedElementJSONElementVisitor;
import io.microsphere.metadata.ConfigurationPropertyGenerator;
import javax.annotation.processing.ProcessingEnvironment;
@@ -26,18 +27,19 @@
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.util.List;
import java.util.Map;
-import static io.microsphere.annotation.processor.util.AnnotationUtils.getAnnotation;
-import static io.microsphere.annotation.processor.util.AnnotationUtils.getAttributeName;
-import static io.microsphere.annotation.processor.util.AnnotationUtils.getElementValues;
-import static io.microsphere.annotation.processor.util.AnnotationUtils.matchesDefaultAttributeValue;
-import static io.microsphere.annotation.processor.util.ClassUtils.getClassName;
-import static io.microsphere.annotation.processor.util.TypeUtils.getTypeName;
import static io.microsphere.constants.SymbolConstants.COMMA_CHAR;
+import static io.microsphere.lang.model.util.AnnotationUtils.getAnnotation;
+import static io.microsphere.lang.model.util.AnnotationUtils.getAttributeName;
+import static io.microsphere.lang.model.util.AnnotationUtils.getElementValues;
+import static io.microsphere.lang.model.util.AnnotationUtils.matchesDefaultAttributeValue;
+import static io.microsphere.lang.model.util.ClassUtils.getClassName;
+import static io.microsphere.lang.model.util.TypeUtils.getTypeName;
import static io.microsphere.util.ServiceLoaderUtils.loadFirstService;
import static io.microsphere.util.StringUtils.isBlank;
@@ -51,13 +53,13 @@
* @see io.microsphere.beans.ConfigurationProperty
* @since 1.0.0
*/
-public class ConfigurationPropertyJSONElementVisitor extends AnnotatedElementJSONElementVisitor {
+class ConfigurationPropertyJSONElementVisitor extends AnnotatedElementJSONElementVisitor {
- public static final String CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME = "io.microsphere.annotation.ConfigurationProperty";
+ static final String CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME = "io.microsphere.annotation.ConfigurationProperty";
private final ConfigurationPropertyGenerator generator;
- public ConfigurationPropertyJSONElementVisitor(ProcessingEnvironment processingEnv) {
+ ConfigurationPropertyJSONElementVisitor(ProcessingEnvironment processingEnv) {
super(processingEnv, CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME);
this.generator = loadFirstService(ConfigurationPropertyGenerator.class);
}
@@ -87,8 +89,8 @@ public Boolean visitVariableAsField(VariableElement field, StringBuilder jsonBui
} else if ("description".equals(attributeName)) {
String description = resolveDescription(field, attributeMethod, annotationValue);
configurationProperty.setDescription(description);
- } else if ("source".equals(attributeName)) {
- setSources(configurationProperty, annotationValue);
+ } else {
+ setSources(configurationProperty, attributeName, annotationValue);
}
}
setDeclaredClass(configurationProperty, field);
@@ -102,6 +104,11 @@ public Boolean visitVariableAsField(VariableElement field, StringBuilder jsonBui
return false;
}
+ @Override
+ protected boolean supportsType(TypeElement e) {
+ return true;
+ }
+
public ConfigurationPropertyGenerator getGenerator() {
return generator;
}
@@ -130,12 +137,14 @@ private String resolveStringValue(ExecutableElement attributeMethod, AnnotationV
return (String) value;
}
- private void setSources(io.microsphere.beans.ConfigurationProperty configurationProperty, AnnotationValue annotationValue) {
- List extends AnnotationValue> sources = (List extends AnnotationValue>) annotationValue.getValue();
- Metadata metadata = configurationProperty.getMetadata();
- for (AnnotationValue source : sources) {
- String sourceValue = (String) source.getValue();
- metadata.getSources().add(sourceValue);
+ void setSources(io.microsphere.beans.ConfigurationProperty configurationProperty, String attributeName, AnnotationValue annotationValue) {
+ if ("source".equals(attributeName)) {
+ List extends AnnotationValue> sources = (List extends AnnotationValue>) annotationValue.getValue();
+ Metadata metadata = configurationProperty.getMetadata();
+ for (AnnotationValue source : sources) {
+ String sourceValue = (String) source.getValue();
+ metadata.getSources().add(sourceValue);
+ }
}
}
@@ -149,5 +158,4 @@ private void setDeclaredField(io.microsphere.beans.ConfigurationProperty configu
String declaredFieldName = field.getSimpleName().toString();
configurationProperty.getMetadata().setDeclaredField(declaredFieldName);
}
-
-}
+}
\ No newline at end of file
diff --git a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/FilerProcessor.java b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/FilerProcessor.java
index 36d1416b4..5a34c0fa5 100644
--- a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/FilerProcessor.java
+++ b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/FilerProcessor.java
@@ -24,7 +24,7 @@
import javax.tools.JavaFileManager;
import java.util.function.BiFunction;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printMandatoryWarning;
+import static io.microsphere.lang.model.util.MessagerUtils.printMandatoryWarning;
import static io.microsphere.reflect.FieldUtils.getFieldValue;
/**
diff --git a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ResourceProcessor.java b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ResourceProcessor.java
index ab7b0c883..71852e810 100644
--- a/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ResourceProcessor.java
+++ b/microsphere-annotation-processor/src/main/java/io/microsphere/annotation/processor/ResourceProcessor.java
@@ -34,8 +34,8 @@
import java.util.function.BiFunction;
import java.util.function.Function;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printNote;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printWarning;
+import static io.microsphere.lang.model.util.MessagerUtils.printNote;
+import static io.microsphere.lang.model.util.MessagerUtils.printWarning;
import static io.microsphere.util.ExceptionUtils.wrap;
import static java.util.Optional.empty;
import static java.util.Optional.of;
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessorTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessorTest.java
index 82693aa0f..2e2806fa0 100644
--- a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessorTest.java
+++ b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyAnnotationProcessorTest.java
@@ -17,19 +17,11 @@
package io.microsphere.annotation.processor;
-import io.microsphere.annotation.ConfigurationProperty;
-import io.microsphere.classloading.ManifestArtifactResourceResolver;
-import io.microsphere.io.IOUtils;
-import io.microsphere.io.StandardFileWatchService;
-import io.microsphere.reflect.MethodUtils;
-import io.microsphere.reflect.TypeUtils;
-import io.microsphere.util.ServiceLoaderUtils;
+import io.microsphere.test.annotation.processing.AbstractAnnotationProcessingTest;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
-import static io.microsphere.annotation.processor.model.util.ConfigurationPropertyJSONElementVisitor.CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import static io.microsphere.util.Assert.assertNotNull;
+import static java.util.Collections.emptySet;
/**
* {@link ConfigurationPropertyAnnotationProcessor} Test
@@ -40,24 +32,12 @@
*/
class ConfigurationPropertyAnnotationProcessorTest extends AbstractAnnotationProcessingTest {
- @Override
- protected void beforeTest() {
- super.beforeTest();
- }
-
- @Override
- protected void addCompiledClasses(Set> compiledClasses) {
- compiledClasses.add(ManifestArtifactResourceResolver.class);
- compiledClasses.add(IOUtils.class);
- compiledClasses.add(StandardFileWatchService.class);
- compiledClasses.add(TypeUtils.class);
- compiledClasses.add(ServiceLoaderUtils.class);
- compiledClasses.add(MethodUtils.class);
- compiledClasses.add(ConfigurationProperty.class);
- }
-
@Test
- void testConstants() {
- assertEquals("io.microsphere.annotation.ConfigurationProperty", CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME);
+ void testResolveMetadataOnEmptySet() {
+ ConfigurationPropertyAnnotationProcessor processor = new ConfigurationPropertyAnnotationProcessor();
+ processor.init(super.processingEnv);
+ processor.resolveMetadata(emptySet());
+ String json = processor.toJSON();
+ assertNotNull("[]", json);
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitorTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitorTest.java
new file mode 100644
index 000000000..89e4e5deb
--- /dev/null
+++ b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ConfigurationPropertyJSONElementVisitorTest.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 io.microsphere.annotation.processor;
+
+
+import io.microsphere.annotation.ConfigurationProperty;
+import io.microsphere.classloading.ManifestArtifactResourceResolver;
+import io.microsphere.io.IOUtils;
+import io.microsphere.io.StandardFileWatchService;
+import io.microsphere.reflect.MethodUtils;
+import io.microsphere.reflect.TypeUtils;
+import io.microsphere.test.annotation.processing.AbstractAnnotationProcessingTest;
+import io.microsphere.util.ServiceLoaderUtils;
+import org.junit.jupiter.api.Test;
+
+import java.util.Set;
+
+import static io.microsphere.annotation.processor.ConfigurationPropertyJSONElementVisitor.CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * {@link ConfigurationPropertyJSONElementVisitor} Test
+ *
+ * @author Mercy
+ * @see ConfigurationPropertyJSONElementVisitor
+ * @since 1.0.0
+ */
+class ConfigurationPropertyJSONElementVisitorTest extends AbstractAnnotationProcessingTest {
+
+ @Override
+ protected void addCompiledClasses(Set> compiledClasses) {
+ compiledClasses.add(ManifestArtifactResourceResolver.class);
+ compiledClasses.add(IOUtils.class);
+ compiledClasses.add(StandardFileWatchService.class);
+ compiledClasses.add(TypeUtils.class);
+ compiledClasses.add(ServiceLoaderUtils.class);
+ compiledClasses.add(MethodUtils.class);
+ compiledClasses.add(ConfigurationProperty.class);
+ }
+
+ @Test
+ void testConstants() {
+ assertEquals("io.microsphere.annotation.ConfigurationProperty", CONFIGURATION_PROPERTY_ANNOTATION_CLASS_NAME);
+ }
+
+ @Test
+ void testSupportsType() {
+ ConfigurationPropertyJSONElementVisitor visitor = new ConfigurationPropertyJSONElementVisitor(super.processingEnv);
+ assertTrue(visitor.supportsType(super.testTypeElement));
+ assertTrue(visitor.supportsType(NULL_TYPE_ELEMENT));
+ }
+
+ @Test
+ void testSetSourcesOnNoSource() {
+ ConfigurationPropertyJSONElementVisitor visitor = new ConfigurationPropertyJSONElementVisitor(super.processingEnv);
+ visitor.setSources(null, "noSource", null);
+ assertNotNull(visitor);
+ }
+}
\ No newline at end of file
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/FilerProcessorTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/FilerProcessorTest.java
index 47588edde..8f715df0f 100644
--- a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/FilerProcessorTest.java
+++ b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/FilerProcessorTest.java
@@ -18,10 +18,14 @@
package io.microsphere.annotation.processor;
+import io.microsphere.test.annotation.processing.AbstractAnnotationProcessingTest;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
+import java.lang.reflect.Method;
import static io.microsphere.annotation.processor.ResourceProcessor.exists;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -40,7 +44,7 @@ class FilerProcessorTest extends AbstractAnnotationProcessingTest {
private FilerProcessor processor;
@Override
- protected void beforeTest() {
+ protected void beforeTest(ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) {
this.processor = new FilerProcessor(super.processingEnv);
}
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ResourceProcessorTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ResourceProcessorTest.java
index 35ad93340..1ed22a16d 100644
--- a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ResourceProcessorTest.java
+++ b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/ResourceProcessorTest.java
@@ -18,9 +18,13 @@
package io.microsphere.annotation.processor;
+import io.microsphere.test.annotation.processing.AbstractAnnotationProcessingTest;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import javax.tools.FileObject;
+import java.lang.reflect.Method;
import java.util.Optional;
import static io.microsphere.annotation.processor.ResourceProcessor.FOR_READING;
@@ -30,11 +34,14 @@
import static io.microsphere.nio.charset.CharsetUtils.DEFAULT_CHARSET;
import static java.lang.Boolean.FALSE;
import static java.lang.System.currentTimeMillis;
+import static java.util.Optional.empty;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
import static javax.tools.StandardLocation.SOURCE_PATH;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -56,14 +63,14 @@ class ResourceProcessorTest extends AbstractAnnotationProcessingTest {
private String randomResourceName;
@Override
- protected void beforeTest() {
+ protected void beforeTest(ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) {
this.classOutputProcessor = new ResourceProcessor(super.processingEnv, CLASS_OUTPUT);
this.sourcePathProcessor = new ResourceProcessor(super.processingEnv, SOURCE_PATH);
this.randomResourceName = "test/" + currentTimeMillis() + ".txt";
}
@Override
- protected void afterTest() {
+ protected void afterTest(ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext, Object result, Throwable failure) {
this.classOutputProcessor.getResource(this.randomResourceName, FOR_WRITING).ifPresent(FileObject::delete);
}
@@ -77,6 +84,10 @@ void testProcessInResourceOnFailed() {
assertThrows(RuntimeException.class, () -> this.classOutputProcessor.processInResource(this.randomResourceName, FOR_READING, fileObject -> {
throw new RuntimeException();
}));
+
+ assertNull(this.classOutputProcessor.processInResource(this.randomResourceName, FOR_READING, fileObject -> {
+ throw new RuntimeException();
+ }, e -> null));
}
@Test
@@ -97,6 +108,10 @@ void testProcessInResourceInputStreamOnFailed() {
assertThrows(RuntimeException.class, () -> this.sourcePathProcessor.processInResourceInputStream(JAVA_SOURCE_RESOURCE_NAME, inputStream -> {
throw new RuntimeException();
}));
+
+ assertSame(empty(), this.sourcePathProcessor.processInResourceInputStream(JAVA_SOURCE_RESOURCE_NAME, inputStream -> {
+ throw new RuntimeException();
+ }, (f, e) -> null));
}
@Test
@@ -111,6 +126,10 @@ void testProcessInResourceReaderOnFailed() {
assertThrows(RuntimeException.class, () -> this.sourcePathProcessor.processInResourceReader(JAVA_SOURCE_RESOURCE_NAME, reader -> {
throw new RuntimeException();
}));
+
+ assertSame(empty(), this.sourcePathProcessor.processInResourceReader(JAVA_SOURCE_RESOURCE_NAME, reader -> {
+ throw new RuntimeException();
+ }, (f, e) -> null));
}
@Test
@@ -124,6 +143,10 @@ void testProcessInResourceContentOnFailed() {
assertThrows(RuntimeException.class, () -> this.sourcePathProcessor.processInResourceContent(JAVA_SOURCE_RESOURCE_NAME, content -> {
throw new RuntimeException();
}));
+
+ assertSame(empty(), this.sourcePathProcessor.processInResourceContent(JAVA_SOURCE_RESOURCE_NAME, content -> {
+ throw new RuntimeException();
+ }, (f, e) -> null));
}
@Test
@@ -138,6 +161,12 @@ void testProcessInResourceOutputStreamOnFailed() {
assertThrows(RuntimeException.class, () -> this.classOutputProcessor.processInResourceOutputStream(this.randomResourceName, outputStream -> {
throw new RuntimeException();
}));
+
+ this.classOutputProcessor.processInResourceOutputStream(this.randomResourceName, outputStream -> {
+ throw new RuntimeException();
+ }, (f, e) -> {
+ assertNotNull(e);
+ });
}
@Test
@@ -152,6 +181,12 @@ void testProcessInResourceOnWriterOnFailed() {
assertThrows(RuntimeException.class, () -> this.classOutputProcessor.processInResourceWriter(randomResourceName, writer -> {
throw new RuntimeException();
}));
+
+ this.classOutputProcessor.processInResourceWriter(this.randomResourceName, writer -> {
+ throw new RuntimeException();
+ }, (f, e) -> {
+ assertNotNull(e);
+ });
}
@Test
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/LoggerUtilsTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/LoggerUtilsTest.java
deleted file mode 100644
index dd436fae9..000000000
--- a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/LoggerUtilsTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 io.microsphere.annotation.processor.util;
-
-import org.junit.jupiter.api.Test;
-
-import static io.microsphere.annotation.processor.util.LoggerUtils.LOGGER;
-import static io.microsphere.annotation.processor.util.LoggerUtils.debug;
-import static io.microsphere.annotation.processor.util.LoggerUtils.error;
-import static io.microsphere.annotation.processor.util.LoggerUtils.info;
-import static io.microsphere.annotation.processor.util.LoggerUtils.trace;
-import static io.microsphere.annotation.processor.util.LoggerUtils.warn;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-/**
- * {@link LoggerUtils} Test
- *
- * @author Mercy
- * @since 1.0.0
- */
-class LoggerUtilsTest {
-
- @Test
- void testLogger() {
- assertNotNull(LOGGER);
- }
-
- @Test
- void testTrace() {
- trace("Hello,World");
- trace("Hello,{}", "World");
- trace("{},{}", "Hello", "World");
- }
-
- @Test
- void testDebug() {
- debug("Hello,World");
- debug("Hello,{}", "World");
- debug("{},{}", "Hello", "World");
- }
-
- @Test
- void testInfo() {
- info("Hello,World");
- info("Hello,{}", "World");
- info("{},{}", "Hello", "World");
- }
-
- @Test
- void testWarn() {
- warn("Hello,World");
- warn("Hello,{}", "World");
- warn("{},{}", "Hello", "World");
- }
-
- @Test
- void testError() {
- error("Hello,World");
- error("Hello,{}", "World");
- error("{},{}", "Hello", "World");
- }
-}
diff --git a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/MessagerUtilsTest.java b/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/MessagerUtilsTest.java
deleted file mode 100644
index 9e7d629ae..000000000
--- a/microsphere-annotation-processor/src/test/java/io/microsphere/annotation/processor/util/MessagerUtilsTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 io.microsphere.annotation.processor.util;
-
-
-import io.microsphere.annotation.processor.AbstractAnnotationProcessingTest;
-import org.junit.jupiter.api.Test;
-
-import javax.annotation.processing.Messager;
-
-import static io.microsphere.annotation.processor.util.MessagerUtils.printError;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printMandatoryWarning;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printMessage;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printNote;
-import static io.microsphere.annotation.processor.util.MessagerUtils.printWarning;
-import static javax.tools.Diagnostic.Kind.OTHER;
-
-/**
- * {@link MessagerUtils} Test
- *
- * @author Mercy
- * @see MessagerUtils
- * @see Messager
- * @since 1.0.0
- */
-class MessagerUtilsTest extends AbstractAnnotationProcessingTest {
-
- private Messager messager;
-
- @Override
- protected void beforeTest() {
- this.messager = this.processingEnv.getMessager();
- }
-
- @Test
- void testPrintNote() {
- printNote(this.processingEnv, "Hello, {}!", "printNote");
- printNote(this.messager, "Hello, {}!", "printNote");
- }
-
- @Test
- void testPrintWarning() {
- printWarning(this.processingEnv, "Hello, {}!", "printWarning");
- printWarning(this.messager, "Hello, {}!", "printWarning");
- }
-
- @Test
- void testPrintMandatoryWarning() {
- printMandatoryWarning(this.processingEnv, "Hello, {}!", "printMandatoryWarning");
- printMandatoryWarning(this.messager, "Hello, {}!", "printMandatoryWarning");
- }
-
- @Test
- void testPrintError() {
- printError(this.processingEnv, "Hello, {}!", "printError");
- printError(this.messager, "Hello, {}!", "printError");
- }
-
- @Test
- void testPrintMessage() {
- printMessage(this.processingEnv, OTHER, "Hello, {}!", "printMessage");
- printMessage(this.messager, OTHER, "Hello, {}!", "printMessage");
- }
-}
\ No newline at end of file
diff --git a/microsphere-java-annotations/pom.xml b/microsphere-java-annotations/pom.xml
new file mode 100644
index 000000000..e80e54ea5
--- /dev/null
+++ b/microsphere-java-annotations/pom.xml
@@ -0,0 +1,44 @@
+
+
+
+ io.github.microsphere-projects
+ microsphere-java-parent
+ ${revision}
+ ../microsphere-java-parent/pom.xml
+
+ 4.0.0
+
+ io.github.microsphere-projects
+ microsphere-java-annotations
+ ${revision}
+ jar
+
+ Microsphere :: Java :: Annotations
+ Microsphere Java Annotations
+
+
+
+
+
+ com.google.code.findbugs
+ jsr305
+ true
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
+
+
+
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/ConfigurationProperty.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/ConfigurationProperty.java
similarity index 99%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/ConfigurationProperty.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/ConfigurationProperty.java
index dd6272f95..10203087e 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/ConfigurationProperty.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/ConfigurationProperty.java
@@ -94,4 +94,4 @@
*/
String[] source() default {};
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/Experimental.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Experimental.java
similarity index 99%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/Experimental.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/Experimental.java
index 498df0028..e3780f909 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/Experimental.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Experimental.java
@@ -49,4 +49,4 @@
*/
String description() default "";
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/Immutable.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Immutable.java
similarity index 99%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/Immutable.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/Immutable.java
index 593118b5e..0ae81044f 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/Immutable.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Immutable.java
@@ -31,4 +31,4 @@
@Documented
@Retention(RUNTIME)
public @interface Immutable {
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/Nonnull.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nonnull.java
similarity index 99%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/Nonnull.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nonnull.java
index 859ec90a4..0a36bb87a 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/Nonnull.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nonnull.java
@@ -35,4 +35,4 @@
@javax.annotation.Nonnull
@TypeQualifierNickname
public @interface Nonnull {
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/Nullable.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nullable.java
similarity index 99%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/Nullable.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nullable.java
index c3a3a49e0..9b708f889 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/Nullable.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Nullable.java
@@ -36,4 +36,4 @@
@javax.annotation.Nonnull(when = MAYBE)
@TypeQualifierNickname
public @interface Nullable {
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/annotation/Since.java b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Since.java
similarity index 96%
rename from microsphere-java-core/src/main/java/io/microsphere/annotation/Since.java
rename to microsphere-java-annotations/src/main/java/io/microsphere/annotation/Since.java
index bb840ccbc..c2ec0c22d 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/annotation/Since.java
+++ b/microsphere-java-annotations/src/main/java/io/microsphere/annotation/Since.java
@@ -16,8 +16,6 @@
*/
package io.microsphere.annotation;
-import io.microsphere.util.Version;
-
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@@ -38,7 +36,6 @@
* The annotation that indicates the API is introduced in the first time.
*
* @author Mercy
- * @see Version
* @see Experimental
* @since 1.0.0
*/
@@ -65,7 +62,7 @@
/**
* @return The version value of the API, e.g. 1.0.0
- * @see Version
*/
String value();
-}
+
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java
similarity index 96%
rename from microsphere-java-core/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java
rename to microsphere-java-annotations/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java
index 54c7d50c6..c31732d3a 100644
--- a/microsphere-java-core/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ConfigurationPropertyTest.java
@@ -25,7 +25,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
- * {@link ConfigurationProperty} Test
+ * {@link ConfigurationProperty @ConfigurationProperty} Test
*
* @author Mercy
* @see ConfigurationProperty
diff --git a/microsphere-java-core/src/test/java/io/microsphere/annotation/ExperimentalTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ExperimentalTest.java
similarity index 96%
rename from microsphere-java-core/src/test/java/io/microsphere/annotation/ExperimentalTest.java
rename to microsphere-java-annotations/src/test/java/io/microsphere/annotation/ExperimentalTest.java
index 9014ea8a9..d4db9a409 100644
--- a/microsphere-java-core/src/test/java/io/microsphere/annotation/ExperimentalTest.java
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ExperimentalTest.java
@@ -21,7 +21,7 @@
import static org.junit.jupiter.api.Assertions.assertNull;
/**
- * {@link Experimental} Test
+ * {@link Experimental @Experimental} Test
*
* @author Mercy
* @see Experimental
diff --git a/microsphere-java-core/src/test/java/io/microsphere/annotation/ImmutableTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ImmutableTest.java
similarity index 96%
rename from microsphere-java-core/src/test/java/io/microsphere/annotation/ImmutableTest.java
rename to microsphere-java-annotations/src/test/java/io/microsphere/annotation/ImmutableTest.java
index 5d871cf1d..6ae1ffb79 100644
--- a/microsphere-java-core/src/test/java/io/microsphere/annotation/ImmutableTest.java
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/ImmutableTest.java
@@ -22,7 +22,7 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
- * {@link Immutable} Test
+ * {@link Immutable @Immutable} Test
*
* @author Mercy
* @see Immutable
diff --git a/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NonnullTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NonnullTest.java
new file mode 100644
index 000000000..cea51bd42
--- /dev/null
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NonnullTest.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 io.microsphere.annotation;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * {@link Nonnull @Nonnull} Test
+ *
+ * @author Mercy
+ * @see Nonnull
+ * @since 1.0.0
+ */
+@Nonnull
+class NonnullTest {
+
+ @Test
+ void test() {
+ assertNotNull(NonnullTest.class.getAnnotation(Nonnull.class));
+ }
+}
\ No newline at end of file
diff --git a/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NullableTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NullableTest.java
new file mode 100644
index 000000000..25a6625fe
--- /dev/null
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/NullableTest.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 io.microsphere.annotation;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * {@link Nullable @Nullable} Test
+ *
+ * @author Mercy
+ * @see Nullable
+ * @since 1.0.0
+ */
+@Nullable
+class NullableTest {
+
+ @Test
+ void test() {
+ assertNotNull(NullableTest.class.getAnnotation(Nullable.class));
+ }
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/test/java/io/microsphere/annotation/SinceTest.java b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/SinceTest.java
similarity index 99%
rename from microsphere-java-core/src/test/java/io/microsphere/annotation/SinceTest.java
rename to microsphere-java-annotations/src/test/java/io/microsphere/annotation/SinceTest.java
index 1ecca38c8..1e6314b95 100644
--- a/microsphere-java-core/src/test/java/io/microsphere/annotation/SinceTest.java
+++ b/microsphere-java-annotations/src/test/java/io/microsphere/annotation/SinceTest.java
@@ -36,4 +36,4 @@ void test() {
assertEquals("microsphere-java-core", since.module());
assertEquals("1.0.0", since.value());
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/pom.xml b/microsphere-java-core/pom.xml
index c6063daa5..c31c60b8c 100644
--- a/microsphere-java-core/pom.xml
+++ b/microsphere-java-core/pom.xml
@@ -20,11 +20,11 @@
-
+
- com.google.code.findbugs
- jsr305
- true
+ io.github.microsphere-projects
+ microsphere-java-annotations
+ ${revision}
@@ -62,6 +62,13 @@
test
+
+
+ com.google.code.findbugs
+ jsr305
+ test
+
+
ch.qos.logback
diff --git a/microsphere-java-core/src/main/java/io/microsphere/classloading/BannedArtifactClassLoadingExecutor.java b/microsphere-java-core/src/main/java/io/microsphere/classloading/BannedArtifactClassLoadingExecutor.java
index 98749c614..4d5f8325a 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/classloading/BannedArtifactClassLoadingExecutor.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/classloading/BannedArtifactClassLoadingExecutor.java
@@ -81,21 +81,19 @@ public BannedArtifactClassLoadingExecutor(@Nullable ClassLoader classLoader) {
}
public void execute() {
- List bannedArtifactConfigs = loadBannedArtifactConfigs();
+ List bannedArtifactConfigs = loadBannedArtifactConfigs(this.classLoader);
List artifacts = artifactDetector.detect(false);
- for (Artifact artifact : artifacts) {
+ artifacts.forEach(artifact -> {
URL classPathURL = artifact.getLocation();
- if (classPathURL != null) {
- for (MavenArtifact bannedArtifactConfig : bannedArtifactConfigs) {
- if (bannedArtifactConfig.matches(artifact)) {
- removeClassPathURL(classLoader, classPathURL);
- }
+ for (MavenArtifact bannedArtifactConfig : bannedArtifactConfigs) {
+ if (bannedArtifactConfig.matches(artifact)) {
+ removeClassPathURL(classLoader, classPathURL);
}
}
- }
+ });
}
- private List loadBannedArtifactConfigs() {
+ static List loadBannedArtifactConfigs(ClassLoader classLoader) {
List bannedArtifactConfigs = new LinkedList<>();
try {
Enumeration configResources = classLoader.getResources(CONFIG_LOCATION);
@@ -110,7 +108,7 @@ private List loadBannedArtifactConfigs() {
return bannedArtifactConfigs;
}
- private List loadBannedArtifactConfigs(URL configResource) throws IOException {
+ static List loadBannedArtifactConfigs(URL configResource) throws IOException {
List bannedArtifactConfigs = new LinkedList<>();
try (InputStream inputStream = configResource.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING))
@@ -127,14 +125,10 @@ private List loadBannedArtifactConfigs(URL configResource) throws
return bannedArtifactConfigs;
}
- /**
- * @param definition
- * @return
- */
- private MavenArtifact loadBannedArtifactConfig(String definition) {
+ static MavenArtifact loadBannedArtifactConfig(String definition) throws IllegalArgumentException {
String[] gav = split(definition.trim(), COLON);
if (gav.length != 3) {
- throw new RuntimeException("The definition of the banned artifact must contain groupId, artifactId and version : " + definition);
+ throw new IllegalArgumentException("The definition of the banned artifact must contain groupId, artifactId and version : " + definition);
}
String groupId = gav[0];
String artifactId = gav[1];
diff --git a/microsphere-java-core/src/main/java/io/microsphere/classloading/ManifestArtifactResourceResolver.java b/microsphere-java-core/src/main/java/io/microsphere/classloading/ManifestArtifactResourceResolver.java
index b0c616a2e..97f79ff08 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/classloading/ManifestArtifactResourceResolver.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/classloading/ManifestArtifactResourceResolver.java
@@ -21,6 +21,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.util.Objects;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
@@ -31,6 +32,7 @@
import static io.microsphere.util.StringUtils.split;
import static io.microsphere.util.jar.JarUtils.MANIFEST_RESOURCE_PATH;
import static java.lang.System.getProperty;
+import static java.util.stream.Stream.of;
/**
* {@link ArtifactResourceResolver} implementation that reads artifact metadata from JAR manifest files.
@@ -197,48 +199,33 @@ protected Artifact resolve(URL resourceURL, InputStream artifactMetadataData, Cl
return resolveArtifactMetaInfoInManifest(manifest, resourceURL);
}
- private Artifact resolveArtifactMetaInfoInManifest(Manifest manifest, URL resourceURL) throws IOException {
+ Artifact resolveArtifactMetaInfoInManifest(Manifest manifest, URL resourceURL) {
Attributes mainAttributes = manifest.getMainAttributes();
- String artifactId = resolveArtifactId(mainAttributes, resourceURL);
+ String artifactId = resolveArtifactId(mainAttributes);
if (artifactId == null) {
return null;
}
String version = resolveVersion(mainAttributes);
- return create(artifactId, version, resourceURL);
+ Artifact artifact = create(artifactId, version, resourceURL);
+ logger.trace("The artifactId was resolved from the resource URL['{}']: {}", artifactId, artifact);
+ return artifact;
}
- private String resolveArtifactId(Attributes attributes, URL artifactResourceURL) {
- String artifactId = null;
-
- for (String artifactIdAttributeName : ARTIFACT_ID_ATTRIBUTE_NAMES) {
- artifactId = attributes.getValue(artifactIdAttributeName);
- if (artifactId != null) {
- break;
- }
- }
-
- if (logger.isTraceEnabled()) {
- logger.trace("The artifactId was resolved from the '{}' of resource URL['{}'] of : {} , attributes : {}",
- MANIFEST_RESOURCE_PATH,
- artifactResourceURL.getPath(),
- artifactId,
- attributes.entrySet()
- );
- }
-
+ private String resolveArtifactId(Attributes attributes) {
+ String artifactId = of(ARTIFACT_ID_ATTRIBUTE_NAMES)
+ .map(attributes::getValue)
+ .filter(Objects::nonNull)
+ .findFirst()
+ .orElse(null);
return artifactId;
}
private String resolveVersion(Attributes attributes) {
- String version = null;
-
- for (String versionAttributeName : VERSION_ATTRIBUTE_NAMES) {
- version = attributes.getValue(versionAttributeName);
- if (version != null) {
- break;
- }
- }
-
+ String version = of(VERSION_ATTRIBUTE_NAMES)
+ .map(attributes::getValue)
+ .filter(Objects::nonNull)
+ .findFirst()
+ .orElse(null);
return version;
}
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/classloading/ServiceLoadingURLClassPathHandle.java b/microsphere-java-core/src/main/java/io/microsphere/classloading/ServiceLoadingURLClassPathHandle.java
index 658f679f0..5feb33760 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/classloading/ServiceLoadingURLClassPathHandle.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/classloading/ServiceLoadingURLClassPathHandle.java
@@ -21,6 +21,7 @@
import static io.microsphere.util.ArrayUtils.isEmpty;
import static io.microsphere.util.ServiceLoaderUtils.loadServicesList;
+import static java.util.Objects.nonNull;
/**
* {@link URLClassPathHandle} implementation based on the Service Loading mechanism
@@ -34,17 +35,16 @@ public class ServiceLoadingURLClassPathHandle implements URLClassPathHandle {
public ServiceLoadingURLClassPathHandle() {
List urlClassPathHandles = loadServicesList(URLClassPathHandle.class);
- for (URLClassPathHandle urlClassPathHandle : urlClassPathHandles) {
- if (urlClassPathHandle.supports()) {
- this.delegate = urlClassPathHandle;
- break;
- }
- }
+ this.delegate = urlClassPathHandles
+ .stream()
+ .filter(URLClassPathHandle::supports)
+ .findFirst()
+ .orElse(null);
}
@Override
public boolean supports() {
- return delegate != null;
+ return nonNull(this.delegate);
}
@Override
diff --git a/microsphere-java-core/src/main/java/io/microsphere/classloading/StreamArtifactResourceResolver.java b/microsphere-java-core/src/main/java/io/microsphere/classloading/StreamArtifactResourceResolver.java
index 052e0bda5..58ed3de1a 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/classloading/StreamArtifactResourceResolver.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/classloading/StreamArtifactResourceResolver.java
@@ -113,9 +113,7 @@ public final Artifact resolve(URL resourceURL) {
Artifact artifact = null;
try {
if (archiveFile == null) {
- if (logger.isTraceEnabled()) {
- logger.trace("The resourceURL['{}'] can't be resolved to be an archive file", resourceURL);
- }
+ logger.trace("The resourceURL['{}'] can't be resolved to be an archive file", resourceURL);
artifactMetadataData = readArtifactMetadataDataFromResource(resourceURL, classLoader);
} else {
artifactMetadataData = readArtifactMetadataDataFromArchiveFile(archiveFile);
@@ -124,9 +122,7 @@ public final Artifact resolve(URL resourceURL) {
artifact = resolve(resourceURL, artifactMetadataData, classLoader);
}
} catch (IOException e) {
- if (logger.isErrorEnabled()) {
- logger.error("The Artifact can't be resolved from the resource URL : {}", resourceURL, e);
- }
+ logger.error("The Artifact can't be resolved from the resource URL : {}", resourceURL, e);
} finally {
// close the InputStream
close(artifactMetadataData);
@@ -141,13 +137,11 @@ protected InputStream readArtifactMetadataDataFromResource(URL resourceURL, Clas
@Nullable
protected InputStream readArtifactMetadataDataFromArchiveFile(File archiveFile) throws IOException {
- InputStream artifactMetadataData = null;
- if (archiveFile.isFile()) {
- artifactMetadataData = readArtifactMetadataDataFromFile(archiveFile);
- } else if (archiveFile.isDirectory()) {
- artifactMetadataData = readArtifactMetadataDataFromDirectory(archiveFile);
+ if (archiveFile.isDirectory()) {
+ return readArtifactMetadataDataFromDirectory(archiveFile);
+ } else {
+ return readArtifactMetadataDataFromFile(archiveFile);
}
- return artifactMetadataData;
}
@Nullable
@@ -155,9 +149,7 @@ protected InputStream readArtifactMetadataDataFromFile(File archiveFile) throws
JarFile jarFile = new JarFile(archiveFile);
JarEntry jarEntry = findArtifactMetadataEntry(jarFile);
if (jarEntry == null) {
- if (logger.isTraceEnabled()) {
- logger.trace("The artifact metadata entry can't be resolved from the JarFile[path: '{}']", archiveFile);
- }
+ logger.trace("The artifact metadata entry can't be resolved from the JarFile[path: '{}']", archiveFile);
return null;
}
return jarFile.getInputStream(jarEntry);
@@ -167,9 +159,7 @@ protected InputStream readArtifactMetadataDataFromFile(File archiveFile) throws
protected InputStream readArtifactMetadataDataFromDirectory(File directory) throws IOException {
File artifactMetadataFile = findArtifactMetadata(directory);
if (artifactMetadataFile == null) {
- if (logger.isTraceEnabled()) {
- logger.trace("The artifact metadata file can't be found in the directory[path: '{}']", directory);
- }
+ logger.trace("The artifact metadata file can't be found in the directory[path: '{}']", directory);
return null;
}
return new FileInputStream(artifactMetadataFile);
@@ -197,4 +187,4 @@ protected boolean isArtifactMetadataFile(File directory, File file) {
protected abstract boolean isArtifactMetadata(String relativePath);
protected abstract Artifact resolve(URL resourceURL, InputStream artifactMetadataData, ClassLoader classLoader) throws IOException;
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/collection/ArrayEnumeration.java b/microsphere-java-core/src/main/java/io/microsphere/collection/ArrayEnumeration.java
index 2a58a8615..151487742 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/collection/ArrayEnumeration.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/collection/ArrayEnumeration.java
@@ -16,7 +16,6 @@
*/
package io.microsphere.collection;
-import java.util.Arrays;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.StringJoiner;
@@ -25,6 +24,7 @@
import static io.microsphere.constants.SymbolConstants.LEFT_SQUARE_BRACKET;
import static io.microsphere.constants.SymbolConstants.RIGHT_SQUARE_BRACKET;
import static io.microsphere.constants.SymbolConstants.SPACE;
+import static io.microsphere.util.ArrayUtils.arrayEquals;
import static java.lang.String.valueOf;
import static java.util.Objects.hash;
@@ -85,7 +85,7 @@ public final boolean equals(Object o) {
if (!(o instanceof ArrayEnumeration)) return false;
ArrayEnumeration> that = (ArrayEnumeration>) o;
- return Arrays.equals(elements, that.elements);
+ return arrayEquals(elements, that.elements);
}
@Override
diff --git a/microsphere-java-core/src/main/java/io/microsphere/collection/DelegatingIterator.java b/microsphere-java-core/src/main/java/io/microsphere/collection/DelegatingIterator.java
new file mode 100644
index 000000000..3975f19ab
--- /dev/null
+++ b/microsphere-java-core/src/main/java/io/microsphere/collection/DelegatingIterator.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 io.microsphere.collection;
+
+import io.microsphere.lang.DelegatingWrapper;
+
+import java.util.Iterator;
+import java.util.function.Consumer;
+
+/**
+ * A delegating implementation of the {@link Iterator} interface that forwards all method calls to a delegate iterator.
+ * This class is useful when you want to wrap an existing iterator and potentially override some of its behavior.
+ *
+ *
Example Usage
+ *
{@code
+ * List list = Arrays.asList("a", "b", "c");
+ * Iterator iterator = new DelegatingIterator<>(list.iterator());
+ * while (iterator.hasNext()) {
+ * System.out.println(iterator.next());
+ * }
+ * }
+ *
+ * @param the type of elements returned by this iterator
+ * @author Mercy
+ * @see Iterator
+ */
+public class DelegatingIterator implements Iterator, DelegatingWrapper {
+
+ private final Iterator delegate;
+
+ public DelegatingIterator(Iterator delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public final boolean hasNext() {
+ return delegate.hasNext();
+ }
+
+ @Override
+ public final E next() {
+ return delegate.next();
+ }
+
+ @Override
+ public final void remove() {
+ delegate.remove();
+ }
+
+ @Override
+ public final void forEachRemaining(Consumer super E> action) {
+ this.delegate.forEachRemaining(action);
+ }
+
+ @Override
+ public final Object getDelegate() {
+ return this.delegate;
+ }
+
+ @Override
+ public final int hashCode() {
+ return this.delegate.hashCode();
+ }
+
+ @Override
+ public final boolean equals(Object obj) {
+ return this.delegate.equals(obj);
+ }
+
+ @Override
+ public final String toString() {
+ return this.delegate.toString();
+ }
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/collection/EmptyIterator.java b/microsphere-java-core/src/main/java/io/microsphere/collection/EmptyIterator.java
index 83f95542d..08514248e 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/collection/EmptyIterator.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/collection/EmptyIterator.java
@@ -55,31 +55,15 @@
* @see Collections#emptyIterator()
*/
@Immutable
-public class EmptyIterator implements Iterator {
+public class EmptyIterator extends DelegatingIterator {
/**
* The singleton of {@link EmptyIterator}
*/
public static final EmptyIterator INSTANCE = new EmptyIterator();
- private final Iterator delegate;
public EmptyIterator() {
- this.delegate = emptyIterator();
- }
-
- @Override
- public boolean hasNext() {
- return delegate.hasNext();
- }
-
- @Override
- public E next() {
- return delegate.next();
- }
-
- @Override
- public void remove() {
- delegate.remove();
+ super(emptyIterator());
}
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/collection/MapUtils.java b/microsphere-java-core/src/main/java/io/microsphere/collection/MapUtils.java
index afc9fba4e..832f4f683 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/collection/MapUtils.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/collection/MapUtils.java
@@ -40,6 +40,7 @@
import static io.microsphere.util.ArrayUtils.length;
import static io.microsphere.util.ClassUtils.isAssignableFrom;
import static java.lang.Float.MIN_VALUE;
+import static java.lang.String.valueOf;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static java.util.Collections.unmodifiableMap;
@@ -1184,7 +1185,7 @@ public static Map nestedMap(Map map) {
for (Map.Entry entry : map.entrySet()) {
String propertyName = entry.getKey();
- String propertyValue = String.valueOf(entry.getValue());
+ String propertyValue = valueOf(entry.getValue());
int index = propertyName.indexOf(DOT_CHAR);
if (index > 0) {
String actualPropertyName = propertyName.substring(0, index);
diff --git a/microsphere-java-core/src/main/java/io/microsphere/collection/ReversedDeque.java b/microsphere-java-core/src/main/java/io/microsphere/collection/ReversedDeque.java
index e55d9ba04..84113b5e0 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/collection/ReversedDeque.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/collection/ReversedDeque.java
@@ -27,6 +27,7 @@
import static io.microsphere.util.ArrayUtils.reverse;
import static io.microsphere.util.ArrayUtils.toArrayReversed;
+import static java.util.Spliterator.ORDERED;
/**
* Reverse ordered {@link Deque} based on JDK 21 {@link java.util.ReverseOrderDequeView}
@@ -64,7 +65,7 @@ public Iterator iterator() {
@Override
public Spliterator spliterator() {
- return Spliterators.spliterator(this, Spliterator.ORDERED);
+ return Spliterators.spliterator(this, ORDERED);
}
// ========== Collection ==========
diff --git a/microsphere-java-core/src/main/java/io/microsphere/concurrent/ExecutorUtils.java b/microsphere-java-core/src/main/java/io/microsphere/concurrent/ExecutorUtils.java
index a4cfc45e8..930ce67d8 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/concurrent/ExecutorUtils.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/concurrent/ExecutorUtils.java
@@ -16,6 +16,7 @@
*/
package io.microsphere.concurrent;
+import io.microsphere.logging.Logger;
import io.microsphere.util.ShutdownHookUtils;
import io.microsphere.util.Utils;
@@ -23,6 +24,7 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import static io.microsphere.logging.LoggerFactory.getLogger;
import static io.microsphere.util.ArrayUtils.forEach;
import static io.microsphere.util.ShutdownHookUtils.addShutdownHookCallback;
@@ -37,6 +39,8 @@
*/
public abstract class ExecutorUtils implements Utils {
+ private static final Logger logger = getLogger(ExecutorUtils.class);
+
/**
* Registers a shutdown hook to gracefully shut down the given {@link Executor} instances when the JVM exits.
*
@@ -131,9 +135,10 @@ public static boolean shutdown(ExecutorService executorService) {
if (!executorService.isShutdown()) {
executorService.shutdown();
}
+ logger.trace("The ExecutorService({}) has been shutdown", executorService);
return true;
}
private ExecutorUtils() {
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/convert/AbstractConverter.java b/microsphere-java-core/src/main/java/io/microsphere/convert/AbstractConverter.java
index 4ce41c1ca..9f465c8ab 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/convert/AbstractConverter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/convert/AbstractConverter.java
@@ -21,11 +21,11 @@
import io.microsphere.annotation.Nullable;
import io.microsphere.lang.Prioritized;
import io.microsphere.logging.Logger;
-import io.microsphere.logging.LoggerFactory;
import java.util.List;
import java.util.Objects;
+import static io.microsphere.logging.LoggerFactory.getLogger;
import static io.microsphere.util.ClassUtils.getAllClasses;
import static io.microsphere.util.ClassUtils.getTypeName;
import static io.microsphere.util.ExceptionUtils.wrap;
@@ -87,7 +87,7 @@
*/
public abstract class AbstractConverter implements Converter {
- protected final Logger logger = LoggerFactory.getLogger(getClass());
+ protected final Logger logger = getLogger(getClass());
@Nullable
private Integer priority;
@@ -102,13 +102,11 @@ public final T convert(@Nullable S source) {
if (source == null) {
return null;
}
- T target = null;
+ T target;
try {
target = doConvert(source);
} catch (Throwable e) {
- if (logger.isTraceEnabled()) {
- logger.trace("The source[value : {}] can't be converted by the Converter[class : '{}']", source, getTypeName(getClass()));
- }
+ logger.warn("The source[value : {}] can't be converted by the Converter[class : '{}']", source, getTypeName(getClass()));
throw wrap(e, RuntimeException.class);
}
return target;
@@ -155,7 +153,12 @@ public int getPriority() {
@Override
public boolean equals(Object o) {
- if (!(o instanceof AbstractConverter)) return false;
+ if (o == this) {
+ return true;
+ }
+ if (!(o instanceof AbstractConverter)) {
+ return false;
+ }
AbstractConverter, ?> that = (AbstractConverter, ?>) o;
return Objects.equals(getSourceType(), that.getSourceType())
diff --git a/microsphere-java-core/src/main/java/io/microsphere/convert/multiple/StringToArrayConverter.java b/microsphere-java-core/src/main/java/io/microsphere/convert/multiple/StringToArrayConverter.java
index d3a7ad6a0..57fc84822 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/convert/multiple/StringToArrayConverter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/convert/multiple/StringToArrayConverter.java
@@ -19,9 +19,8 @@
import io.microsphere.convert.Converter;
-import java.lang.reflect.Array;
-
import static java.lang.reflect.Array.newInstance;
+import static java.lang.reflect.Array.set;
/**
* The class to convert {@link String} to array-type object
@@ -44,7 +43,7 @@ public Object convert(String[] segments, int size, Class> targetType, Class>
Object array = newInstance(componentType, size);
for (int i = 0; i < size; i++) {
- Array.set(array, i, converter.convert(segments[i]));
+ set(array, i, converter.convert(segments[i]));
}
return array;
diff --git a/microsphere-java-core/src/main/java/io/microsphere/event/EventListener.java b/microsphere-java-core/src/main/java/io/microsphere/event/EventListener.java
index 53bf32623..c85f1a5f2 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/event/EventListener.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/event/EventListener.java
@@ -22,8 +22,9 @@
import java.lang.reflect.Type;
import java.util.Objects;
+import static io.microsphere.reflect.TypeUtils.asClass;
import static io.microsphere.reflect.TypeUtils.getAllParameterizedTypes;
-
+import static io.microsphere.reflect.TypeUtils.isAssignableFrom;
/**
* The {@link Event Event} Listener that is based on Java standard {@link java.util.EventListener} interface supports
@@ -128,7 +129,7 @@ static Class extends Event> findEventType(EventListener> listener) {
static Class extends Event> findEventType(Class> listenerClass) {
Class extends Event> eventType = null;
- if (listenerClass != null && EventListener.class.isAssignableFrom(listenerClass)) {
+ if (isAssignableFrom(EventListener.class, listenerClass)) {
eventType = getAllParameterizedTypes(listenerClass)
.stream()
.map(EventListener::findEventType)
@@ -174,15 +175,13 @@ static Class extends Event> findEventType(ParameterizedType parameterizedType)
Class extends Event> eventType = null;
Type rawType = parameterizedType.getRawType();
- if ((rawType instanceof Class) && EventListener.class.isAssignableFrom((Class) rawType)) {
+ if (isAssignableFrom(EventListener.class, rawType)) {
Type[] typeArguments = parameterizedType.getActualTypeArguments();
for (Type typeArgument : typeArguments) {
- if (typeArgument instanceof Class) {
- Class argumentClass = (Class) typeArgument;
- if (Event.class.isAssignableFrom(argumentClass)) {
- eventType = argumentClass;
- break;
- }
+ Class argumentClass = asClass(typeArgument);
+ if (isAssignableFrom(Event.class, argumentClass)) {
+ eventType = argumentClass;
+ break;
}
}
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/filter/Filter.java b/microsphere-java-core/src/main/java/io/microsphere/filter/Filter.java
index 912e24704..5850f5118 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/filter/Filter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/filter/Filter.java
@@ -3,6 +3,8 @@
*/
package io.microsphere.filter;
+import java.util.function.Predicate;
+
/**
* The {@code Filter} interface represents a generic filtering mechanism that can be applied to objects of type {@code T}.
*
@@ -29,7 +31,7 @@
* @since 1.0.0
*/
@FunctionalInterface
-public interface Filter {
+public interface Filter extends Predicate {
/**
* Does accept filtered object?
@@ -38,4 +40,9 @@ public interface Filter {
* @return
*/
boolean accept(T filteredObject);
-}
+
+ @Override
+ default boolean test(T t) {
+ return accept(t);
+ }
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/filter/PackageNameClassFilter.java b/microsphere-java-core/src/main/java/io/microsphere/filter/PackageNameClassFilter.java
index e77237aa7..c0e313cc9 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/filter/PackageNameClassFilter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/filter/PackageNameClassFilter.java
@@ -24,7 +24,9 @@
public class PackageNameClassFilter implements ClassFilter {
private final String packageName;
+
private final boolean includedSubPackages;
+
private final String subPackageNamePrefix;
/**
diff --git a/microsphere-java-core/src/main/java/io/microsphere/invoke/MethodHandleUtils.java b/microsphere-java-core/src/main/java/io/microsphere/invoke/MethodHandleUtils.java
index 13ec7877e..49f07cfea 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/invoke/MethodHandleUtils.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/invoke/MethodHandleUtils.java
@@ -22,6 +22,7 @@
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
@@ -88,7 +89,7 @@ public abstract class MethodHandleUtils implements Utils {
/**
* A single-bit mask representing {@code module} access,
- * which may contribute to the result of {@link MethodHandles.Lookup#lookupModes lookupModes}.
+ * which may contribute to the result of {@link Lookup#lookupModes lookupModes}.
* The value is {@code 0x10}, which does not correspond meaningfully to
* any particular {@linkplain Modifier modifier bit}.
* In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
@@ -96,17 +97,17 @@ public abstract class MethodHandleUtils implements Utils {
* lookup class and public types in packages exported by other modules
* to the module of the class to be looked up.
*
- * If this lookup mode is set, the {@linkplain MethodHandles.Lookup#previousrequestedClass()
+ * If this lookup mode is set, the {@linkplain Lookup#previousrequestedClass()
* previous lookup class} is always {@code null}.
*
- * @see MethodHandles.Lookup#MODULE
+ * @see Lookup#MODULE
* @since 9
*/
public static final int MODULE = PACKAGE << 1;
/**
* A single-bit mask representing {@code unconditional} access
- * which may contribute to the result of {@link MethodHandles.Lookup#lookupModes lookupModes}.
+ * which may contribute to the result of {@link Lookup#lookupModes lookupModes}.
* The value is {@code 0x20}, which does not correspond meaningfully to
* any particular {@linkplain Modifier modifier bit}.
* A {@code Lookup} with this lookup mode assumes {@linkplain
@@ -116,18 +117,18 @@ public abstract class MethodHandleUtils implements Utils {
* java.lang.Module#isExported(String) exported unconditionally}.
*
*
- * If this lookup mode is set, the {@linkplain MethodHandles.Lookup#previousrequestedClass()
+ * If this lookup mode is set, the {@linkplain Lookup#previousrequestedClass()
* previous lookup class} is always {@code null}.
*
- * @see MethodHandles.Lookup#publicLookup()
- * @see MethodHandles.Lookup#UNCONDITIONAL
+ * @see Lookup#publicLookup()
+ * @see Lookup#UNCONDITIONAL
* @since 9
*/
public static final int UNCONDITIONAL = PACKAGE << 2;
/**
* A single-bit mask representing {@code original} access
- * which may contribute to the result of {@link MethodHandles.Lookup#lookupModes lookupModes}.
+ * which may contribute to the result of {@link Lookup#lookupModes lookupModes}.
* The value is {@code 0x40}, which does not correspond meaningfully to
* any particular {@linkplain Modifier modifier bit}.
*
@@ -136,9 +137,9 @@ public abstract class MethodHandleUtils implements Utils {
* created by the original lookup class by calling
* {@link MethodHandles#lookup()} method or by a bootstrap method
* invoked by the VM. The {@code Lookup} object with this lookup
- * mode has {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess() full privilege access}.
+ * mode has {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
*
- * @see MethodHandles.Lookup#ORIGINAL
+ * @see Lookup#ORIGINAL
* @since 16
*/
public static final int ORIGINAL = PACKAGE << 3;
@@ -150,61 +151,61 @@ public abstract class MethodHandleUtils implements Utils {
public static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
/**
- * The {@link Constructor} for {@link MethodHandles.Lookup#Lookup(Class)} since JDK 7
+ * The {@link Constructor} for {@link Lookup#Lookup(Class)} since JDK 7
*/
- private static final Constructor lookupConstructor1 = getDeclaredConstructor(MethodHandles.Lookup.class, Class.class);
+ private static final Constructor lookupConstructor1 = getDeclaredConstructor(Lookup.class, Class.class);
/**
- * The {@link Constructor} for {@link MethodHandles.Lookup#Lookup(Class, int)} since JDK 7
+ * The {@link Constructor} for {@link Lookup#Lookup(Class, int)} since JDK 7
*/
- private static final Constructor lookupConstructor2 = findConstructor(MethodHandles.Lookup.class, Class.class, int.class);
+ private static final Constructor lookupConstructor2 = findConstructor(Lookup.class, Class.class, int.class);
/**
- * The {@link Constructor} for {@link MethodHandles.Lookup#Lookup(Class, Class, int)} since JDK 14
+ * The {@link Constructor} for {@link Lookup#Lookup(Class, Class, int)} since JDK 14
*/
- private static final Constructor lookupConstructor3 = findConstructor(MethodHandles.Lookup.class, Class.class, Class.class, int.class);
+ private static final Constructor lookupConstructor3 = findConstructor(Lookup.class, Class.class, Class.class, int.class);
- private static final ConcurrentMap lookupCache = new ConcurrentHashMap<>();
+ private static final ConcurrentMap lookupCache = new ConcurrentHashMap<>();
/**
- * The {@link MethodHandles.Lookup} for {@link MethodHandles#publicLookup()}
+ * The {@link Lookup} for {@link MethodHandles#publicLookup()}
*/
- public static final MethodHandles.Lookup PUBLIC_LOOKUP = publicLookup();
+ public static final Lookup PUBLIC_LOOKUP = publicLookup();
/**
- * The allowed {@link MethodHandles.Lookup} modes enumeration
+ * The allowed {@link Lookup} modes enumeration
*
- * @see MethodHandles.Lookup#PUBLIC
- * @see MethodHandles.Lookup#PRIVATE
- * @see MethodHandles.Lookup#PROTECTED
- * @see MethodHandles.Lookup#PACKAGE
- * @see MethodHandles.Lookup#MODULE
- * @see MethodHandles.Lookup#UNCONDITIONAL
- * @see MethodHandles.Lookup#ORIGINAL
- * @see MethodHandles.Lookup#TRUSTED
- * @see MethodHandles.Lookup#ALL_MODES
+ * @see Lookup#PUBLIC
+ * @see Lookup#PRIVATE
+ * @see Lookup#PROTECTED
+ * @see Lookup#PACKAGE
+ * @see Lookup#MODULE
+ * @see Lookup#UNCONDITIONAL
+ * @see Lookup#ORIGINAL
+ * @see Lookup#TRUSTED
+ * @see Lookup#ALL_MODES
*/
public enum LookupMode {
/**
- * @see MethodHandles.Lookup#PUBLIC
+ * @see Lookup#PUBLIC
*/
- PUBLIC(MethodHandles.Lookup.PUBLIC),
+ PUBLIC(Lookup.PUBLIC),
/**
- * @see MethodHandles.Lookup#PRIVATE
+ * @see Lookup#PRIVATE
*/
- PRIVATE(MethodHandles.Lookup.PRIVATE),
+ PRIVATE(Lookup.PRIVATE),
/**
- * @see MethodHandles.Lookup#PROTECTED
+ * @see Lookup#PROTECTED
*/
- PROTECTED(MethodHandles.Lookup.PROTECTED),
+ PROTECTED(Lookup.PROTECTED),
/**
- * @see MethodHandles.Lookup#PACKAGE
+ * @see Lookup#PACKAGE
*/
- PACKAGE(MethodHandles.Lookup.PACKAGE),
+ PACKAGE(Lookup.PACKAGE),
/**
* @see MethodHandleUtils#MODULE
@@ -249,6 +250,7 @@ public static int getModes(LookupMode... lookupModes) {
}
static class LookupKey {
+
final Class> requestedClass;
final int allowedModes;
@@ -260,10 +262,15 @@ static class LookupKey {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof LookupKey)) {
+ return false;
+ }
LookupKey lookupKey = (LookupKey) o;
- return allowedModes == lookupKey.allowedModes && Objects.equals(requestedClass, lookupKey.requestedClass);
+ return allowedModes == lookupKey.allowedModes &&
+ Objects.equals(requestedClass, lookupKey.requestedClass);
}
@Override
@@ -277,31 +284,31 @@ static LookupKey buildKey(Class> requestedClass, int allowedModes) {
}
/**
- * Create an instance of {@link MethodHandles.Lookup} by the specified lookup class
+ * Create an instance of {@link Lookup} by the specified lookup class
* with {@link #ALL_MODES all accesses (public, private, protected and package)}
*
* @param requestedClass the class to be looked up
* @return non-null
*/
- public static MethodHandles.Lookup lookup(Class> requestedClass) {
+ public static Lookup lookup(Class> requestedClass) {
return lookup(requestedClass, LookupMode.ALL);
}
/**
- * Create an instance of {@link MethodHandles.Lookup} by the specified lookup class
+ * Create an instance of {@link Lookup} by the specified lookup class
* with {@link #ALL_MODES all access (public, private, protected and package)}
*
* @param requestedClass the class to be looked up
* @return non-null
*/
- public static MethodHandles.Lookup lookup(Class> requestedClass, LookupMode... lookupModes) {
+ public static Lookup lookup(Class> requestedClass, LookupMode... lookupModes) {
int allowedModes = getModes(lookupModes);
LookupKey key = buildKey(requestedClass, allowedModes);
return lookupCache.computeIfAbsent(key, MethodHandleUtils::newLookup);
}
/**
- * The convenient method to find {@link MethodHandles.Lookup#findVirtual(Class, String, MethodType)}
+ * The convenient method to find {@link Lookup#findVirtual(Class, String, MethodType)}
*
* @param requestedClass the class to be looked up
* @param methodName the target method name
@@ -313,7 +320,7 @@ public static MethodHandle findVirtual(Class> requestedClass, String methodNam
}
/**
- * The convenient method to find {@link MethodHandles.Lookup#findStatic(Class, String, MethodType)}
+ * The convenient method to find {@link Lookup#findStatic(Class, String, MethodType)}
*
* @param requestedClass the class to be looked up
* @param methodName the target method name
@@ -332,13 +339,11 @@ public static MethodHandle findStatic(Class> requestedClass, String methodName
* @param args the arguments of {@link MethodHandle#invokeExact(Object...)}
*/
public static void handleInvokeExactFailure(Throwable e, MethodHandle methodHandle, Object... args) {
- if (logger.isWarnEnabled()) {
- logger.warn("Failed to invokeExact on the {} with arguments : {}", methodHandle, arrayToString(args), e);
- }
+ logger.warn("Failed to invokeExact on the {} with arguments : {}", methodHandle, arrayToString(args), e);
}
protected static MethodHandle find(Class> requestedClass, String methodName, Class[] parameterTypes,
- ThrowableBiFunction function) {
+ ThrowableBiFunction function) {
Method method = findMethod(requestedClass, methodName, parameterTypes);
if (method == null) {
return NOT_FOUND_METHOD_HANDLE;
@@ -346,11 +351,11 @@ protected static MethodHandle find(Class> requestedClass, String methodName, C
if (isiCandidateMethod(method)) {
return findPublic(method, function);
}
- MethodHandles.Lookup lookup = lookup(requestedClass);
+ Lookup lookup = lookup(requestedClass);
return MethodHandlesLookupUtils.find(lookup, requestedClass, methodName, parameterTypes, function);
}
- private static MethodHandles.Lookup newLookup(LookupKey key) {
+ private static Lookup newLookup(LookupKey key) {
if (lookupConstructor3 != null) {
return newInstance(lookupConstructor3, key.requestedClass, key.requestedClass, key.allowedModes);
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/FastByteArrayInputStream.java b/microsphere-java-core/src/main/java/io/microsphere/io/FastByteArrayInputStream.java
index a297812dc..73474abc1 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/FastByteArrayInputStream.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/FastByteArrayInputStream.java
@@ -17,8 +17,8 @@
package io.microsphere.io;
import java.io.ByteArrayInputStream;
-import java.util.Arrays;
+import static io.microsphere.util.ArrayUtils.arrayEquals;
import static java.lang.System.arraycopy;
import static java.util.Objects.hash;
@@ -110,17 +110,20 @@ public int read(byte[] b, int off, int len) {
throw new IndexOutOfBoundsException();
}
- if (pos >= count) {
- return -1;
+ if (len == 0) {
+ return 0;
}
int avail = count - pos;
+
+ if (avail < 1) {
+ return -1;
+ }
+
if (len > avail) {
len = avail;
}
- if (len <= 0) {
- return 0;
- }
+
arraycopy(buf, pos, b, off, len);
pos += len;
return len;
@@ -156,7 +159,7 @@ public boolean equals(Object obj) {
if (!(obj instanceof FastByteArrayInputStream)) {
return false;
}
- return Arrays.equals(this.buf, ((FastByteArrayInputStream) obj).buf);
+ return arrayEquals(this.buf, ((FastByteArrayInputStream) obj).buf);
}
@Override
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/FileUtils.java b/microsphere-java-core/src/main/java/io/microsphere/io/FileUtils.java
index b8ca0539e..b11cf416a 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/FileUtils.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/FileUtils.java
@@ -10,17 +10,18 @@
import io.microsphere.util.Utils;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.file.NoSuchFileException;
-import static io.microsphere.constants.FileConstants.FILE_EXTENSION_CHAR;
+import static io.microsphere.constants.FileConstants.FILE_EXTENSION;
import static io.microsphere.constants.PathConstants.SLASH_CHAR;
import static io.microsphere.constants.SymbolConstants.DOT_CHAR;
import static io.microsphere.lang.function.ThrowableSupplier.execute;
import static io.microsphere.util.ArrayUtils.isEmpty;
import static io.microsphere.util.CharSequenceUtils.isEmpty;
-import static io.microsphere.util.StringUtils.isBlank;
+import static io.microsphere.util.StringUtils.substringAfterLast;
import static java.io.File.separatorChar;
+import static java.nio.file.Files.delete;
import static java.nio.file.Files.isSymbolicLink;
/**
@@ -97,11 +98,7 @@ public static String resolveRelativePath(File parentDirectory, File targetFile)
*/
@Nullable
public static String getFileExtension(String fileName) {
- if (isBlank(fileName)) {
- return null;
- }
- int index = fileName.lastIndexOf(FILE_EXTENSION_CHAR);
- return index > -1 ? fileName.substring(index + 1) : null;
+ return substringAfterLast(fileName, FILE_EXTENSION);
}
/**
@@ -164,17 +161,8 @@ public static int deleteDirectory(File directory) throws IOException {
*/
public static int cleanDirectory(File directory) throws IOException {
int deletedFilesCount = 0;
- IOException exception = null;
for (File file : listFiles(directory)) {
- try {
- deletedFilesCount += forceDelete(file);
- } catch (IOException ioe) {
- exception = ioe;
- }
- }
-
- if (null != exception) {
- throw exception;
+ deletedFilesCount += forceDelete(file);
}
return deletedFilesCount;
}
@@ -190,30 +178,22 @@ public static int cleanDirectory(File directory) throws IOException {
*
{@code forceDelete(new File("/tmp/file.txt"))} deletes the file and returns {@code 1}
*
{@code forceDelete(new File("/tmp/testDir"))} deletes the directory and all its contents,
* returning the total count of deleted files and directories.
- *
{@code forceDelete(new File("/nonexistent/file"))} throws a {@link FileNotFoundException}
+ *
{@code forceDelete(new File("/nonexistent/file"))} throws a {@link NoSuchFileException}
*
*
* @param file the file or directory to delete, must not be {@code null}
* @return the number of deleted files and directories
- * @throws NullPointerException if the file is {@code null}
- * @throws FileNotFoundException if the file does not exist
- * @throws IOException if deletion fails for any reason
+ * @throws NullPointerException if the file is {@code null}
+ * @throws NoSuchFileException if the file does not exist
+ * @throws IOException if deletion fails for any reason
*/
- public static int forceDelete(File file) throws IOException {
+ public static int forceDelete(File file) throws NoSuchFileException, IOException {
final int deletedFilesCount;
if (file.isDirectory()) {
deletedFilesCount = deleteDirectory(file);
} else {
- boolean filePresent = file.exists();
- if (file.delete()) {
- deletedFilesCount = 1;
- } else {
- if (!filePresent) {
- throw new FileNotFoundException("File does not exist: " + file);
- }
- String message = "Unable to delete file: " + file;
- throw new IOException(message);
- }
+ delete(file.toPath());
+ deletedFilesCount = 1;
}
return deletedFilesCount;
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/IOUtils.java b/microsphere-java-core/src/main/java/io/microsphere/io/IOUtils.java
index 424454bff..c5bd0b47e 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/IOUtils.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/IOUtils.java
@@ -367,9 +367,7 @@ public static int copy(InputStream in, OutputStream out) throws IOException {
byteCount += bytesRead;
}
out.flush();
- if (logger.isTraceEnabled()) {
- logger.trace("Copied {} bytes[buffer size : {}] from InputStream[{}] to OutputStream[{}]", byteCount, BUFFER_SIZE, in, out);
- }
+ logger.trace("Copied {} bytes[buffer size : {}] from InputStream[{}] to OutputStream[{}]", byteCount, BUFFER_SIZE, in, out);
return byteCount;
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/StandardFileWatchService.java b/microsphere-java-core/src/main/java/io/microsphere/io/StandardFileWatchService.java
index 052a8a5f1..ba892d397 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/StandardFileWatchService.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/StandardFileWatchService.java
@@ -22,6 +22,7 @@
import io.microsphere.io.event.FileChangedEvent;
import io.microsphere.io.event.FileChangedEvent.Kind;
import io.microsphere.io.event.FileChangedListener;
+import io.microsphere.logging.Logger;
import java.io.File;
import java.nio.file.FileSystem;
@@ -36,7 +37,7 @@
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import static io.microsphere.annotation.ConfigurationProperty.SYSTEM_PROPERTIES_SOURCE;
import static io.microsphere.collection.MapUtils.newTreeMap;
@@ -49,6 +50,9 @@
import static io.microsphere.io.event.FileChangedEvent.Kind.CREATED;
import static io.microsphere.io.event.FileChangedEvent.Kind.DELETED;
import static io.microsphere.io.event.FileChangedEvent.Kind.MODIFIED;
+import static io.microsphere.logging.LoggerFactory.getLogger;
+import static io.microsphere.text.FormatUtils.format;
+import static io.microsphere.util.ArrayUtils.arrayToString;
import static io.microsphere.util.ArrayUtils.length;
import static java.lang.System.getProperty;
import static java.nio.file.FileSystems.getDefault;
@@ -57,8 +61,8 @@
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
-import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* /**
@@ -103,6 +107,8 @@
*/
public class StandardFileWatchService implements FileWatchService, AutoCloseable {
+ private static final Logger logger = getLogger(StandardFileWatchService.class);
+
/**
* The default thread name prefix : "microsphere-file-watch-service"
*/
@@ -124,7 +130,7 @@ public class StandardFileWatchService implements FileWatchService, AutoCloseable
)
public static final String THREAD_NAME_PREFIX = getProperty(THREAD_NAME_PREFIX_PROPERTY_NAME, DEFAULT_THREAD_NAME_PREFIX);
- private static final WatchEvent.Kind>[] ALL_WATCH_EVENT_KINDS = {
+ static final WatchEvent.Kind>[] ALL_WATCH_EVENT_KINDS = {
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY
@@ -132,15 +138,15 @@ public class StandardFileWatchService implements FileWatchService, AutoCloseable
private WatchService watchService;
- private final ExecutorService eventLoopExecutor;
-
private final Executor eventHandlerExecutor;
+ private final ExecutorService eventLoopExecutor;
+
private final Map fileChangedMetadataCache = newTreeMap();
- private volatile boolean started;
+ private final AtomicBoolean started;
- private Future eventLoopFuture;
+ private volatile Future eventLoopFuture;
public StandardFileWatchService() {
this(DIRECT_EXECUTOR);
@@ -151,18 +157,19 @@ public StandardFileWatchService(Executor eventHandlerExecutor) {
}
public StandardFileWatchService(Executor eventHandlerExecutor, ExecutorService eventLoopExecutor) {
- this.eventLoopExecutor = eventLoopExecutor;
this.eventHandlerExecutor = eventHandlerExecutor;
+ this.eventLoopExecutor = eventLoopExecutor;
+ this.started = new AtomicBoolean(false);
// shutdown the ExecutorService when JVM exits
shutdownOnExit(eventLoopExecutor, eventHandlerExecutor);
}
public void start() throws Exception {
- if (started) {
+ if (!this.started.compareAndSet(false, true)) {
throw new IllegalStateException("StandardFileWatchService has started");
}
- started = true;
+ logger.info("Start to watch the file system.");
FileSystem fileSystem = getDefault();
@@ -176,9 +183,32 @@ public void start() throws Exception {
}
+ public void stop() throws Exception {
+ // set the flag "started" to false
+ while (this.started.compareAndSet(true, false)) {
+ // wait for the event loop to complete
+ this.eventLoopExecutor.awaitTermination(100, MILLISECONDS);
+ // if the event loop is not done, try to cancel the task
+ this.eventLoopFuture.cancel(true);
+ }
+ }
+
+ public boolean isStarted() {
+ return this.started.get();
+ }
+
+ @Override
+ public void close() throws Exception {
+ this.stop();
+ IOUtils.close(this.watchService);
+ this.fileChangedMetadataCache.clear();
+ shutdown(this.eventLoopExecutor);
+ shutdown(this.eventHandlerExecutor);
+ }
+
private void dispatchFileChangedEvents(WatchService watchService) {
- eventLoopFuture = eventLoopExecutor.submit(() -> {
- while (started) {
+ this.eventLoopFuture = this.eventLoopExecutor.submit(() -> {
+ while (isStarted()) {
WatchKey watchKey = null;
try {
watchKey = watchService.take();
@@ -188,7 +218,8 @@ private void dispatchFileChangedEvents(WatchService watchService) {
Path dirPath = (Path) watchable;
Path fileRelativePath = (Path) event.context();
- FileChangedMetadata metadata = fileChangedMetadataCache.get(dirPath);
+ FileChangedMetadata metadata = this.fileChangedMetadataCache.get(dirPath);
+
if (metadata != null) {
Path filePath = dirPath.resolve(fileRelativePath);
if (isDirectory(dirPath, NOFOLLOW_LINKS) || metadata.filePaths.contains(filePath)) {
@@ -214,14 +245,17 @@ private void dispatchFileChangedEvent(Path filePath, WatchEvent.Kind watchEventK
Kind kind = toKind(watchEventKind);
FileChangedEvent fileChangedEvent = new FileChangedEvent(file, kind);
eventDispatcher.dispatch(fileChangedEvent);
+ logger.trace("The {} was dispatched", fileChangedEvent);
}
private void registerDirectoriesToWatchService(WatchService watchService) throws Exception {
- for (Map.Entry entry : fileChangedMetadataCache.entrySet()) {
+ for (Map.Entry entry : this.fileChangedMetadataCache.entrySet()) {
Path directoryPath = entry.getKey();
FileChangedMetadata metadata = entry.getValue();
WatchEvent.Kind[] kinds = metadata.watchEventKinds;
directoryPath.register(watchService, kinds);
+ logger.trace("The directory[path : '{}' , event kinds : {}] registers the WatchService : {}",
+ directoryPath, arrayToString(kinds), watchService);
}
}
@@ -235,7 +269,7 @@ public void watch(File file, FileChangedListener listener, Kind... kinds) {
private FileChangedMetadata getMetadata(Path filePath, Kind... kinds) {
final Path dirPath = isDirectory(filePath, NOFOLLOW_LINKS) ? filePath : filePath.getParent();
- return fileChangedMetadataCache.computeIfAbsent(dirPath, k -> {
+ return this.fileChangedMetadataCache.computeIfAbsent(dirPath, k -> {
FileChangedMetadata metadata = new FileChangedMetadata();
metadata.eventDispatcher = parallel(this.eventHandlerExecutor);
metadata.watchEventKinds = toWatchEventKinds(kinds);
@@ -244,7 +278,7 @@ private FileChangedMetadata getMetadata(Path filePath, Kind... kinds) {
}
@Nonnull
- private WatchEvent.Kind>[] toWatchEventKinds(Kind[] kinds) {
+ static WatchEvent.Kind>[] toWatchEventKinds(Kind... kinds) {
int size = length(kinds);
if (size < 1) {
return ALL_WATCH_EVENT_KINDS;
@@ -258,8 +292,8 @@ private WatchEvent.Kind>[] toWatchEventKinds(Kind[] kinds) {
}
@Nonnull
- private WatchEvent.Kind> toWatchEventKind(Kind kind) {
- WatchEvent.Kind> watchEventKind = OVERFLOW;
+ static WatchEvent.Kind> toWatchEventKind(Kind kind) {
+ final WatchEvent.Kind> watchEventKind;
switch (kind) {
case CREATED:
watchEventKind = ENTRY_CREATE;
@@ -267,7 +301,7 @@ private WatchEvent.Kind> toWatchEventKind(Kind kind) {
case MODIFIED:
watchEventKind = ENTRY_MODIFY;
break;
- case DELETED:
+ default:
watchEventKind = ENTRY_DELETE;
break;
}
@@ -275,42 +309,21 @@ private WatchEvent.Kind> toWatchEventKind(Kind kind) {
}
@Nonnull
- private Kind toKind(WatchEvent.Kind> watchEventKind) {
+ static Kind toKind(WatchEvent.Kind> watchEventKind) {
final Kind kind;
if (ENTRY_CREATE.equals(watchEventKind)) {
kind = CREATED;
} else if (ENTRY_MODIFY.equals(watchEventKind)) {
kind = MODIFIED;
- } else {
+ } else if (ENTRY_DELETE.equals(watchEventKind)) {
kind = DELETED;
+ } else {
+ String errorMessage = format("The invalid kind of WatchEvent : {}", watchEventKind);
+ throw new IllegalArgumentException(errorMessage);
}
return kind;
}
- public void stop() throws Exception {
- if (started) {
- // set the flag "started" to false
- started = false;
- // wait for the event loop to complete
- if (!eventLoopExecutor.awaitTermination(100, TimeUnit.MILLISECONDS)) {
- // if the event loop is not done, try to cancel the task
- eventLoopFuture.cancel(true);
- }
-
- if (watchService != null) {
- watchService.close();
- }
- fileChangedMetadataCache.clear();
- shutdown(eventLoopExecutor);
- shutdown(eventHandlerExecutor);
- }
- }
-
- @Override
- public void close() throws Exception {
- this.stop();
- }
-
private static class FileChangedMetadata {
private final Set filePaths = new TreeSet<>();
@@ -320,4 +333,4 @@ private static class FileChangedMetadata {
private WatchEvent.Kind>[] watchEventKinds;
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedEvent.java b/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedEvent.java
index 086cdfe83..847efc57c 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedEvent.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedEvent.java
@@ -21,6 +21,8 @@
import java.io.File;
+import static io.microsphere.util.Assert.assertNotNull;
+
/**
* The event raised when the {@link File file} is changed
*
@@ -42,9 +44,7 @@ public class FileChangedEvent extends Event {
*/
public FileChangedEvent(File file, Kind kind) throws IllegalArgumentException {
super(file);
- if (kind == null) {
- throw new IllegalArgumentException("The 'kind' argument must not be null");
- }
+ assertNotNull(kind, () -> "The 'kind' argument must not be null");
this.kind = kind;
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedListener.java b/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedListener.java
index 53ece6b00..26bc767ed 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedListener.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/event/FileChangedListener.java
@@ -18,6 +18,7 @@
import io.microsphere.event.Event;
import io.microsphere.event.EventListener;
+import io.microsphere.io.event.FileChangedEvent.Kind;
/**
* A listener interface for receiving file change events.
@@ -94,7 +95,7 @@
public interface FileChangedListener extends EventListener {
default void onEvent(FileChangedEvent event) {
- FileChangedEvent.Kind kind = event.getKind();
+ Kind kind = event.getKind();
switch (kind) {
case CREATED:
onFileCreated(event);
@@ -102,7 +103,7 @@ default void onEvent(FileChangedEvent event) {
case MODIFIED:
onFileModified(event);
break;
- case DELETED:
+ default:
onFileDeleted(event);
break;
}
@@ -111,7 +112,7 @@ default void onEvent(FileChangedEvent event) {
/**
* Invoked when the file has been created
*
- * @param event the {@link FileChangedEvent.Kind#CREATED created} {@link FileChangedEvent event}
+ * @param event the {@link Kind#CREATED created} {@link FileChangedEvent event}
*/
default void onFileCreated(FileChangedEvent event) {
}
@@ -119,7 +120,7 @@ default void onFileCreated(FileChangedEvent event) {
/**
* Invoked when the file has been modified
*
- * @param event the {@link FileChangedEvent.Kind#MODIFIED modified} {@link FileChangedEvent event}
+ * @param event the {@link Kind#MODIFIED modified} {@link FileChangedEvent event}
*/
default void onFileModified(FileChangedEvent event) {
}
@@ -127,7 +128,7 @@ default void onFileModified(FileChangedEvent event) {
/**
* Invoked when the file has been deleted
*
- * @param event the {@link FileChangedEvent.Kind#DELETED deleted} {@link FileChangedEvent event}
+ * @param event the {@link Kind#DELETED deleted} {@link FileChangedEvent event}
*/
default void onFileDeleted(FileChangedEvent event) {
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/event/LoggingFileChangedListener.java b/microsphere-java-core/src/main/java/io/microsphere/io/event/LoggingFileChangedListener.java
index e104e361d..50077a7d5 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/event/LoggingFileChangedListener.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/event/LoggingFileChangedListener.java
@@ -67,8 +67,6 @@ public void onFileDeleted(FileChangedEvent event) {
}
private void log(FileChangedEvent event) {
- if (logger.isDebugEnabled()) {
- logger.debug(event.toString());
- }
+ logger.debug(event.toString());
}
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/filter/FileExtensionFilter.java b/microsphere-java-core/src/main/java/io/microsphere/io/filter/FileExtensionFilter.java
index 71d885d8c..6115094f6 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/filter/FileExtensionFilter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/filter/FileExtensionFilter.java
@@ -56,6 +56,8 @@
*/
public class FileExtensionFilter implements IOFileFilter {
+ private static final boolean CASE_SENSITIVE = !IS_OS_WINDOWS;
+
private final String extension;
protected FileExtensionFilter(String extension) {
@@ -75,7 +77,11 @@ public boolean accept(File file) {
return false;
}
- return IS_OS_WINDOWS ? fileExtension.equalsIgnoreCase(extension) : fileExtension.equals(extension);
+ return matches(fileExtension, CASE_SENSITIVE);
+ }
+
+ protected boolean matches(String fileExtension, boolean caseSensitive) {
+ return caseSensitive ? fileExtension.equals(extension) : fileExtension.equalsIgnoreCase(extension);
}
/**
@@ -87,4 +93,5 @@ public boolean accept(File file) {
public static FileExtensionFilter of(String extension) {
return new FileExtensionFilter(extension);
}
-}
+
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/io/filter/NameFileFilter.java b/microsphere-java-core/src/main/java/io/microsphere/io/filter/NameFileFilter.java
index 1e53e2231..c71c2032d 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/io/filter/NameFileFilter.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/io/filter/NameFileFilter.java
@@ -46,4 +46,4 @@ public boolean accept(File file) {
String name = this.name;
return caseSensitive ? fileName.equals(name) : fileName.equalsIgnoreCase(name);
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/json/JSONStringer.java b/microsphere-java-core/src/main/java/io/microsphere/json/JSONStringer.java
index 832787050..ffb062aec 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/json/JSONStringer.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/json/JSONStringer.java
@@ -21,7 +21,13 @@
import static io.microsphere.json.JSONObject.NULL;
import static io.microsphere.json.JSONObject.numberToString;
+import static io.microsphere.json.JSONStringer.Scope.DANGLING_KEY;
+import static io.microsphere.json.JSONStringer.Scope.EMPTY_ARRAY;
+import static io.microsphere.json.JSONStringer.Scope.EMPTY_OBJECT;
+import static io.microsphere.json.JSONStringer.Scope.NONEMPTY_ARRAY;
+import static io.microsphere.json.JSONStringer.Scope.NONEMPTY_OBJECT;
import static io.microsphere.util.ClassUtils.getTypeName;
+import static java.lang.String.format;
import static java.util.Arrays.fill;
/**
@@ -145,7 +151,7 @@ public JSONStringer(int indentSpaces) {
* @throws JSONException if processing of json failed
*/
public JSONStringer array() throws JSONException {
- return open(Scope.EMPTY_ARRAY, "[");
+ return open(EMPTY_ARRAY, "[");
}
/**
@@ -155,7 +161,7 @@ public JSONStringer array() throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer endArray() throws JSONException {
- return close(Scope.EMPTY_ARRAY, Scope.NONEMPTY_ARRAY, "]");
+ return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]");
}
/**
@@ -166,7 +172,7 @@ public JSONStringer endArray() throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer object() throws JSONException {
- return open(Scope.EMPTY_OBJECT, "{");
+ return open(EMPTY_OBJECT, "{");
}
/**
@@ -176,7 +182,7 @@ public JSONStringer object() throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer endObject() throws JSONException {
- return close(Scope.EMPTY_OBJECT, Scope.NONEMPTY_OBJECT, "}");
+ return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}");
}
/**
@@ -188,7 +194,7 @@ public JSONStringer endObject() throws JSONException {
* @throws JSONException if processing of json failed
*/
JSONStringer open(Scope empty, String openBracket) throws JSONException {
- if (this.stack.isEmpty() && this.out.length() > 0) {
+ if (isEmpty() && this.out.length() > 0) {
throw new JSONException("Nesting problem: multiple top-level roots");
}
beforeValue();
@@ -228,7 +234,7 @@ JSONStringer close(Scope empty, Scope nonempty, String closeBracket) throws JSON
* @throws JSONException if processing of json failed
*/
private Scope peek() throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
throw new JSONException("Nesting problem");
}
return this.stack.get(this.stack.size() - 1);
@@ -253,7 +259,7 @@ private void replaceTop(Scope topOfStack) {
* @throws JSONException if processing of json failed
*/
public JSONStringer value(Object value) throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
throw new JSONException("Nesting problem");
}
@@ -288,7 +294,7 @@ public JSONStringer value(Object value) throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer value(boolean value) throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
throw new JSONException("Nesting problem");
}
beforeValue();
@@ -305,7 +311,7 @@ public JSONStringer value(boolean value) throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer value(double value) throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
throw new JSONException("Nesting problem");
}
beforeValue();
@@ -321,7 +327,7 @@ public JSONStringer value(double value) throws JSONException {
* @throws JSONException if processing of json failed
*/
public JSONStringer value(long value) throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
throw new JSONException("Nesting problem");
}
beforeValue();
@@ -368,7 +374,7 @@ void string(String value) {
default:
if (c <= 0x1F) {
- this.out.append(String.format("\\u%04x", (int) c));
+ this.out.append(format("\\u%04x", (int) c));
} else {
this.out.append(c);
}
@@ -414,13 +420,13 @@ public JSONStringer key(String name) throws JSONException {
*/
void beforeKey() throws JSONException {
Scope context = peek();
- if (context == Scope.NONEMPTY_OBJECT) { // first in object
+ if (context == NONEMPTY_OBJECT) { // first in object
this.out.append(',');
- } else if (context != Scope.EMPTY_OBJECT) { // not in an object!
+ } else if (context != EMPTY_OBJECT) { // not in an object!
throw new JSONException("Nesting problem");
}
newline();
- replaceTop(Scope.DANGLING_KEY);
+ replaceTop(DANGLING_KEY);
}
/**
@@ -431,20 +437,20 @@ void beforeKey() throws JSONException {
* @throws JSONException if processing of json failed
*/
void beforeValue() throws JSONException {
- if (this.stack.isEmpty()) {
+ if (isEmpty()) {
return;
}
Scope context = peek();
- if (context == Scope.EMPTY_ARRAY) { // first in array
- replaceTop(Scope.NONEMPTY_ARRAY);
+ if (context == EMPTY_ARRAY) { // first in array
+ replaceTop(NONEMPTY_ARRAY);
newline();
- } else if (context == Scope.NONEMPTY_ARRAY) { // another in array
+ } else if (context == NONEMPTY_ARRAY) { // another in array
this.out.append(',');
newline();
- } else if (context == Scope.DANGLING_KEY) { // value for key
+ } else if (context == DANGLING_KEY) { // value for key
this.out.append(this.indent == null ? ":" : ": ");
- replaceTop(Scope.NONEMPTY_OBJECT);
+ replaceTop(NONEMPTY_OBJECT);
} else if (context != Scope.NULL) {
throw new JSONException("Nesting problem");
}
@@ -466,4 +472,7 @@ public String toString() {
return this.out.length() == 0 ? null : this.out.toString();
}
+ boolean isEmpty() {
+ return this.stack.isEmpty();
+ }
}
diff --git a/microsphere-java-core/src/main/java/io/microsphere/json/JSONTokener.java b/microsphere-java-core/src/main/java/io/microsphere/json/JSONTokener.java
index ac6e4318a..f17066c58 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/json/JSONTokener.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/json/JSONTokener.java
@@ -19,6 +19,10 @@
import static io.microsphere.json.JSONObject.NULL;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
+import static java.lang.Double.valueOf;
+import static java.lang.Integer.MAX_VALUE;
+import static java.lang.Integer.MIN_VALUE;
+import static java.lang.Long.parseLong;
/**
* Parses a JSON (RFC 4627) encoded
@@ -117,8 +121,8 @@ public Object nextValue() throws JSONException {
}
int nextCleanInternal() throws JSONException {
- while (this.pos < this.in.length()) {
- int c = this.in.charAt(this.pos++);
+ while (hasNext()) {
+ int c = nextChar();
switch (c) {
case '\t':
case ' ':
@@ -131,7 +135,7 @@ int nextCleanInternal() throws JSONException {
return c;
}
- char peek = this.in.charAt(this.pos);
+ char peek = currentChar();
switch (peek) {
case '*':
// skip a /* c-style comment */
@@ -175,8 +179,8 @@ int nextCleanInternal() throws JSONException {
* terminated by "\r\n", the '\n' must be consumed as whitespace by the caller.
*/
void skipToEndOfLine() {
- for (; this.pos < this.in.length(); this.pos++) {
- char c = this.in.charAt(this.pos);
+ for (; hasNext(); this.pos++) {
+ char c = currentChar();
if (c == '\r' || c == '\n') {
this.pos++;
break;
@@ -206,8 +210,8 @@ public String nextString(char quote) throws JSONException {
/* the index of the first character not yet appended to the builder. */
int start = this.pos;
- while (this.pos < this.in.length()) {
- int c = this.in.charAt(this.pos++);
+ while (hasNext()) {
+ int c = nextChar();
if (c == quote) {
if (builder == null) {
// a new string avoids leaking memory
@@ -244,7 +248,7 @@ public String nextString(char quote) throws JSONException {
* @throws JSONException if processing of json failed
*/
char readEscapeCharacter() throws JSONException {
- char escaped = this.in.charAt(this.pos++);
+ char escaped = nextChar();
switch (escaped) {
case 'u':
if (this.pos + 4 > this.in.length()) {
@@ -309,8 +313,8 @@ public Object readLiteral() throws JSONException {
base = 8;
}
try {
- long longValue = Long.parseLong(number, base);
- if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
+ long longValue = parseLong(number, base);
+ if (longValue <= MAX_VALUE && longValue >= MIN_VALUE) {
return (int) longValue;
} else {
return longValue;
@@ -326,7 +330,7 @@ public Object readLiteral() throws JSONException {
/* ...next try to parse as a floating point... */
try {
- return Double.valueOf(literal);
+ return valueOf(literal);
} catch (NumberFormatException ignored) {
}
@@ -343,8 +347,8 @@ public Object readLiteral() throws JSONException {
*/
String nextToInternal(String excluded) {
int start = this.pos;
- for (; this.pos < this.in.length(); this.pos++) {
- char c = this.in.charAt(this.pos);
+ for (; hasNext(); this.pos++) {
+ char c = currentChar();
if (c == '\r' || c == '\n' || excluded.indexOf(c) != -1) {
return this.in.substring(start, this.pos);
}
@@ -389,7 +393,7 @@ public JSONObject readObject() throws JSONException {
if (separator != ':' && separator != '=') {
throw syntaxError("Expected ':' after " + name);
}
- if (this.pos < this.in.length() && this.in.charAt(this.pos) == '>') {
+ if (hasNext() && currentChar() == '>') {
this.pos++;
}
@@ -486,11 +490,15 @@ public String toString() {
*/
public boolean more() {
- return this.pos < this.in.length();
+ return hasNext();
}
public char next() {
- return this.pos < this.in.length() ? this.in.charAt(this.pos++) : '\0';
+ return hasNext() ? nextChar() : '\0';
+ }
+
+ public boolean hasNext() {
+ return this.pos < this.in.length();
}
public char next(char c) throws JSONException {
@@ -547,6 +555,18 @@ public void back() {
}
}
+ char currentChar() {
+ return charAt(this.pos);
+ }
+
+ char nextChar() {
+ return charAt(this.pos++);
+ }
+
+ char charAt(int pos) {
+ return this.in.charAt(pos);
+ }
+
public static int dehexchar(char hex) {
if (hex >= '0' && hex <= '9') {
return hex - '0';
@@ -559,4 +579,4 @@ public static int dehexchar(char hex) {
}
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/lang/ClassDataRepository.java b/microsphere-java-core/src/main/java/io/microsphere/lang/ClassDataRepository.java
index 05961ed23..812b135ff 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/lang/ClassDataRepository.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/lang/ClassDataRepository.java
@@ -21,11 +21,6 @@
import io.microsphere.annotation.Nullable;
import io.microsphere.util.ClassPathUtils;
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.security.CodeSource;
-import java.security.ProtectionDomain;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
@@ -38,7 +33,6 @@
import static io.microsphere.util.ClassPathUtils.getClassPaths;
import static io.microsphere.util.ClassUtils.findClassNamesInClassPath;
import static io.microsphere.util.ClassUtils.resolvePackageName;
-import static io.microsphere.util.StringUtils.isNotBlank;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
@@ -94,9 +88,6 @@ public class ClassDataRepository {
private final Map> packageNameToClassNamesMap = initPackageNameToClassNamesMap();
- private ClassDataRepository() {
- }
-
/**
* Get all package names in {@link ClassPathUtils#getClassPaths() class paths}
*
@@ -199,35 +190,6 @@ public Set getAllClassNamesInClassPaths() {
return unmodifiableSet(allClassNames);
}
- /**
- * Get {@link Class}'s code source location URL
- *
- * @param type
- * @return If , return null.
- * @throws NullPointerException If type is null , {@link NullPointerException} will be thrown.
- */
- public URL getCodeSourceLocation(Class> type) throws NullPointerException {
-
- URL codeSourceLocation = null;
- ClassLoader classLoader = type.getClassLoader();
-
- if (classLoader == null) { // Bootstrap ClassLoader or type is primitive or void
- String path = findClassPath(type);
- if (isNotBlank(path)) {
- try {
- codeSourceLocation = new File(path).toURI().toURL();
- } catch (MalformedURLException ignored) {
- codeSourceLocation = null;
- }
- }
- } else {
- ProtectionDomain protectionDomain = type.getProtectionDomain();
- CodeSource codeSource = protectionDomain == null ? null : protectionDomain.getCodeSource();
- codeSourceLocation = codeSource == null ? null : codeSource.getLocation();
- }
- return codeSourceLocation;
- }
-
@Nonnull
@Immutable
private Map> initClassPathToClassNamesMap() {
@@ -280,4 +242,7 @@ private Map> initPackageNameToClassNamesMap() {
return unmodifiableMap(packageNameToClassNamesMap);
}
-}
+
+ private ClassDataRepository() {
+ }
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/lang/Deprecation.java b/microsphere-java-core/src/main/java/io/microsphere/lang/Deprecation.java
index a19eb0a01..135c872e8 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/lang/Deprecation.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/lang/Deprecation.java
@@ -26,6 +26,7 @@
import static io.microsphere.constants.SymbolConstants.QUOTE_CHAR;
import static io.microsphere.lang.Deprecation.Level.DEFAULT;
+import static io.microsphere.util.Assert.assertNotNull;
import static java.util.Objects.hash;
/**
@@ -96,12 +97,13 @@ public final class Deprecation implements Serializable {
}
Deprecation(@Nullable Version since, @Nullable String replacement, @Nullable String reason,
- @Nullable String link, @Nullable Level level) {
+ @Nullable String link, @Nonnull Level level) {
+ assertNotNull(level, () -> "the 'level' must not be null");
this.since = since;
this.replacement = replacement;
this.reason = reason;
this.link = link;
- this.level = level == null ? DEFAULT : level;
+ this.level = level;
}
@Nullable
@@ -129,10 +131,14 @@ public Level getLevel() {
return level;
}
-
@Override
public boolean equals(Object o) {
- if (!(o instanceof Deprecation)) return false;
+ if (o == this) {
+ return true;
+ }
+ if (!(o instanceof Deprecation)) {
+ return false;
+ }
Deprecation that = (Deprecation) o;
return Objects.equals(since, that.since)
&& Objects.equals(replacement, that.replacement)
@@ -270,4 +276,4 @@ public static Deprecation of(String since, String replacement, String reason, St
.level(level)
.build();
}
-}
+}
\ No newline at end of file
diff --git a/microsphere-java-core/src/main/java/io/microsphere/lang/Prioritized.java b/microsphere-java-core/src/main/java/io/microsphere/lang/Prioritized.java
index b8a94072c..b369e3840 100644
--- a/microsphere-java-core/src/main/java/io/microsphere/lang/Prioritized.java
+++ b/microsphere-java-core/src/main/java/io/microsphere/lang/Prioritized.java
@@ -61,15 +61,18 @@ public interface Prioritized extends Comparable {
Comparator