forked from tronprotocol/java-tron
-
Notifications
You must be signed in to change notification settings - Fork 1
refactor(config): merge config files with BeanDefaults fallback #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
317787106
wants to merge
10
commits into
hotfix/restrict_jsonrpc_size
Choose a base branch
from
hotfix/fix_dup_config
base: hotfix/restrict_jsonrpc_size
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c8b53b6
optimize config file
317787106 afea1c9
format code
317787106 418cb61
chore: merge develop into hotfix/fix_dup_config
317787106 7de92be
add stripNullLeaves to auto binding; simply binding not compatible va…
317787106 650e8e1
add userSection; resolve the priority of allowShieldedTransactionApi
317787106 7dd0137
optimize BeanDefaults
317787106 2e44a07
merge develop
317787106 627b85d
merge develop
317787106 86f8d74
fix bug of BeanDefaultsTest
317787106 f8850be
merge hotfix/restrict_jsonrpc_size
317787106 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
common/src/main/java/org/tron/core/config/BeanDefaults.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| package org.tron.core.config; | ||
|
|
||
| import com.typesafe.config.Config; | ||
| import com.typesafe.config.ConfigFactory; | ||
| import com.typesafe.config.ConfigObject; | ||
| import com.typesafe.config.ConfigValue; | ||
| import com.typesafe.config.ConfigValueType; | ||
| import java.beans.BeanInfo; | ||
| import java.beans.Introspector; | ||
| import java.beans.PropertyDescriptor; | ||
| import java.lang.reflect.Method; | ||
| import java.util.ArrayList; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Generates a Typesafe {@link Config} from a bean instance's current field values. | ||
| * | ||
| * <p>Used by each {@code XxxConfig.fromConfig()} to replace the role that | ||
| * {@code reference.conf} played: ensures every key ConfigBeanFactory needs is | ||
| * present, so a partial user config works without throwing | ||
| * {@code ConfigException.Missing}. | ||
| * | ||
| * <p>Only public getter+setter pairs (standard JavaBean properties) are included — | ||
| * the same set that {@code ConfigBeanFactory.create()} auto-binds. Keys are | ||
| * decapitalized exactly as ConfigBeanFactory does: | ||
| * {@code Character.toLowerCase(name.charAt(0)) + name.substring(1)}. | ||
| * | ||
| * <p>Nested bean fields are recursed into nested HOCON objects. | ||
| * {@code List} fields are serialized as HOCON lists (empty by default). | ||
| * Fields with no public setter (e.g. {@code @Getter(AccessLevel.NONE)} overrides) | ||
| * are automatically skipped — these are handled manually in each | ||
| * {@code fromConfig()} via {@code hasPath} guards. | ||
| */ | ||
| public final class BeanDefaults { | ||
|
|
||
| private BeanDefaults() {} | ||
|
|
||
| /** | ||
| * Convert {@code bean}'s public JavaBean properties to a Typesafe Config. | ||
| * The resulting Config can be used as a {@code withFallback()} for a user's | ||
| * config section to guarantee all keys are present for ConfigBeanFactory. | ||
| */ | ||
| public static Config toConfig(Object bean) { | ||
| return ConfigFactory.parseMap(toMap(bean)); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a copy of {@code config} with all null-valued leaf paths removed. | ||
| * Call this on a user-supplied config section before {@link Config#withFallback} | ||
| * so that HOCON {@code null} entries in legacy configs do not shadow bean defaults. | ||
| * | ||
| * <p>Uses {@link ConfigObject#entrySet()} (not {@link Config#entrySet()}) because | ||
| * the latter silently excludes null values, making them impossible to detect. | ||
| */ | ||
| public static Config stripNullLeaves(Config config) { | ||
| return stripNullObject(config.root()).toConfig(); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a copy of {@code config} where the value at {@code fromKey} is moved to | ||
| * {@code toKey}, leaving the original key absent. If {@code fromKey} is absent, the | ||
| * config is returned unchanged. Use this in {@code fromConfig()} to bridge config keys | ||
| * that violate JavaBean naming (e.g. {@code pBFTExpireNum} → {@code PBFTExpireNum}) so | ||
| * that {@code ConfigBeanFactory} finds the value under the key it derives from the setter. | ||
| */ | ||
| public static Config remapKey(Config config, String fromKey, String toKey) { | ||
| if (!config.hasPath(fromKey)) { | ||
| return config; | ||
| } | ||
| return config.withValue(toKey, config.getValue(fromKey)).withoutPath(fromKey); | ||
| } | ||
|
|
||
| private static ConfigObject stripNullObject(ConfigObject obj) { | ||
| ConfigObject result = obj; | ||
| for (Map.Entry<String, ConfigValue> entry : obj.entrySet()) { | ||
| ConfigValue v = entry.getValue(); | ||
| if (v.valueType() == ConfigValueType.NULL) { | ||
| result = result.withoutKey(entry.getKey()); | ||
| } else if (v.valueType() == ConfigValueType.OBJECT) { | ||
| result = result.withValue(entry.getKey(), stripNullObject((ConfigObject) v)); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| private static Map<String, Object> toMap(Object bean) { | ||
| Map<String, Object> map = new LinkedHashMap<>(); | ||
| BeanInfo info; | ||
| try { | ||
| info = Introspector.getBeanInfo(bean.getClass()); | ||
| } catch (java.beans.IntrospectionException e) { | ||
| // Programming error: bean class does not conform to JavaBean spec. | ||
| // Propagate immediately so the misconfigured class is identified at startup, | ||
| // rather than returning a silent empty map that produces a confusing | ||
| // ConfigException.Missing pointing at the user config. | ||
| throw new IllegalStateException("Cannot introspect bean: " + bean.getClass().getName(), e); | ||
| } | ||
| for (PropertyDescriptor pd : info.getPropertyDescriptors()) { | ||
| Method getter = pd.getReadMethod(); | ||
| Method setter = pd.getWriteMethod(); | ||
| // Skip read-only properties (no setter) — matches ConfigBeanFactory's contract | ||
| if (getter == null || setter == null) { | ||
| continue; | ||
| } | ||
| // Use the property name exactly as Introspector produced it. | ||
| // ConfigBeanFactory does configProps.get(beanProp.getName()) — the lookup key | ||
| // is the property name verbatim, not decapitalized. For ordinary camelCase | ||
| // setters (setMaxConnections → "MaxConnections" → decapitalize → "maxConnections") | ||
| // Introspector already returns the lowercase form. For setters that start with | ||
| // two consecutive uppercase letters (setPBFTEnable → "PBFTEnable") the JavaBean | ||
| // spec forbids decapitalization, so pd.getName() == "PBFTEnable" — matching the | ||
| // capital-P key that config.conf uses for those fields. | ||
| try { | ||
| String key = pd.getName(); | ||
| Object value = getter.invoke(bean); | ||
| map.put(key, toValue(value)); | ||
| } catch (Exception ignored) { | ||
| // Best-effort: skip individual unresolvable property so that the rest of | ||
| // the defaults are still emitted. getter.invoke() is the only realistic | ||
| // throw site (InvocationTargetException / IllegalAccessException). | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| return map; | ||
| } | ||
|
|
||
| private static Object toValue(Object value) { | ||
| if (value == null) { | ||
| return ""; | ||
| } | ||
| if (value instanceof Boolean || value instanceof Number || value instanceof String) { | ||
| return value; | ||
| } | ||
| if (value instanceof List) { | ||
| List<Object> list = new ArrayList<>(); | ||
| for (Object item : (List<?>) value) { | ||
| list.add(toValue(item)); | ||
| } | ||
| return list; | ||
| } | ||
| // Assume nested bean — recurse so it becomes a nested HOCON object. | ||
| return toMap(value); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -48,10 +48,11 @@ public static com.typesafe.config.Config getByFileName( | |||||||
|
|
||||||||
| private static void resolveConfigFile(String fileName, File confFile) { | ||||||||
| if (confFile.exists()) { | ||||||||
| config = ConfigFactory.parseFile(confFile) | ||||||||
| .withFallback(ConfigFactory.defaultReference()); | ||||||||
| config = ConfigFactory.parseFile(confFile); | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Prompt for AI agents
Suggested change
|
||||||||
| } else if (Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) | ||||||||
| != null) { | ||||||||
| // ConfigFactory.load merges system properties (higher priority than the file), | ||||||||
| // which tests rely on to override storage.db.engine via -D flags. | ||||||||
| config = ConfigFactory.load(fileName); | ||||||||
| } else { | ||||||||
| throw new IllegalArgumentException( | ||||||||
|
|
||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: remapKey should not overwrite an already-present canonical key; legacy key remapping currently changes user precedence when both keys are set.
Prompt for AI agents
Tip: Review your code locally with the cubic CLI to iterate faster.