Skip to content

Commit c67d254

Browse files
committed
Clean up PropertyEnvironment
We clean up `PropertyEnvironment` from all the unused public methods. Since all the classes should only use `getProperty(Class)`, the other converter methods are not necessary. We keep `getStringProperty` (renamed to `getProperty(String)`) for convenience: this allows to transform a `PropertyEnvironment` into a `PropertySource`.
1 parent 9d0b681 commit c67d254

File tree

19 files changed

+62
-610
lines changed

19 files changed

+62
-610
lines changed

log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NamedLoggerContextPropertiesTest.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,11 @@
2525
import org.apache.logging.log4j.core.config.Configuration;
2626
import org.apache.logging.log4j.core.selector.BasicContextSelector;
2727
import org.apache.logging.log4j.core.test.junit.ContextSelectorType;
28+
import org.apache.logging.log4j.kit.env.Log4jProperty;
2829
import org.apache.logging.log4j.kit.env.PropertyEnvironment;
2930
import org.apache.logging.log4j.plugins.Inject;
3031
import org.apache.logging.log4j.plugins.di.ConfigurableInstanceFactory;
32+
import org.jspecify.annotations.Nullable;
3133
import org.junit.jupiter.api.Test;
3234
import org.junitpioneer.jupiter.DisabledUntil;
3335

@@ -43,7 +45,7 @@ public void testProperties() {
4345
assertEquals(LifeCycle.State.STARTED, context.getState());
4446
final PropertyEnvironment props = context.getEnvironment();
4547
assertNotNull(props, "Logger Context Properties were not loaded");
46-
final String scriptLanguages = props.getStringProperty("Script.enableLanguages");
48+
final String scriptLanguages = props.getProperty(Script.class).enableLanguages();
4749
assertEquals("Groovy,JavaScript", scriptLanguages);
4850
final Configuration config = context.getConfiguration();
4951
assertNotNull(config, "Configuration was not created");
@@ -52,6 +54,9 @@ public void testProperties() {
5254
assertEquals(LifeCycle.State.STOPPED, context.getState());
5355
}
5456

57+
@Log4jProperty
58+
private record Script(@Nullable String enableLanguages) {}
59+
5560
public static class TestContextSelector extends BasicContextSelector {
5661

5762
@Inject

log4j-core/src/main/java/org/apache/logging/log4j/core/util/OptionConverter.java

+1-91
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
*/
1717
package org.apache.logging.log4j.core.util;
1818

19-
import static org.apache.logging.log4j.util.Strings.toRootUpperCase;
20-
2119
import java.io.InterruptedIOException;
2220
import java.util.ArrayList;
2321
import java.util.List;
@@ -40,23 +38,12 @@ public final class OptionConverter {
4038
private static final char DELIM_STOP = '}';
4139
private static final int DELIM_START_LEN = 2;
4240
private static final int DELIM_STOP_LEN = 1;
43-
private static final int ONE_K = 1024;
4441

4542
/**
4643
* OptionConverter is a static class.
4744
*/
4845
private OptionConverter() {}
4946

50-
public static String[] concatenateArrays(final String[] l, final String[] r) {
51-
final int len = l.length + r.length;
52-
final String[] a = new String[len];
53-
54-
System.arraycopy(l, 0, a, 0, l.length);
55-
System.arraycopy(r, 0, a, l.length, r.length);
56-
57-
return a;
58-
}
59-
6047
public static String convertSpecialChars(final String s) {
6148
char c;
6249
final int len = s.length();
@@ -114,49 +101,6 @@ public static Object instantiateByKey(
114101
return OptionConverter.instantiateByClassName(className.trim(), superClass, defaultValue);
115102
}
116103

117-
/**
118-
* If <code>value</code> is "true", then {@code true} is
119-
* returned. If <code>value</code> is "false", then
120-
* {@code false} is returned. Otherwise, <code>default</code> is
121-
* returned.
122-
*
123-
* <p>Case of value is unimportant.</p>
124-
* @param value The value to convert.
125-
* @param defaultValue The default value.
126-
* @return true or false, depending on the value and/or default.
127-
*/
128-
public static boolean toBoolean(final String value, final boolean defaultValue) {
129-
if (value == null) {
130-
return defaultValue;
131-
}
132-
final String trimmedVal = value.trim();
133-
if ("true".equalsIgnoreCase(trimmedVal)) {
134-
return true;
135-
}
136-
if ("false".equalsIgnoreCase(trimmedVal)) {
137-
return false;
138-
}
139-
return defaultValue;
140-
}
141-
142-
/**
143-
* Convert the String value to an int.
144-
* @param value The value as a String.
145-
* @param defaultValue The default value.
146-
* @return The value as an int.
147-
*/
148-
public static int toInt(final String value, final int defaultValue) {
149-
if (value != null) {
150-
final String s = value.trim();
151-
try {
152-
return Integer.parseInt(s);
153-
} catch (final NumberFormatException e) {
154-
LOGGER.error("[{}] is not in proper int form.", s, e);
155-
}
156-
}
157-
return defaultValue;
158-
}
159-
160104
public static Level toLevel(String value, Level defaultValue) {
161105
if (value == null) {
162106
return defaultValue;
@@ -220,40 +164,6 @@ public static Level toLevel(String value, Level defaultValue) {
220164
return result;
221165
}
222166

223-
/**
224-
*
225-
* @param value The size of the file as a String.
226-
* @param defaultValue The default value.
227-
* @return The size of the file as a long.
228-
*/
229-
public static long toFileSize(final String value, final long defaultValue) {
230-
if (value == null) {
231-
return defaultValue;
232-
}
233-
234-
String str = toRootUpperCase(value.trim());
235-
long multiplier = 1;
236-
int index;
237-
238-
if ((index = str.indexOf("KB")) != -1) {
239-
multiplier = ONE_K;
240-
str = str.substring(0, index);
241-
} else if ((index = str.indexOf("MB")) != -1) {
242-
multiplier = ONE_K * ONE_K;
243-
str = str.substring(0, index);
244-
} else if ((index = str.indexOf("GB")) != -1) {
245-
multiplier = ONE_K * ONE_K * ONE_K;
246-
str = str.substring(0, index);
247-
}
248-
try {
249-
return Long.parseLong(str) * multiplier;
250-
} catch (final NumberFormatException e) {
251-
LOGGER.error("[{}] is not in proper int form.", str);
252-
LOGGER.error("[{}] not in expected format.", value, e);
253-
}
254-
return defaultValue;
255-
}
256-
257167
/**
258168
* Find the value corresponding to <code>key</code> in
259169
* <code>props</code>. Then perform variable substitution on the
@@ -380,7 +290,7 @@ private static String substVars(final String val, final Properties props, final
380290
j += DELIM_START_LEN;
381291
final String key = val.substring(j, k);
382292
// first try in System properties
383-
String replacement = PropertyEnvironment.getGlobal().getStringProperty(key, null);
293+
String replacement = PropertyEnvironment.getGlobal().getProperty(key);
384294
// then try props parameter
385295
if (replacement == null && props != null) {
386296
replacement = props.getProperty(key);

log4j-core/src/main/java/org/apache/logging/log4j/core/util/UuidUtil.java

+4-5
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import java.util.Random;
2222
import java.util.UUID;
2323
import java.util.concurrent.atomic.AtomicInteger;
24-
import org.apache.logging.log4j.core.impl.CoreProperties;
24+
import org.apache.logging.log4j.core.impl.CoreProperties.UuidProperties;
2525
import org.apache.logging.log4j.kit.env.PropertyEnvironment;
2626

2727
/**
@@ -37,9 +37,8 @@ public final class UuidUtil {
3737
private static final byte VARIANT = (byte) 0x80;
3838
private static final int SEQUENCE_MASK = 0x3FFF;
3939
private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
40-
private static final long INITIAL_UUID_SEQNO = PropertyEnvironment.getGlobal()
41-
.getProperty(CoreProperties.UuidProperties.class)
42-
.sequence();
40+
private static final long INITIAL_UUID_SEQNO =
41+
PropertyEnvironment.getGlobal().getProperty(UuidProperties.class).sequence();
4342

4443
private static final long LOW_MASK = 0xffffffffL;
4544
private static final long MID_MASK = 0xffff00000000L;
@@ -78,7 +77,7 @@ static long initialize(byte[] mac) {
7877
System.arraycopy(mac, index, node, 2, length);
7978
final ByteBuffer buf = ByteBuffer.wrap(node);
8079
long rand = INITIAL_UUID_SEQNO;
81-
String assigned = PropertyEnvironment.getGlobal().getStringProperty(ASSIGNED_SEQUENCES);
80+
String assigned = System.getProperty(ASSIGNED_SEQUENCES);
8281
final long[] sequences;
8382
if (assigned == null) {
8483
sequences = new long[0];

log4j-docker/src/main/java/org/apache/logging/log4j/docker/DockerLookup.java

+6-9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import com.fasterxml.jackson.core.type.TypeReference;
2020
import com.fasterxml.jackson.databind.ObjectMapper;
2121
import java.io.IOException;
22+
import java.net.URI;
2223
import java.net.URL;
2324
import java.util.List;
2425
import java.util.Map;
@@ -41,32 +42,28 @@
4142
public class DockerLookup extends AbstractLookup {
4243

4344
private static final Logger LOGGER = StatusLogger.getLogger();
44-
private static final String DOCKER_URI = "DOCKER_URI";
4545
private static final String HTTP = "http";
4646
private final Container container;
4747

4848
/**
4949
* Constructs a new instance.
5050
*/
5151
public DockerLookup() {
52-
String baseUri = System.getenv(DOCKER_URI);
53-
if (baseUri == null) {
54-
final PropertyEnvironment props = PropertyEnvironment.getGlobal();
55-
baseUri = props.getStringProperty(DOCKER_URI);
56-
}
52+
final URI baseUri = PropertyEnvironment.getGlobal()
53+
.getProperty(DockerProperties.class)
54+
.uri();
5755
if (baseUri == null) {
5856
LOGGER.warn("No Docker URI provided. Docker information is unavailable");
5957
container = null;
6058
return;
6159
}
6260
Container current = null;
6361
try {
64-
final URL url = new URL(baseUri + "/containers/json");
62+
final URL url = baseUri.resolve("/containers/json").toURL();
6563
if (url.getProtocol().equals(HTTP)) {
6664
final String macAddr = NetUtils.getMacAddressString();
6765
final ObjectMapper objectMapper = new ObjectMapper();
68-
final List<Container> containerList =
69-
objectMapper.readValue(url, new TypeReference<List<Container>>() {});
66+
final List<Container> containerList = objectMapper.readValue(url, new TypeReference<>() {});
7067

7168
for (final Container container : containerList) {
7269
if (macAddr != null && container.getNetworkSettings() != null) {

log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/condition/ConditionalOnProperty.java log4j-docker/src/main/java/org/apache/logging/log4j/docker/DockerProperties.java

+8-18
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,15 @@
1414
* See the License for the specific language governing permissions and
1515
* limitations under the License.
1616
*/
17-
package org.apache.logging.log4j.plugins.condition;
17+
package org.apache.logging.log4j.docker;
1818

19-
import java.lang.annotation.Documented;
20-
import java.lang.annotation.ElementType;
21-
import java.lang.annotation.Retention;
22-
import java.lang.annotation.RetentionPolicy;
23-
import java.lang.annotation.Target;
19+
import java.net.URI;
20+
import org.apache.logging.log4j.kit.env.Log4jProperty;
21+
import org.jspecify.annotations.Nullable;
2422

2523
/**
26-
* Checks if a Log4j property is present or matches a specific non-empty value.
24+
* Properties for the Docker lookup.
25+
* @param uri
2726
*/
28-
@Retention(RetentionPolicy.RUNTIME)
29-
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.METHOD})
30-
@Documented
31-
@Conditional(OnPropertyCondition.class)
32-
public @interface ConditionalOnProperty {
33-
String name();
34-
35-
String value() default "";
36-
37-
boolean matchIfMissing() default false;
38-
}
27+
@Log4jProperty(name = "docker")
28+
public record DockerProperties(@Nullable URI uri) {}

log4j-flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeEmbeddedManager.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import static org.apache.logging.log4j.util.Strings.toRootUpperCase;
2020

2121
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22+
import java.io.File;
2223
import java.security.MessageDigest;
2324
import java.security.NoSuchAlgorithmException;
2425
import java.util.HashMap;
@@ -31,13 +32,11 @@
3132
import org.apache.logging.log4j.core.appender.ManagerFactory;
3233
import org.apache.logging.log4j.core.config.ConfigurationException;
3334
import org.apache.logging.log4j.core.config.Property;
34-
import org.apache.logging.log4j.kit.env.PropertyEnvironment;
3535
import org.apache.logging.log4j.util.Strings;
3636

3737
public class FlumeEmbeddedManager extends AbstractFlumeManager {
3838

39-
private static final String FILE_SEP = PropertyEnvironment.getGlobal().getStringProperty("file.separator");
40-
39+
private static final String FILE_SEP = File.separator;
4140
private static final String IN_MEMORY = "InMemory";
4241

4342
private static final FlumeManagerFactory FACTORY = new FlumeManagerFactory();

log4j-jndi/src/main/java/org/apache/logging/log4j/jndi/lookup/JndiLookup.java

+5-10
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,13 @@
2626
import org.apache.logging.log4j.core.lookup.Lookup;
2727
import org.apache.logging.log4j.jndi.JndiManager;
2828
import org.apache.logging.log4j.plugins.Plugin;
29-
import org.apache.logging.log4j.plugins.validation.constraints.RequiredProperty;
3029
import org.apache.logging.log4j.status.StatusLogger;
3130

3231
/**
3332
* Looks up keys from JNDI resources.
3433
*/
3534
@Lookup
3635
@Plugin("jndi")
37-
@RequiredProperty(
38-
name = "jndi.enableLookup",
39-
value = "true",
40-
message = "JNDI must be enabled by setting jndi.enableLookup=true")
4136
public class JndiLookup extends AbstractLookup {
4237

4338
private static final Logger LOGGER = StatusLogger.getLogger();
@@ -46,13 +41,13 @@ public class JndiLookup extends AbstractLookup {
4641
/** JNDI resource path prefix used in a J2EE container */
4742
static final String CONTAINER_JNDI_RESOURCE_PATH_PREFIX = "java:comp/env/";
4843

44+
private final boolean disabled;
45+
4946
/**
50-
* Constructs a new instance or throw IllegalStateException if this feature is disabled.
47+
* Constructs a new instance.
5148
*/
5249
public JndiLookup() {
53-
if (!JndiManager.isJndiLookupEnabled()) {
54-
throw new IllegalStateException("JNDI must be enabled by setting log4j2.enableJndiLookup=true");
55-
}
50+
this.disabled = !JndiManager.isJndiLookupEnabled();
5651
}
5752

5853
/**
@@ -64,7 +59,7 @@ public JndiLookup() {
6459
*/
6560
@Override
6661
public String lookup(final LogEvent event, final String key) {
67-
if (key == null) {
62+
if (disabled || key == null) {
6863
return null;
6964
}
7065
final String jndiName = convertJndiName(key);

0 commit comments

Comments
 (0)