Skip to content
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

Code style-Optimize some code structures to improve readability #5293

Merged
merged 3 commits into from
Dec 14, 2024

Conversation

youngzil
Copy link
Contributor

@youngzil youngzil commented Dec 10, 2024

What's the purpose of this PR

  1. Add @Override to the method in the implementation class
  2. Modify the equals compare method
  3. Use an empty collection instead of null return value

Which issue(s) this PR fixes:

Fixes #

Brief changelog

Follow this checklist to help us incorporate your contribution quickly and easily:

  • Read the Contributing Guide before making this pull request.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Write necessary unit tests to verify the code.
  • Run mvn clean test to make sure this pull request doesn't break anything.
  • Update the CHANGES log.

Summary by CodeRabbit

  • New Features

    • Enhanced user identification and management with the introduction of a default user ID constant.
  • Bug Fixes

    • Improved null safety in various methods across multiple classes by using safer comparison methods and returning empty lists instead of null.
  • Documentation

    • Added toString() methods in several entity classes, improving string representation for debugging and logging.
  • Refactor

    • Annotated methods with @Override in various classes to clarify intent and improve readability.
  • Chores

    • Updated method return values to ensure consistent handling of empty cases across the application.

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Dec 10, 2024
Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between dc1bcb2 and 8c177dd.

📒 Files selected for processing (25)
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiJpaImpl.java (1 hunks)
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiNoOpImpl.java (2 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Audit.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Cluster.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Item.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Privilege.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ReleaseHistory.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ServerConfig.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/DatabaseServiceRegistryImpl.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/configuration/support/ApolloServiceRegistryProperties.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/utils/ReleaseMessageKeyGenerator.java (2 hunks)
  • apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/utils/ReleaseKeyGeneratorTest.java (1 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/ApolloDataSourceScriptDatabaseInitializerFactory.java (2 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/App.java (1 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/AppNamespace.java (1 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/BaseEntity.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/PortalSettings.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/RestTemplateFactory.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java (2 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRoleInitializationService.java (6 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java (9 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java (1 hunks)
 ___________________________________________________________________________________________________________________________________
< Finish what you start. Where possible, the routine or object that allocates a resource should be responsible for deallocating it. >
 -----------------------------------------------------------------------------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ

Walkthrough

The pull request introduces several modifications across various classes in the Apollo framework. Key changes include enhancing null safety in string comparisons, updating method return values from null to Collections.emptyList(), and adding toString() method overrides for better string representation of objects. Additionally, several methods are annotated with @Override to clarify their implementation from interfaces. These changes aim to improve error handling, maintainability, and the robustness of the codebase.

Changes

File Path Change Summary
apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiJpaImpl.java Modified appendDataInfluences method to use Objects.equals(tableName, "") for null-safe comparison of tableName.
apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiNoOpImpl.java Updated multiple methods to return Collections.emptyList() instead of null (e.g., queryLogs, queryLogsByOpName, etc.).
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Audit.java Added public String toString() method to provide a string representation of the Audit object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Cluster.java Added public String toString() method to provide a string representation of the Cluster object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Item.java Added public String toString() method to provide a string representation of the Item object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java Added @Override public String toString() method to provide a string representation of the Namespace object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Privilege.java Added public String toString() method to provide a string representation of the Privilege object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java Added public String toString() method to provide a string representation of the Release object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ReleaseHistory.java Added public String toString() method to provide a string representation of the ReleaseHistory object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ServerConfig.java Added public String toString() method to provide a string representation of the ServerConfig object.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/DatabaseServiceRegistryImpl.java Added @Override annotation to register and deregister methods.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/configuration/support/ApolloServiceRegistryProperties.java Added @Override annotation to getServiceName() method.
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/utils/ReleaseMessageKeyGenerator.java Updated messageToList method to return Collections.emptyList() instead of null for invalid formats.
apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/ApolloDataSourceScriptDatabaseInitializerFactory.java Modified convertRepositoryLocations method to return Collections.emptyList() instead of null for empty input locations.
apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/App.java Added @Override public String toString() method to provide a string representation of the App object.
apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/AppNamespace.java Added public String toString() method to provide a string representation of the AppNamespace object.
apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/BaseEntity.java Added public String toString() method to provide a string representation of the BaseEntity object.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/PortalSettings.java Added @Override annotation to run method in HealthCheckTask class.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/RestTemplateFactory.java Added methods to implement FactoryBean interface and initialized RestTemplate.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java Updated isValidVersion method to use Objects.equals() for null-safe version comparison.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java Added public String toString() method to provide a string representation of the ServerConfig object.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRoleInitializationService.java Added @Override annotations to multiple methods implementing RoleInitializationService.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java Added @Override annotations to multiple methods and enhanced error handling and logging.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java Introduced DEFAULT_USER_ID constant and improved user ID handling methods for better null safety and consistency.

Suggested labels

size:S, lgtm

Suggested reviewers

  • nobodyiam

🐇 In the code we hop and play,
With strings and lists, we pave the way.
Nulls to empty, a safer route,
In every method, we dance about!
Debugging's easier, logs so bright,
Hooray for changes, all feels right! 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (15)
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java (1)

61-67: Consider enhancing assembleDefaultUser method.

The method could be improved by:

  1. Making it more maintainable with additional constants
  2. Adding validation for the email format

Here's a suggested improvement:

+ private static final String DEFAULT_USER_EMAIL = "[email protected]";

  private UserInfo assembleDefaultUser() {
    UserInfo defaultUser = new UserInfo();
    defaultUser.setUserId(DEFAULT_USER_ID);
    defaultUser.setName(DEFAULT_USER_ID);
-   defaultUser.setEmail("[email protected]");
+   defaultUser.setEmail(DEFAULT_USER_EMAIL);

    return defaultUser;
  }
apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiNoOpImpl.java (1)

54-76: LGTM! Good improvement in null safety

Replacing null returns with Collections.emptyList() is a great improvement that:

  • Prevents potential NullPointerExceptions
  • Makes the API more predictable
  • Follows Java best practices for collection returns

Consider extracting the Collections.emptyList() to a private static final field to avoid creating new instances:

public class ApolloAuditLogApiNoOpImpl implements ApolloAuditLogApi {
+  private static final List<?> EMPTY_LIST = Collections.emptyList();
+
   @Override
   public List<ApolloAuditLogDTO> queryLogs(int page, int size) {
-    return Collections.emptyList();
+    return (List<ApolloAuditLogDTO>) EMPTY_LIST;
   }
   // Apply similar changes to other methods
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java (1)

149-149: Consider improving the magic string comparison.

While the null-safe comparison is good, the magic string "java-null" could be extracted as a constant to improve maintainability and document its significance.

+ private static final String INVALID_VERSION = "java-null";
  private boolean isValidVersion(String version) {
-   return !Objects.equals(version, "java-null");
+   return !Objects.equals(version, INVALID_VERSION);
  }
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRoleInitializationService.java (1)

Line range hint 138-165: Consider optimizing synchronization scope.

While the synchronization is good for thread safety, consider making it more granular by moving it to only wrap the critical section where the role is actually created.

  @Override
  public void initCreateAppRole() {
    if (rolePermissionService.findRoleByRoleName(SystemRoleManagerService.CREATE_APPLICATION_ROLE_NAME) != null) {
      return;
    }
-   Permission createAppPermission = permissionRepository.findTopByPermissionTypeAndTargetId(PermissionType.CREATE_APPLICATION, SystemRoleManagerService.SYSTEM_PERMISSION_TARGET_ID);
-   if (createAppPermission == null) {
-     // create application permission init
-     createAppPermission = createPermission(SystemRoleManagerService.SYSTEM_PERMISSION_TARGET_ID, PermissionType.CREATE_APPLICATION, "apollo");
-     rolePermissionService.createPermission(createAppPermission);
-   }
-   //  create application role init
-   Role createAppRole = createRole(SystemRoleManagerService.CREATE_APPLICATION_ROLE_NAME, "apollo");
-   rolePermissionService.createRoleWithPermissions(createAppRole, Sets.newHashSet(createAppPermission.getId()));
+   synchronized (DefaultRoleInitializationService.class) {
+     if (rolePermissionService.findRoleByRoleName(SystemRoleManagerService.CREATE_APPLICATION_ROLE_NAME) != null) {
+       return;
+     }
+     Permission createAppPermission = permissionRepository.findTopByPermissionTypeAndTargetId(PermissionType.CREATE_APPLICATION, SystemRoleManagerService.SYSTEM_PERMISSION_TARGET_ID);
+     if (createAppPermission == null) {
+       // create application permission init
+       createAppPermission = createPermission(SystemRoleManagerService.SYSTEM_PERMISSION_TARGET_ID, PermissionType.CREATE_APPLICATION, "apollo");
+       rolePermissionService.createPermission(createAppPermission);
+     }
+     //  create application role init
+     Role createAppRole = createRole(SystemRoleManagerService.CREATE_APPLICATION_ROLE_NAME, "apollo");
+     rolePermissionService.createRoleWithPermissions(createAppRole, Sets.newHashSet(createAppPermission.getId()));
+   }
  }
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java (1)

Line range hint 276-294: Consider improving error message specificity.

While the implementation is correct, the error message could be more helpful by specifying which exact permission type and target ID combination caused the conflict.

-            Preconditions.checkState(CollectionUtils.isEmpty(current),
-                    "Permission with permissionType %s targetId %s already exists!", permissionTypes,
-                    targetId);
+            if (!CollectionUtils.isEmpty(current)) {
+                String conflictingTypes = current.stream()
+                    .map(p -> String.format("%s (targetId: %s)", p.getPermissionType(), p.getTargetId()))
+                    .collect(Collectors.joining(", "));
+                throw new IllegalStateException(
+                    String.format("Conflicting permissions already exist: %s", conflictingTypes));
+            }
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Privilege.java (1)

Line range hint 67-71: Consider improving toString() formatting for better readability

While the implementation is correct, consider formatting the method chaining for better readability:

  @Override
  public String toString() {
-    return toStringHelper().add("namespaceId", namespaceId).add("privilType", privilType)
-        .add("name", name).toString();
+    return toStringHelper()
+        .add("namespaceId", namespaceId)
+        .add("privilType", privilType)
+        .add("name", name)
+        .toString();
  }
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Audit.java (2)

Line range hint 82-86: Approve implementation with minor formatting suggestion

The toString() implementation includes all relevant fields and is well-structured. Consider reformatting the method chaining for better readability:

  @Override
  public String toString() {
-    return toStringHelper().add("entityName", entityName).add("entityId", entityId)
-        .add("opName", opName).add("comment", comment).toString();
+    return toStringHelper()
+        .add("entityName", entityName)
+        .add("entityId", entityId)
+        .add("opName", opName)
+        .add("comment", comment)
+        .toString();
  }

Line range hint 67-71: Commend consistent toString() implementation pattern across entities

The consistent use of toStringHelper() across all entity classes demonstrates good architectural coherence. This pattern provides a uniform approach to object string representation, which is valuable for debugging and logging.

Consider documenting this pattern in the contributing guidelines to ensure future entity classes follow the same approach.

Also applies to: 80-83, 82-86

apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java (1)

Line range hint 77-82: LGTM! Consider adding Javadoc.

The toString() implementation correctly includes all essential fields and follows the BaseEntity pattern using toStringHelper().

Consider adding Javadoc to document the string format for better maintainability:

/**
 * Returns a string representation of this Namespace including appId, clusterName, and namespaceName.
 * @return a string representation of this object
 */
@Override
public String toString() {
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Cluster.java (1)

Line range hint 81-85: Consider null safety for comment field.

While the toString() implementation is correct, the comment field is nullable. Consider using Objects.toString(comment, "") to handle null values gracefully.

  @Override
  public String toString() {
    return toStringHelper().add("name", name).add("appId", appId)
-        .add("parentClusterId", parentClusterId).add("comment", comment).toString();
+        .add("parentClusterId", parentClusterId)
+        .add("comment", Objects.toString(comment, "")).toString();
  }
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java (1)

Line range hint 77-82: Consider documenting toString() implementation guidelines.

The consistent use of toStringHelper() across entity classes is good practice. Consider:

  1. Documenting the standard toString() format in the BaseEntity class
  2. Creating guidelines for which fields should be included
  3. Establishing null handling conventions

This will help maintain consistency as more entity classes are added or modified.

Also applies to: 81-85, 77-80

apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java (1)

Line range hint 126-131: Include releaseKey and mask sensitive configurations

Two suggestions for improvement:

  1. Include the releaseKey field as it's a required field (nullable=false)
  2. Mask the configurations field to prevent exposing sensitive data in logs
   @Override
   public String toString() {
     return toStringHelper().add("name", name).add("appId", appId).add("clusterName", clusterName)
+        .add("releaseKey", releaseKey)
         .add("namespaceName", namespaceName).add("configurations", configurations != null ? "***" : null)
         .add("comment", comment).add("isAbandoned", isAbandoned).toString();
   }
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ReleaseHistory.java (2)

Line range hint 124-129: Include operationContext and improve operation field representation

Consider the following improvements:

  1. Include the operationContext field as it's a required field (nullable=false)
  2. Consider adding a string representation of the operation integer for better readability in logs
   @Override
   public String toString() {
     return toStringHelper().add("appId", appId).add("clusterName", clusterName)
         .add("namespaceName", namespaceName).add("branchName", branchName)
         .add("releaseId", releaseId).add("previousReleaseId", previousReleaseId)
-        .add("operation", operation).toString();
+        .add("operation", operation)
+        .add("operationContext", operationContext).toString();
   }

Line range hint 102-107: Consider establishing toString() implementation guidelines

To maintain consistency across entity classes, consider establishing the following guidelines for toString() implementations:

  1. Include all non-null required fields (marked with nullable=false)
  2. Mask or truncate sensitive data fields
  3. Use meaningful string representations for enum/integer constants
  4. Consider the impact on log file sizes for fields with large content

Would you like me to help create a documentation PR with detailed toString() implementation guidelines?

Also applies to: 126-131, 124-129

apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/App.java (1)

Line range hint 114-121: LGTM! Consider minor formatting improvements.

The toString implementation is functionally correct and well-structured. Consider improving readability by consistent chaining format:

-    return toStringHelper().add("name", name).add("appId", appId)
-        .add("orgId", orgId)
-        .add("orgName", orgName)
-        .add("ownerName", ownerName)
-        .add("ownerEmail", ownerEmail).toString();
+    return toStringHelper()
+        .add("name", name)
+        .add("appId", appId)
+        .add("orgId", orgId)
+        .add("orgName", orgName)
+        .add("ownerName", ownerName)
+        .add("ownerEmail", ownerEmail)
+        .toString();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 28d2898 and c7ec8a1.

📒 Files selected for processing (24)
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiJpaImpl.java (1 hunks)
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiNoOpImpl.java (2 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Audit.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Cluster.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Item.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Privilege.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ReleaseHistory.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ServerConfig.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/DatabaseServiceRegistryImpl.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/configuration/support/ApolloServiceRegistryProperties.java (1 hunks)
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/utils/ReleaseMessageKeyGenerator.java (2 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/ApolloDataSourceScriptDatabaseInitializerFactory.java (2 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/App.java (1 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/AppNamespace.java (1 hunks)
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/BaseEntity.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/PortalSettings.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/RestTemplateFactory.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java (2 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRoleInitializationService.java (6 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java (9 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/PortalSettings.java
🔇 Additional comments (21)
apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/utils/ReleaseMessageKeyGenerator.java (1)

24-24: LGTM! Good improvement in null safety.

Replacing the null return with Collections.emptyList() is a good practice as it:

  • Prevents potential NullPointerExceptions in calling code
  • Provides a more predictable behavior
  • Aligns with the "Null Object" pattern

Also applies to: 46-46

apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/DatabaseServiceRegistryImpl.java (1)

40-40: LGTM! Good use of @OverRide annotations.

Adding @OverRide annotations to interface implementations:

  • Improves code clarity by explicitly showing inheritance
  • Provides compile-time safety against interface changes
  • Follows Java best practices

Also applies to: 46-46

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java (1)

34-34: LGTM! Excellent improvements in code quality.

The changes enhance code quality through:

  • Introduction of DEFAULT_USER_ID constant eliminates magic strings
  • Use of Objects.equals improves null safety
  • Proper collection emptiness checks with CollectionUtils.isEmpty
  • Consistent use of Collections.emptyList() instead of null returns

Also applies to: 43-43, 51-58

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/RestTemplateFactory.java (2)

50-63: LGTM! Well-implemented FactoryBean methods

The implementation of getObject(), getObjectType(), and isSingleton() follows Spring's FactoryBean contract correctly.


Line range hint 65-85: Consider breaking down the initialization logic

The afterPropertiesSet() method handles multiple responsibilities:

  1. Connection manager configuration
  2. HTTP client creation
  3. RestTemplate setup
  4. Interceptor configuration

Consider breaking this into smaller, focused methods:

+ private PoolingHttpClientConnectionManager createConnectionManager() {
+   PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
+   connectionManager.setMaxTotal(portalConfig.connectPoolMaxTotal());
+   connectionManager.setDefaultMaxPerRoute(portalConfig.connectPoolMaxPerRoute());
+   return connectionManager;
+ }

+ private CloseableHttpClient createHttpClient(PoolingHttpClientConnectionManager connectionManager) {
+   return HttpClientBuilder.create()
+       .setConnectionTimeToLive(portalConfig.connectionTimeToLive(), TimeUnit.MILLISECONDS)
+       .setConnectionManager(connectionManager)
+       .build();
+ }

+ private void configureRequestFactory(HttpComponentsClientHttpRequestFactory requestFactory) {
+   requestFactory.setConnectTimeout(portalConfig.connectTimeout());
+   requestFactory.setReadTimeout(portalConfig.readTimeout());
+ }

Also, let's verify thread safety of the RestTemplate configuration:

✅ Verification successful

Let me gather more context about the RestTemplateFactory usage to verify thread safety concerns.


Let me try one more search to find the complete RestTemplateFactory implementation.


The refactoring suggestion is good, but there are no thread-safety concerns

The RestTemplateFactory is properly implemented as a Spring singleton bean (marked with @component) that follows the FactoryBean pattern. The initialization happens once during bean creation in afterPropertiesSet(), and the RestTemplate instance is safely shared through getObject(). The implementation shows:

  1. Thread-safe initialization through Spring's bean lifecycle
  2. Proper singleton scope (explicitly declared via isSingleton())
  3. All consumers get the same RestTemplate instance through the factory's getObject()
  4. No concurrent modifications to the RestTemplate after initialization

The original suggestion to break down the initialization logic into smaller methods is still valid for better code organization, but there are no thread-safety issues to address.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any concurrent access to RestTemplate instance
rg -l 'private\s+RestTemplate\s+restTemplate' | xargs rg 'restTemplate\s*='

Length of output: 866


Script:

#!/bin/bash
# Check RestTemplateFactory implementation and scope
ast-grep --pattern 'class RestTemplateFactory'

# Check if RestTemplateFactory is singleton/prototype
rg -A 2 '@Scope.*RestTemplateFactory'

# Check getObject implementation
ast-grep --pattern 'public RestTemplate getObject()'

Length of output: 4881


Script:

#!/bin/bash
# Get the complete RestTemplateFactory implementation
rg -A 100 "class RestTemplateFactory"

# Check for @Bean or other Spring annotations
rg -B 5 "class RestTemplateFactory"

Length of output: 8004

apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/configuration/support/ApolloServiceRegistryProperties.java (1)

100-103: LGTM! Good use of @OverRide annotation

Adding the @OverRide annotation:

  • Improves code clarity by explicitly showing interface contract implementation
  • Helps catch errors if the interface method signature changes
  • Follows Java best practices for interface implementations
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java (1)

28-28: LGTM! Import added for null-safe comparison.

The addition of java.util.Objects import supports the improved null-safe comparison implementation.

apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiJpaImpl.java (1)

98-98: LGTM! Improved null safety in condition check.

The condition has been enhanced to safely handle both null and empty string cases using Objects.isNull and Objects.equals. This prevents potential NPEs and makes the code more robust.

apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/ApolloDataSourceScriptDatabaseInitializerFactory.java (2)

23-23: LGTM! Import added for empty collection return.

The addition of java.util.Collections import supports the improved empty collection return pattern.


105-105: LGTM! Improved null safety with empty collection return.

Replacing null return with Collections.emptyList() follows best practices and prevents potential NPEs in the calling code. This change makes the API more predictable and safer to use.

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRoleInitializationService.java (5)

Line range hint 60-93: LGTM! Well-structured role initialization logic.

The method properly handles app role initialization with appropriate checks and synchronization.


Line range hint 95-111: LGTM! Clear and consistent namespace role initialization.

The method properly handles namespace role initialization with appropriate null checks and transactional boundaries.


Line range hint 112-121: LGTM! Comprehensive environment-specific role initialization.

The method properly handles role initialization across all supported environments.


Line range hint 122-137: LGTM! Well-structured environment-specific role initialization.

The method maintains consistency with the overall role initialization pattern.


Line range hint 166-174: LGTM! Thread-safe role initialization.

The method properly handles role initialization with appropriate synchronization and null checks.

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java (2)

Line range hint 175-193: LGTM! Improved null safety and collection handling.

The change from null check to CollectionUtils.isEmpty enhances robustness, and returning an empty set instead of null follows best practices.


251-254: LGTM! Clear and focused super admin check.

The method properly delegates to configuration for super admin verification.

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java (1)

77-80: Review comment field constraints.

The toString() implementation is correct, but there appears to be an inconsistency in the comment field's constraints:

  • It's marked as nullable = false in the column definition
  • But unlike key and value fields, it lacks the @NotBlank constraint

Let's verify the usage of comment field constraints across similar entities:

apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Item.java (1)

Line range hint 102-107: Consider masking sensitive configuration values in toString()

While the toString() implementation is well-structured, the value field might contain sensitive configuration data. Consider masking or truncating sensitive values to prevent accidental exposure in logs.

Example approach:

   @Override
   public String toString() {
     return toStringHelper().add("namespaceId", namespaceId).add("key", key)
             .add("type", type).add("value", value != null ? "***" : null)
             .add("lineNum", lineNum).add("comment", comment).toString();
   }
apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/AppNamespace.java (1)

Line range hint 110-114: LGTM! Well-structured toString implementation.

The toString implementation follows good practices by:

  • Using the parent's toStringHelper method
  • Including all relevant fields
  • Properly annotating with @OverRide
  • Safely handling null values
apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/BaseEntity.java (1)

152-155: LGTM! Good base implementation.

The toString implementation in BaseEntity provides a solid foundation for subclasses by:

  • Properly delegating to toStringHelper()
  • Including all base entity fields
  • Allowing subclasses to extend it with their specific fields

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot reviewed 10 out of 25 changed files in this pull request and generated no comments.

Files not reviewed (15)
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiJpaImpl.java: Evaluated as low risk
  • apollo-audit/apollo-audit-impl/src/main/java/com/ctrip/framework/apollo/audit/component/ApolloAuditLogApiNoOpImpl.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Audit.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Cluster.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Item.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Privilege.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ReleaseHistory.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/ServerConfig.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/DatabaseServiceRegistryImpl.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/registry/configuration/support/ApolloServiceRegistryProperties.java: Evaluated as low risk
  • apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/utils/ReleaseMessageKeyGenerator.java: Evaluated as low risk
  • apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/utils/ReleaseKeyGeneratorTest.java: Evaluated as low risk
  • apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/ApolloDataSourceScriptDatabaseInitializerFactory.java: Evaluated as low risk
Copy link
Member

@nobodyiam nobodyiam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Dec 14, 2024
@nobodyiam nobodyiam merged commit 939f890 into apolloconfig:master Dec 14, 2024
7 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Dec 14, 2024
@youngzil youngzil deleted the code_style branch December 14, 2024 06:20
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants