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

Eap7.4.x #17

Open
wants to merge 262 commits into
base: master
Choose a base branch
from
Open

Eap7.4.x #17

wants to merge 262 commits into from

Conversation

2lambda123
Copy link
Owner

@2lambda123 2lambda123 commented Oct 31, 2024

Description

Related Issue

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Chore (non-breaking change that does not add functionality or fix an issue)

Checklist:

  • I have read the Code of Conduct
  • I have updated the documentation accordingly.
  • All commits are GPG signed

Summary by Sourcery

Migrate CI from Travis CI to GitHub Actions, introducing a new workflow configuration. Refactor proxy class handling to support multi-release JARs and improve package management. Enhance logging and documentation to reflect these changes. Add comprehensive tests to cover new proxy handling and annotation processing features.

New Features:

  • Introduce GitHub Actions configuration for CI workflows, replacing Travis CI.

Enhancements:

  • Refactor proxy class name generation to improve package handling and support for multi-release JARs.
  • Improve handling of additional bean defining annotations in Weld SE.
  • Enhance logging for various operations, including class loading and proxy creation.

CI:

  • Add a comprehensive GitHub Actions workflow for continuous integration, covering multiple JDK versions and various test scenarios.

Documentation:

  • Update README to reflect the switch from Travis CI to GitHub Actions for build status.

Tests:

  • Add new tests for proxy class name generation, including scenarios with hierarchical interfaces and multi-release JARs.
  • Introduce tests for additional bean defining annotations and their handling in Weld SE.
  • Add tests for decorator and interceptor metadata availability in complex scenarios.

Description by Korbit AI

What change is being made?

Add GitHub Actions configuration for CI workflows and update various configuration files, dependencies, and documentation within the Weld project.

Why are these changes being made?

These changes are introduced to migrate from Travis CI to GitHub Actions, align with the latest configurations, dependencies, and libraries to enhance build and runtime efficiency. The updates in documentation and descoped CI aspects improve clarity and modernize the project's build process with enhanced capabilities and streamlined workflows.

Is this description stale? Ask me to generate a new description by commenting /korbit-generate-pr-description

manovotn and others added 30 commits August 12, 2020 12:38
Bumps [htmlunit](https://github.com/HtmlUnit/htmlunit) from 2.20 to 2.37.0. **This update includes a security fix.**
- [Release notes](https://github.com/HtmlUnit/htmlunit/releases)
- [Commits](HtmlUnit/htmlunit@HtmlUnit-2.20...2.37.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps `tomcat.version` from 9.0.31 to 9.0.37.

Updates `tomcat-embed-core` from 9.0.31 to 9.0.37

Updates `tomcat-embed-jasper` from 9.0.31 to 9.0.37

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps jboss-logmanager from 1.2.2.GA to 2.1.17.Final.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps `jax.artifacts.version` from 2.3.2 to 2.3.3.

Updates `jakarta.xml.ws-api` from 2.3.2 to 2.3.3
- [Release notes](https://github.com/eclipse-ee4j/jax-ws-api/releases)
- [Commits](jakartaee/jax-ws-api@2.3.2...2.3.3)

Updates `jaxws-ri` from 2.3.2 to 2.3.3

Updates `jaxb-ri` from 2.3.2 to 2.3.3

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps [mockito-core](https://github.com/mockito/mockito) from 2.19.0 to 3.5.7.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](mockito/mockito@v2.19.0...v3.5.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps jakarta.activation-api from 1.2.1 to 1.2.2.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps [htmlunit](https://github.com/HtmlUnit/htmlunit) from 2.37.0 to 2.43.0.
- [Release notes](https://github.com/HtmlUnit/htmlunit/releases)
- [Commits](HtmlUnit/htmlunit@2.37.0...2.43.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps `arquillian.version` from 1.7.0.Alpha2 to 1.7.0.Alpha4.

Updates `arquillian-bom` from 1.7.0.Alpha2 to 1.7.0.Alpha4
- [Release notes](https://github.com/arquillian/arquillian-core/releases)
- [Commits](https://github.com/arquillian/arquillian-core/commits)

Updates `arquillian-container-spi` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-junit-container` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-test-impl-base` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-container-test-impl-base` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-container-test-spi` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-testenricher-cdi` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Updates `arquillian-protocol-servlet` from 1.7.0.Alpha2 to 1.7.0.Alpha4

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps `arquillian.glassfish.version` from 1.0.0.CR1 to 1.0.2.

Updates `arquillian-glassfish-embedded-3.1` from 1.0.0.CR1 to 1.0.2
- [Release notes](https://github.com/arquillian/arquillian-container-glassfish/releases)
- [Commits](arquillian/arquillian-container-glassfish@1.0.0.CR1...1.0.2)

Updates `arquillian-glassfish-remote-3.1` from 1.0.0.CR1 to 1.0.2
- [Release notes](https://github.com/arquillian/arquillian-container-glassfish/releases)
- [Commits](arquillian/arquillian-container-glassfish@1.0.0.CR1...1.0.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps bcel from 6.2 to 6.5.0.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.7.9 to 0.8.5.
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](jacoco/jacoco@v0.7.9...v0.8.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
Copy link

quine-bot bot commented Oct 31, 2024

👋 Figuring out if a PR is useful is hard, hopefully this will help.

  • @2lambda123 has been on GitHub since 2019 and in that time has had 2890 public PRs merged
  • They haven't contributed to this repo before
  • Here's a good example of their work: black-forest-labs-flux
  • From looking at their profile, they seem to be good with Shell and Python.

Their most recently public accepted PR is: 2lambda123/orc-tuni-dark-spot-mapper#1

@labels-and-badges labels-and-badges bot added NO JIRA This PR does not have a Jira Ticket PR:size/XXL Denotes a Pull Request that changes 1000+ lines. labels Oct 31, 2024
Copy link

codeautopilot bot commented Oct 31, 2024

Your organization has reached the subscribed usage limit. You can upgrade your account by purchasing a subscription at Stripe payment link

Disclaimer: This comment was entirely generated using AI. Be aware that the information provided may be incorrect.

Current plan usage: 143.19%

Have feedback or need help?
Discord
Documentation
support@codeautopilot.com

Copy link

git-greetings bot commented Oct 31, 2024

PR Details of @2lambda123 in weld-core :

OPEN CLOSED TOTAL
9 8 17

Copy link

Description has been updated!

Copy link

coderabbitai bot commented Oct 31, 2024

Warning

Rate limit exceeded

@2lambda123 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 957ab78 and 5d1fd80.


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 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.

@labels-and-badges labels-and-badges bot added the PR:CONFLICT This PR has a conflict label Oct 31, 2024
@restyled-io restyled-io bot mentioned this pull request Oct 31, 2024
Copy link

sourcery-ai bot commented Oct 31, 2024

🧙 Sourcery is reviewing your pull request!


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @2lambda123 - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟡 Documentation: 1 issue found

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

* @param domain {@link ProtectionDomain}
* @return
*/
private Class<?> defineWithClassLoader(String classToDefineName, byte[] classBytes, int length, ClassLoader loader, ProtectionDomain domain) {
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Potential race condition in class loader creation and definition

While computeIfAbsent is atomic, there's a potential race between getting the WeldProxyDeclaringCL and using it to define the class. Consider adding synchronization or documenting why it's safe.

Choose a reason for hiding this comment

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

Micro-Learning Topic: Race condition (Detected by phrase)

Matched on "race condition"

What is this? (2min video)

A race condition is a flaw that produces an unexpected result when the timing of actions impact other actions.

Try a challenge in Secure Code Warrior

@@ -33,33 +33,6 @@ Then, run the upgrade script:
In the above snippet, `${weld.version}` is the version of Weld you want to use.
Now you should have patched WildFly in `JBOSS_HOME`.

Creating a patch file for WildFly
Copy link

Choose a reason for hiding this comment

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

suggestion (documentation): Consider adding a note about the status of WildFly patching functionality

If this functionality still exists but is documented elsewhere, please add a reference to the new location. If it's been deprecated or removed, consider adding a brief note about the current recommended approach for WildFly customization.

Creating a patch file for WildFly (Note: For current WildFly versions, refer to the official WildFly Configuration Guide at https://docs.wildfly.org/26/Admin_Guide.html for recommended customization approaches)

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @2lambda123 - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟡 Documentation: 1 issue found

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -33,33 +33,6 @@ Then, run the upgrade script:
In the above snippet, `${weld.version}` is the version of Weld you want to use.
Now you should have patched WildFly in `JBOSS_HOME`.

Creating a patch file for WildFly
Copy link

Choose a reason for hiding this comment

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

suggestion (documentation): Consider adding a note about the status of WildFly patching functionality

If this functionality still exists but is documented elsewhere, please add a reference to the new location. If it's been deprecated or removed, consider adding a brief note about the current recommended approach for WildFly customization.

Creating a patch file for WildFly (Note: For current WildFly versions, refer to the official WildFly Configuration Guide at https://docs.wildfly.org/26/Admin_Guide.html for recommended customization approaches)

Copy link
Contributor

penify-dev bot commented Oct 31, 2024

Failed to generate code suggestions for PR

Comment on lines 105 to 106
throw CommonLogger.LOG.cannotReadClassPathEntry(entryFile);
}

Choose a reason for hiding this comment

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

The method scan() throws an exception if a class path entry is not readable, potentially halting the entire scanning process. This could be problematic in environments where partial results are still useful, or where certain class path entries might be expected to be unreadable due to permissions or other issues.

Recommended Solution:
Consider logging a warning and continuing with the next entry instead of throwing an exception. This approach would allow the scanning process to complete as much as possible, providing more robust behavior in diverse environments.

Comment on lines 139 to 145
@Message(id = 34, value = "Cannot scan class path entry: {0}", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotScanClassPathEntry(Object entry, @Cause Throwable cause);

@Message(id = 35, value = "Class path entry does not exist or cannot be read: {0}", format = Format.MESSAGE_FORMAT)
@Message(id = 35, value = "Class path entry cannot be read: {0}", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotReadClassPathEntry(Object entry);

@Message(id = 36, value = "Weld cannot read the java class path system property!", format = Format.MESSAGE_FORMAT)

Choose a reason for hiding this comment

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

The use of IllegalStateException in methods cannotScanClassPathEntry, cannotReadClassPathEntry, and cannotReadJavaClassPathSystemProperty might not be the most appropriate choice. These exceptions are typically used to indicate that the method has been invoked at an illegal or inappropriate time, or that the application is not in an appropriate state for the requested operation. However, issues related to class path entries and system properties might be better represented by IOException or a custom exception that more accurately reflects the nature of the issue, such as ClassPathException or SystemPropertyReadException. This would improve the clarity and maintainability of the code by using more specific exceptions that better describe the actual error condition.

Recommended Change:
Replace IllegalStateException with more specific exceptions that accurately describe the issues related to class path and system properties.

Comment on lines 82 to 83
@Message(id = 2016, value = "Zero or more than one container is running - WeldContainer.current() cannot determine the current container.", format = Format.MESSAGE_FORMAT)
IllegalStateException zeroOrMoreThanOneContainerRunning();

Choose a reason for hiding this comment

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

The method zeroOrMoreThanOneContainerRunning throws an IllegalStateException which is appropriate for the error condition it handles. However, the error message could be enhanced by suggesting potential steps to resolve the ambiguity in container identification. This would aid developers or system administrators in troubleshooting and resolving the issue more efficiently.

Comment on lines 93 to 94
@Message(id = 2019, value = "Failed to parse the following string as additional bean defining annotation: {0}. The exception was: {1}", format = Format.MESSAGE_FORMAT)
IllegalArgumentException failedToLoadClass(String className, String exception);

Choose a reason for hiding this comment

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

The exception handling in failedToLoadClass is crucial for robustness, especially in dynamic class loading scenarios. However, the method could be improved by logging the exception details or providing a more detailed message about the nature of the error. This would help in diagnosing the issue more effectively and potentially guide the user on how to correct the class name or handle the configuration error.

Weld weld = new Weld().disableDiscovery().addBeanClass(DummyBean.class).addServices(new InvalidProxyServices());
try (WeldContainer container = weld.initialize()){
// ISE should have been thrown earlier
Assert.fail();

Choose a reason for hiding this comment

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

The use of Assert.fail() without a descriptive message can lead to unclear test failure reports. It is recommended to include a message that describes the expected behavior, which in this case is the failure of container initialization due to incorrect ProxyServices.

Suggested Improvement:

Assert.fail("Weld container initialized successfully, but was expected to fail due to incorrect ProxyServices.");

Comment on lines 53 to 56
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

Choose a reason for hiding this comment

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

The CloseableHttpClient created in line 53 is not being closed after use, which can lead to resource leaks and potentially affect the performance of the test suite. It's recommended to use a try-with-resources statement to ensure that the client is closed properly after the request is made.

Suggested Change:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
    assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The test method lacks comprehensive error handling. If client.execute(request) fails for any reason (e.g., network issues, server not responding), it could throw an exception or return a null response, leading to a NullPointerException when calling getStatusLine(). It's advisable to add null checks and proper exception handling to make the test more robust and prevent it from failing unexpectedly.

Suggested Change:

HttpResponse response = client.execute(request);
assertNotNull("Response should not be null", response);
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

Comment on lines 63 to 79
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=request").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=sce").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=sce").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=session").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The CloseableHttpClient created in each test method is not being closed after use. This can lead to resource leaks, such as open sockets and consumed memory, which can affect the performance and stability of the test suite.

Recommended Solution:
Use a try-with-resources statement to ensure that the CloseableHttpClient is closed properly after its use. For example:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    // use client
}

Comment on lines 63 to 79
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=request").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=sce").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=sce").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=session").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

There is significant code duplication across the test methods testRequestListenerInjection, testSceListenerInjection, and testSessionListenerInjection. Each method repeats the process of creating a client, constructing a request, sending it, and checking the response.

Recommended Solution:
Refactor the common code into a private helper method that takes parameters for the unique parts (e.g., the URL path and query). This will make the tests easier to maintain and reduce the risk of errors when changes are made. For example:

private void testListenerInjection(String path) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpGet request = new HttpGet(new URL(baseURL, path).toExternalForm());
        assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
    }
}

Comment on lines 53 to 55
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "rat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The CloseableHttpClient created with HttpClients.createDefault() is not closed after use, which can lead to resource leaks. It's recommended to use a try-with-resources statement to ensure that the client is closed properly after the request is made. For example:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpGet request = new HttpGet(new URL(baseURL, "rat").toExternalForm());
    assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

Comment on lines 74 to 75
/**
*

Choose a reason for hiding this comment

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

The constructor ClassPathBeanArchiveScanner(Bootstrap bootstrap) lacks documentation. It's important to provide comments explaining the purpose of the constructor and the role of its parameters. This will enhance the maintainability and understandability of the code.

Recommended Solution:
Add a detailed Javadoc comment above the constructor explaining its functionality and the significance of the bootstrap parameter.

Comment on lines 107 to 109
if (entryFile.isDirectory()) {
scanDirectory(entryFile, results);
} else {

Choose a reason for hiding this comment

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

The methods scanJarFile and scanDirectory are called without prior validation that entryFile is indeed a directory or JAR file. This could lead to unnecessary exceptions if the file type does not match the expected. This approach can lead to performance degradation and potential crashes.

Recommended Solution:
Before calling scanJarFile or scanDirectory, add checks to confirm that entryFile is a valid directory or JAR file. Use appropriate file type checks such as checking the file extension for JAR files or using File.isDirectory() for directories.

Comment on lines 163 to 170
@Message(id = 41, value = "Using {0} for bean discovery", format = Format.MESSAGE_FORMAT)
void usingServiceLoaderSourcedDiscoveryStrategy(Object discoveryStrategy);

@LogMessage(level = Level.WARN)
@Message(id = 42, value = "Class path entry does not exist: {0}", format = Format.MESSAGE_FORMAT)
void classPathEntryDoesNotExist(Object entry);

}

Choose a reason for hiding this comment

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

The methods usingServiceLoaderSourcedDiscoveryStrategy and classPathEntryDoesNotExist use Object as the parameter type for discoveryStrategy and entry respectively. This generic type can lead to type safety issues, as it allows any object to be passed to these methods, potentially causing runtime type errors if the object is not of the expected type.

Recommendation: Consider using more specific types for these parameters, or add type checks within the methods to ensure that the passed objects meet the expected criteria.

Comment on lines 85 to 86
@Message(id = 2017, value = "Unexpected value for parameter 'org.jboss.weld.se.additionalBeanDefiningAnnotations'. Expected java.util.Collection but found {0}. ", format = Format.MESSAGE_FORMAT)
IllegalArgumentException unexpectedValueForAdditionalBeanDefiningAnnotations(Class clazz);

Choose a reason for hiding this comment

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

The error message in line 85 could be improved for clarity. It currently states an expectation but does not specify what was actually found, which could lead to confusion during debugging. Consider modifying the error message to include the actual type found to enhance clarity and aid in quicker issue resolution.

Suggested Change:

@Message(id = 2017, value = "Unexpected value for parameter 'org.jboss.weld.se.additionalBeanDefiningAnnotations'. Expected java.util.Collection but found {0}: {1}.", format = Format.MESSAGE_FORMAT)
IllegalArgumentException unexpectedValueForAdditionalBeanDefiningAnnotations(Class clazz, String foundType);

Comment on lines 93 to 94
@Message(id = 2019, value = "Failed to parse the following string as additional bean defining annotation: {0}. The exception was: {1}", format = Format.MESSAGE_FORMAT)
IllegalArgumentException failedToLoadClass(String className, String exception);

Choose a reason for hiding this comment

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

The method failedToLoadClass at line 93 throws an IllegalArgumentException which is appropriate for indicating a parsing error. However, to enhance error handling, consider providing a more specific exception or a more detailed error message that includes potential causes or resolutions. This would aid developers in understanding and resolving the issue more efficiently.

Suggested Change:

@Message(id = 2019, value = "Failed to parse the following string as additional bean defining annotation: {0}. The exception was: {1}. Ensure the string is a valid class name and is accessible.", format = Format.MESSAGE_FORMAT)
IllegalArgumentException failedToLoadClass(String className, String exception);

Comment on lines 53 to 55
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The CloseableHttpClient created in line 53 is not closed after use, which can lead to resource leaks. It is recommended to use a try-with-resources statement to ensure that the client is closed properly after the request is made.

Recommended change:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
    assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The method client.execute(request) is directly used to get the status code without checking if the response object is null or if the entity is available. This could lead to a NullPointerException if the response is unsuccessful or the server returns no content.

Recommended change:

HttpResponse response = client.execute(request);
if (response != null && response.getEntity() != null) {
    assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} else {
    fail("No response or no entity in response");
}

Comment on lines 62 to 80
public void testRequestListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=request").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=request").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=sce").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=sce").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=session").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

Choose a reason for hiding this comment

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

Resource Management Issue

The test methods testRequestListenerInjection, testSceListenerInjection, and testSessionListenerInjection each create a new instance of CloseableHttpClient but do not close it after use. This can lead to resource leaks and potential exhaustion of system resources.

Recommendation:
Use a try-with-resources statement to ensure that the CloseableHttpClient and any other closeable resources are closed properly after their use. For example:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    // use client
}

Comment on lines 62 to 80
public void testRequestListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=request").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=request").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=sce").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=sce").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "bat?mode=session").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

Choose a reason for hiding this comment

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

Lack of Exception Handling

The test methods currently declare throws Exception, which is a generic exception handling strategy that may not provide sufficient information on the type of error or allow for specific recovery actions.

Recommendation:
Implement more specific exception handling within the test methods to manage different types of HTTP or client-related exceptions. This approach will enhance the test's robustness by allowing for specific responses to different error conditions and ensuring resources are cleaned up even when exceptions occur.

Comment on lines 53 to 55
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "rat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The CloseableHttpClient created with HttpClients.createDefault() is not being closed after use, which can lead to resource leaks and potentially exhaust system resources when running many tests. It's recommended to use a try-with-resources statement to ensure that the client is closed properly after the request is made.

Recommended Change:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpGet request = new HttpGet(new URL(baseURL, "rat").toExternalForm());
    assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

Copy link

cr-gpt bot commented Oct 31, 2024

Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information

Copy link

Processing PR updates...

@restyled-io restyled-io bot mentioned this pull request Oct 31, 2024
Copy link

cr-gpt bot commented Oct 31, 2024

Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information

Copy link

Processing PR updates...

Comment on lines +85 to +117
String javaClassPath = AccessController.doPrivileged(
new GetSystemPropertyAction(JAVA_CLASS_PATH_SYSTEM_PROPERTY));
if (javaClassPath == null) {
throw CommonLogger.LOG.cannotReadJavaClassPathSystemProperty();
}
ImmutableList.Builder<ScanResult> results = ImmutableList.builder();
Set<String> entries =
ImmutableSet.of(javaClassPath.split(Pattern.quote(File.pathSeparator)));
logger.debugv("Scanning class path entries: {0}", entries);
for (String entry : entries) {
if (entry == null || entry.isEmpty()) {
continue;
}
File entryFile = new File(entry);
try {
if (!visitedClassPathEntries.add(entryFile.toURI().toURL())) {
continue;
}
ImmutableList.Builder<ScanResult> results = ImmutableList.builder();
Set<String> entries = ImmutableSet.of(javaClassPath.split(Pattern.quote(File.pathSeparator)));
logger.debugv("Scanning class path entries: {0}", entries);
for (String entry : entries) {
if (entry == null || entry.isEmpty()) {
continue;
}
File entryFile = new File(entry);
if (!entryFile.canRead()) {
throw CommonLogger.LOG.cannotReadClassPathEntry(entryFile);
}
try {
if (entryFile.isDirectory()) {
scanDirectory(entryFile, results);
} else {
scanJarFile(entryFile, results);
}
} catch (IOException e) {
throw CommonLogger.LOG.cannotScanClassPathEntry(entryFile, e);
}
if (!entryFile.exists()) {
CommonLogger.LOG.classPathEntryDoesNotExist(entryFile);
continue;
}
return results.build();
}

private void scanDirectory(File entryDirectory, ImmutableList.Builder<ScanResult> results) throws IOException {
// First try to find beans.xml
File beansXmlFile = new File(entryDirectory, AbstractWeldDeployment.BEANS_XML);
if (beansXmlFile.canRead()) {
logger.debugv(BEANS_XML_FOUND_MESSAGE, entryDirectory);
final BeansXml beansXml = parseBeansXml(beansXmlFile.toURI().toURL());
if (accept(beansXml)) {
results.add(new ScanResult(beansXml, entryDirectory.getPath()));
}
if (!entryFile.canRead()) {
throw CommonLogger.LOG.cannotReadClassPathEntry(entryFile);
}
if (entryFile.isDirectory()) {
scanDirectory(entryFile, results);
} else {
// No beans.xml found - check whether the bean archive contains an extension
logger.debugv(BEANS_XML_NOT_FOUND_MESSAGE, entryDirectory);
File extensionFile = new File(entryDirectory, EXTENSION_FILE);
if (!extensionFile.canRead()) {
results.add(new ScanResult(null, entryDirectory.getPath()));
}
scanJarFile(entryFile, results);
}
} catch (IOException e) {
throw CommonLogger.LOG.cannotScanClassPathEntry(entryFile, e);
}

Choose a reason for hiding this comment

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

The method scan() throws an exception if a class path entry is not readable, potentially halting the entire scanning process. This could be problematic in environments where partial results are still useful, or where certain class path entries might be expected to be unreadable due to permissions or other issues.

Recommended Solution:
Consider logging a warning and continuing with the next entry instead of throwing an exception. This approach would allow the scanning process to complete as much as possible, providing more robust behavior in diverse environments.

Comment on lines +92 to +197
try (FileInputStream fis = new FileInputStream(manifestFile)) {
final Manifest manifest = new Manifest(fis);
final Attributes manifestMainAttributes = manifest.getMainAttributes();
if (manifestMainAttributes.containsKey(CLASS_PATH)) {
scanManifestClassPath(entryDirectory.toURI().toURL(),
manifestMainAttributes.getValue(CLASS_PATH),
results);
}
}
}

private void scanJarFile(File entryFile, ImmutableList.Builder<ScanResult> results) throws IOException {
try (JarFile jar = new JarFile(entryFile)) {
JarEntry beansXmlEntry = jar.getJarEntry(AbstractWeldDeployment.BEANS_XML);
if (beansXmlEntry != null) {
logger.debugv(BEANS_XML_FOUND_MESSAGE, entryFile);
BeansXml beansXml = parseBeansXml(
new URL(PROCOTOL_JAR + ":" + entryFile.toURI().toURL().toExternalForm() + JAR_URL_SEPARATOR + beansXmlEntry.getName()));
if (accept(beansXml)) {
results.add(new ScanResult(beansXml, entryFile.getPath()));
}
} else {
// No beans.xml found - check whether the bean archive contains an extension
if (jar.getEntry(EXTENSION_FILE) == null) {
logger.debugv(BEANS_XML_NOT_FOUND_MESSAGE, entryFile);
results.add(new ScanResult(null, entryFile.getPath()));
}
}

Manifest manifest = jar.getManifest();
if (manifest != null) {
final Attributes manifestMainAttributes = manifest.getMainAttributes();
if (manifestMainAttributes.containsKey(CLASS_PATH)) {
scanManifestClassPath(entryFile.toURI().toURL(), manifestMainAttributes.getValue(CLASS_PATH), results);
}
}
}

private void scanJarFile(File entryFile,
ImmutableList.Builder<ScanResult> results)
throws IOException {
try (JarFile jar = new JarFile(entryFile)) {
JarEntry beansXmlEntry =
jar.getJarEntry(AbstractWeldDeployment.BEANS_XML);
if (beansXmlEntry != null) {
logger.debugv(BEANS_XML_FOUND_MESSAGE, entryFile);
BeansXml beansXml = parseBeansXml(new URL(
PROCOTOL_JAR + ":" + entryFile.toURI().toURL().toExternalForm() +
JAR_URL_SEPARATOR + beansXmlEntry.getName()));
if (accept(beansXml)) {
results.add(new ScanResult(beansXml, entryFile.getPath()));
}
} else {
// No beans.xml found - check whether the bean archive contains an
// extension
if (jar.getEntry(EXTENSION_FILE) == null) {
logger.debugv(BEANS_XML_NOT_FOUND_MESSAGE, entryFile);
results.add(new ScanResult(null, entryFile.getPath()));
}
}

Manifest manifest = jar.getManifest();
if (manifest != null) {
final Attributes manifestMainAttributes = manifest.getMainAttributes();
if (manifestMainAttributes.containsKey(CLASS_PATH)) {
scanManifestClassPath(entryFile.toURI().toURL(),
manifestMainAttributes.getValue(CLASS_PATH),
results);
}
}
}

private void scanManifestClassPath(URL context, String classPath, ImmutableList.Builder<ScanResult> results) {
Set<String> entries = ImmutableSet.of(MANIFEST_CLASSPATH_SEPARATOR_PATTERN.split(classPath));
for (String entry : entries) {
if (entry == null || entry.isEmpty()) {
continue;
}
try {
URL entryUrl = new URL(context, entry);
if (visitedManifestClassPathEntries.add(entryUrl) && entryUrl.getProtocol().equals("file")) {
File entryFile = new File(URI.create(entryUrl.toString()));
// do not throw an error here, as some libraries use the class path attribute wrongly
if (entryFile.canRead()) {
if (entry.endsWith("/")) {
scanDirectory(entryFile, results);
} else {
scanJarFile(entryFile, results);
}
}
}
} catch (IOException e) {
throw CommonLogger.LOG.cannotScanClassPathEntry(entry, e);
}

private void
scanManifestClassPath(URL context, String classPath,
ImmutableList.Builder<ScanResult> results) {
Set<String> entries =
ImmutableSet.of(MANIFEST_CLASSPATH_SEPARATOR_PATTERN.split(classPath));

Choose a reason for hiding this comment

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

The use of ImmutableSet.of() in lines 92 and 197 for splitting class path and manifest class path entries is not optimal for handling potentially large sets of entries. This method creates an immutable set, which can be inefficient in terms of memory and performance when dealing with large data sets.

Recommended Solution:
Consider using a more suitable data structure, such as HashSet, which offers better performance for large and mutable sets of entries. This change would enhance the efficiency and scalability of the class path scanning process.

@Message(id = 26, value = "Unable to instantiate {0} using parameters: {1}.",
format = Format.MESSAGE_FORMAT)
IllegalStateException
unableToInstantiate(Object param1, Object param2, @Cause Throwable cause);

Choose a reason for hiding this comment

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

The use of IllegalStateException in unableToInstantiate might not be the most appropriate choice for exception handling in this context. This exception typically indicates that the environment or application is not in an appropriate state for the requested operation, which may not accurately describe an instantiation failure.

Recommendation: Consider using a more specific exception, such as InstantiationException or a custom exception that more accurately reflects the failure to instantiate an object with given parameters. This change would improve the clarity and maintainability of the code by using exceptions that better describe the actual error condition.

Comment on lines +41 to +42
Logger.getMessageLogger(CommonLogger.class, Category.BOOTSTRAP.getName());

Choose a reason for hiding this comment

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

The static initialization of LOG using Logger.getMessageLogger is performed outside of any method or static block. This approach can lead to issues if the initialization of Category.BOOTSTRAP.getName() fails or if it depends on some other static fields or systems not yet ready during the class loading.

Recommendation: Consider initializing LOG within a static block or providing a static initialization method that handles potential exceptions and dependencies more gracefully. This would enhance the reliability and maintainability of the logger initialization process.

Comment on lines 166 to 175
* </pre>
*
* <p>
* The builder is reusable which means that it's possible to initialize multiple Weld containers with one builder. However, note that containers must have a
* unique identifier assigned when running multiple Weld instances at the same time.
* The builder is reusable which means that it's possible to initialize multiple
* Weld containers with one builder. However, note that containers must have a
* unique identifier assigned when running multiple Weld instances at the same
* time.
* </p>
*
* @author Peter Royle

Choose a reason for hiding this comment

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

The example provided in lines [166-175] demonstrates the initialization of a Weld container with various configurations. However, it is crucial to ensure that the example is complete and does not omit necessary steps that might be required for a new user to successfully run the example. It would be beneficial to include comments or additional context to explain each configuration option used in the example, such as what disableDiscovery() does or why certain packages are included. This would make the example more informative and useful for users who are not yet familiar with the Weld framework.


Set<T> inputs = getElements(page.getBody(), elementClass);

Choose a reason for hiding this comment

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

The method getElements is called for each element in the HTML page to find elements of a specific class. This could be inefficient if the page contains a large number of elements. Recommendation: Consider optimizing the getElements method to reduce the number of recursive calls or refactor the approach to use a more efficient algorithm for element retrieval, such as using a queue or stack as suggested in the existing comments.

Comment on lines +66 to +69
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK,
client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The CloseableHttpClient created in line 66 is not being closed after use, which can lead to resource leaks and potentially affect the performance of the test suite. It's recommended to use a try-with-resources statement to ensure that the client is closed properly after the request is made.

Suggested Change:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
    assertEquals(HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());
}

CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URL(baseURL, "cat").toExternalForm());
assertEquals(HttpServletResponse.SC_OK,
client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

The test method lacks comprehensive error handling. If client.execute(request) fails for any reason (e.g., network issues, server not responding), it could throw an exception or return a null response, leading to a NullPointerException when calling getStatusLine(). It's advisable to add null checks and proper exception handling to make the test more robust and prevent it from failing unexpectedly.

Suggested Change:

HttpResponse response = client.execute(request);
assertNotNull("Response should not be null", response);
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

Comment on lines 45 to 57
StringBuilder listeners = new StringBuilder();
listeners.append(toListener(BatRequestListener.class.getName()));
listeners.append(toListener(BatSessionListener.class.getName()));
listeners.append(toListener(BatServletContextListener.class.getName()));
Asset webXml = new ByteArrayAsset(
extendDefaultWebXml(
listeners.toString() +
("<servlet><servlet-name>Bat " +
"Servlet</servlet-name><servlet-class>") +
BatServlet.class.getName() +
("</servlet-class></servlet> <servlet-mapping><servlet-name>Bat " +
"Servlet</servlet-name><url-pattern>/bat</url-pattern></" +
"servlet-mapping>"))

Choose a reason for hiding this comment

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

Maintainability Issue in Web XML Construction

The construction of the webXml string in the createTestArchive method is done through multiple appends and inline XML content, which can be error-prone and hard to maintain, especially as the complexity of the XML structure grows.

Recommendation:
Refactor the XML string construction into a separate method or use a more structured approach like DOM manipulation or a templating library. This will make the code cleaner, reduce the chance of errors, and improve maintainability. For example:

private String constructWebXml() {
    // Use DOM manipulation or templating library to construct XML
    return constructedXml;
}

Comment on lines +71 to +92
assertEquals(HttpServletResponse.SC_OK,
client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=sce").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
}
@Test
public void testSceListenerInjection(@ArquillianResource URL baseURL)
throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request =
new HttpGet(new URL(baseURL, "bat?mode=sce").toExternalForm());
assertEquals(HttpServletResponse.SC_OK,
client.execute(request).getStatusLine().getStatusCode());
}

@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
}
@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL)
throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request =
new HttpGet(new URL(baseURL, "bat?mode=session").toExternalForm());
assertEquals(HttpServletResponse.SC_OK,
client.execute(request).getStatusLine().getStatusCode());

Choose a reason for hiding this comment

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

Improvement in Assertion Clarity

The assertions in the test methods only check for HttpServletResponse.SC_OK without any additional context or messages. When these assertions fail, it might not be clear what the expected behavior was or why the test failed.

Recommendation:
Enhance the assertions by providing a message that describes what the expected outcome should be. This will make the tests more understandable and easier to debug when they fail. For example:

assertEquals("Expected HTTP status 200 when testing request listener injection", HttpServletResponse.SC_OK, client.execute(request).getStatusLine().getStatusCode());

Comment on lines +85 to +86
String javaClassPath = AccessController.doPrivileged(
new GetSystemPropertyAction(JAVA_CLASS_PATH_SYSTEM_PROPERTY));

Choose a reason for hiding this comment

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

The method scan() uses AccessController.doPrivileged to read the system property for the class path. While this is generally a good practice for security, the code does not handle potential SecurityException that might be thrown if the security context does not allow reading the system property. This could lead to unhandled exceptions that may disrupt the application.

Recommended Solution:
Wrap the call to AccessController.doPrivileged in a try-catch block to catch SecurityException. Log an appropriate error message and handle the exception gracefully, possibly by skipping the class path scanning or providing a fallback mechanism.

Comment on lines +206 to +213
File entryFile = new File(URI.create(entryUrl.toString()));
// do not throw an error here, as some libraries use the class path
// attribute wrongly
if (entryFile.canRead()) {
if (entry.endsWith("/")) {
scanDirectory(entryFile, results);
} else {
scanJarFile(entryFile, results);

Choose a reason for hiding this comment

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

The method scanManifestClassPath converts URLs to File objects without verifying if the URL actually represents a file. This could lead to IllegalArgumentException if the URL is not formatted correctly for file conversion. Additionally, the method assumes that all URLs with a 'file' protocol can be directly converted to File objects, which might not always be the case, leading to errors when accessing the file system.

Recommended Solution:
Before converting a URL to a File, check if the URL is well-formed and valid for such conversion. Use URL.toURI() followed by new File(URI) and handle URISyntaxException which might be thrown if the URL is not a valid URI for file conversion. This ensures that only valid file URLs are processed, improving the robustness of the file handling logic.

Comment on lines +41 to +42
Logger.getMessageLogger(CommonLogger.class, Category.BOOTSTRAP.getName());

Choose a reason for hiding this comment

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

The static initialization of LOG using Logger.getMessageLogger(CommonLogger.class, Category.BOOTSTRAP.getName()) could potentially lead to issues if the Category.BOOTSTRAP enum or its method getName() has any side effects or throws an unchecked exception. Static initializers run when the class is first loaded, and any exceptions thrown at this time can prevent the class from being loaded, leading to a NoClassDefFoundError.

Recommendation: Consider wrapping this initialization in a static method that handles potential exceptions gracefully, ensuring that any issues with category name retrieval do not prevent class usage.

@Message(id = 26, value = "Unable to instantiate {0} using parameters: {1}.",
format = Format.MESSAGE_FORMAT)
IllegalStateException
unableToInstantiate(Object param1, Object param2, @Cause Throwable cause);

Choose a reason for hiding this comment

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

The method unableToInstantiate throws an IllegalStateException with a cause, but it might be more appropriate to use a more specific exception type that reflects the instantiation issue more accurately, such as InstantiationException. Using IllegalStateException here is too generic and does not convey the specific nature of the error, which is a failure in object instantiation due to constructor issues.

Recommendation: Replace IllegalStateException with InstantiationException or a custom exception that clearly indicates an instantiation failure, providing more clarity on the error.

Comment on lines 129 to 159
* </pre>
*
* <p>
* By default, the discovery is enabled so that all beans from all discovered bean archives are considered. However, it's possible to define a "synthetic" bean
* archive, or the set of bean classes and enablement respectively:
* By default, the discovery is enabled so that all beans from all discovered
* bean archives are considered. However, it's possible to define a "synthetic"
* bean archive, or the set of bean classes and enablement respectively:
* </p>
*
* <pre>
* WeldContainer container = new Weld().beanClasses(Foo.class, Bar.class).alternatives(Bar.class).initialize()) {
* WeldContainer container = new Weld().beanClasses(Foo.class,
* Bar.class).alternatives(Bar.class).initialize()) {
* </pre>
*
* <p>
* Moreover, it's also possible to disable the discovery completely so that only the "synthetic" bean archive is considered:
* Moreover, it's also possible to disable the discovery completely so that only
* the "synthetic" bean archive is considered:
* </p>
*
* <pre>
* WeldContainer container = new Weld().disableDiscovery().beanClasses(Foo.class, Bar.class).initialize()) {
* WeldContainer container = new
* Weld().disableDiscovery().beanClasses(Foo.class, Bar.class).initialize()) {
* </pre>
*
*
* <p>
* In the same manner, it is possible to explicitly declare interceptors, decorators, extensions and Weld-specific options (such as relaxed construction) using
* the builder.
* In the same manner, it is possible to explicitly declare interceptors,
* decorators, extensions and Weld-specific options (such as relaxed
* construction) using the builder.
* </p>
*
* <pre>

Choose a reason for hiding this comment

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

The documentation provided in this section is comprehensive and offers various examples of how to use the Weld class to configure and initialize CDI containers. However, it's crucial to ensure that all the configurations and methods mentioned are up-to-date and reflect the current capabilities of the Weld class. Any discrepancy between the documentation and the actual code can lead to confusion and misuse of the API.


// Init foo - set info archive deployment url
WebClient webClient = new WebClient();

Choose a reason for hiding this comment

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

The WebClient instance is created inside the test method without any configuration for cleanup or reuse. This can lead to resource leaks if the WebClient instances are not properly closed or if they accumulate over repeated test executions.

Recommendation:
Manage the lifecycle of WebClient more effectively by using a @Before or @After method to initialize and clean up the WebClient instances. This ensures that each test method starts with a clean state and helps prevent resource leaks.

Comment on lines +41 to +42
assertTrue(results.getWebResponse().getContentAsString().contains(
"onComplete: true"));

Choose a reason for hiding this comment

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

Potential Data Race Issue

The method testOnCompleteCalledSuccesfully uses a shared WebClient instance across different test methods without proper synchronization, which could lead to data races if tests are run in parallel. This issue can affect the reliability and correctness of test results.

Recommendation:
Ensure that each test method uses its own WebClient instance or properly synchronize access to shared resources to prevent data races.

Comment on lines +81 to +82
WebClient client = new WebClient();
HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf"));

Choose a reason for hiding this comment

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

The WebClient instance is created but not explicitly closed after use, which can lead to resource leaks. It's recommended to use a try-with-resources statement or finally block to ensure that resources are properly closed.

Recommended Solution:

try (WebClient client = new WebClient()) {
    HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf"));
    // rest of the code
}

Comment on lines +79 to +93
public void testELWithParameters(@ArquillianResource URL baseURL)
throws Exception {
WebClient client = new WebClient();
HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf"));

page.asXml();

HtmlSpan oldel = getFirstMatchingElement(page, HtmlSpan.class, "oldel");
assertNotNull(oldel);
final String charlie = "Charlie";
assertEquals(charlie, oldel.asNormalizedText());

HtmlSpan newel = getFirstMatchingElement(page, HtmlSpan.class, "newel");
assertNotNull(newel);
assertEquals(charlie, newel.asNormalizedText());

Choose a reason for hiding this comment

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

The method testELWithParameters lacks error handling for potential exceptions such as MalformedURLException from new URL(baseURL, "charlie.jsf") and null checks for oldel and newel elements. This can lead to unhandled exceptions during test execution, affecting test reliability.

Recommended Solution:
Add appropriate try-catch blocks to handle possible exceptions and include null checks before using the elements.

try {
    HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf"));
    HtmlSpan oldel = getFirstMatchingElement(page, HtmlSpan.class, "oldel");
    assertNotNull(oldel);
    // similar for newel
} catch (MalformedURLException e) {
    // handle exception
}

Comment on lines 44 to 62
public static WebArchive createTestArchive() {
StringBuilder listeners = new StringBuilder();
listeners.append(toListener(BatRequestListener.class.getName()));
listeners.append(toListener(BatSessionListener.class.getName()));
listeners.append(toListener(BatServletContextListener.class.getName()));
Asset webXml = new ByteArrayAsset(
extendDefaultWebXml(
listeners.toString() +
("<servlet><servlet-name>Bat " +
"Servlet</servlet-name><servlet-class>") +
BatServlet.class.getName() +
("</servlet-class></servlet> <servlet-mapping><servlet-name>Bat " +
"Servlet</servlet-name><url-pattern>/bat</url-pattern></" +
"servlet-mapping>"))
.getBytes());
return baseDeployment(webXml).addClasses(
BatRequestListener.class, BatSessionListener.class,
BatServletContextListener.class, BatListener.class, BatServlet.class,
Sewer.class);

Choose a reason for hiding this comment

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

Maintainability and Error-Prone String Manipulation

The method createTestArchive uses a series of string concatenations to construct the XML content for the deployment descriptor. This approach is error-prone and can lead to hard-to-maintain code, especially as modifications to the XML structure become necessary. The use of StringBuilder and manual XML construction increases the risk of typos and structural errors in the XML.

Recommendation:
Consider using a more structured approach to generate XML, such as JAXB or another XML generation library. This would reduce the risk of errors and improve the readability and maintainability of the code. For example:

JAXBContext jaxbContext = JAXBContext.newInstance(WebXml.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.marshal(webXmlObject, byteArrayOutputStream);
Asset webXml = new ByteArrayAsset(byteArrayOutputStream.toByteArray());

@Message(id = 26, value = "Unable to instantiate {0} using parameters: {1}.",
format = Format.MESSAGE_FORMAT)
IllegalStateException
unableToInstantiate(Object param1, Object param2, @Cause Throwable cause);

Choose a reason for hiding this comment

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

The method unableToInstantiate uses IllegalStateException to indicate problems during instantiation, which is not very descriptive of the actual issue, which is an instantiation failure. This could lead to confusion when handling exceptions, as IllegalStateException might suggest that the method was called at an inappropriate time or that the environment was not correctly configured.

Recommendation: Use a more specific exception like InstantiationException or a custom exception that clearly indicates an instantiation failure. This change would make the error handling more intuitive and the code easier to maintain.

@Message(id = 34, value = "Cannot scan class path entry: {0}",
format = Format.MESSAGE_FORMAT)
IllegalStateException
cannotScanClassPathEntry(Object entry, @Cause Throwable cause);

Choose a reason for hiding this comment

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

The method cannotScanClassPathEntry throws an IllegalStateException when it encounters an issue scanning a class path entry. This exception type is generally used to indicate that a method has been invoked at an illegal or inappropriate time, which is not necessarily indicative of the issues related to class path scanning.

Recommendation: Consider using a more specific exception, such as IOException or a custom ClassPathScanningException. This would provide clearer information about the nature of the error and improve the maintainability and clarity of the code.

@@ -11,8 +11,9 @@
import org.jboss.weld.exceptions.IllegalArgumentException;

Choose a reason for hiding this comment

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

The import of IllegalArgumentException from org.jboss.weld.exceptions instead of the standard java.lang package could lead to confusion. Developers might assume that the standard Java exception is being used, which could cause issues in exception handling.

Suggested Change:
Consider renaming the custom exception to avoid confusion with the standard IllegalArgumentException, or ensure that there is clear documentation and usage distinction in the codebase.

Comment on lines +41 to +44
@Message(id = 2002, value = "Weld SE container {0} was already shut down",
format = Format.MESSAGE_FORMAT)
IllegalStateException
weldContainerAlreadyShutDown(Object id);

Choose a reason for hiding this comment

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

The method weldContainerAlreadyShutDown throws an IllegalStateException which is appropriate for the error condition it handles. However, the method could be improved by including more context in the exception message, such as the current state of the container or suggestions for next steps. This would aid developers or system administrators in troubleshooting and resolving the issue more efficiently.

Suggested Change:

@Message(id = 2002, value = "Weld SE container {0} was already shut down. Current state: {1}", format = Format.MESSAGE_FORMAT)
IllegalStateException weldContainerAlreadyShutDown(Object id, String currentState);

Comment on lines +65 to +72
@Test
public void testIsResolvable(Client client) {
try (WeldContainer container = new Weld().initialize()) {
assertTrue(container.select(Alpha.class).isResolvable());
assertFalse(container.select(BigDecimal.class, Juicy.Literal.INSTANCE)
.isResolvable());
}

@Test
public void testGetHandler() {
}

Choose a reason for hiding this comment

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

Resource Management Improvement

The test method testIsResolvable uses a try-with-resources statement to manage the WeldContainer, which is good practice. However, the test could be improved by explicitly checking that all resources are properly released after the try block. This can be particularly important in a container environment to prevent resource leaks. Consider adding assertions or checks after the try block to ensure that all resources, such as threads or connections, are cleaned up.

// After try block
assertFalse(container.isRunning());

Comment on lines +119 to +125
} catch (RuntimeException e) {
throw e;
} catch (java.lang.reflect.InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}

Choose a reason for hiding this comment

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

The method defineClass handles exceptions by catching them and rethrowing as RuntimeException. This practice can obscure the original exception details and does not enforce handling of these exceptions in the calling code, potentially leading to unhandled runtime exceptions.

Recommendation:
Refine the exception handling to throw more specific exceptions or ensure that the original exceptions are properly logged and documented. Additionally, consider declaring checked exceptions to enforce error handling in the calling code.

}
this.executor = new ThreadPoolExecutor(
threadPoolSize, threadPoolSize, keepAliveTime, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),

Choose a reason for hiding this comment

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

The LinkedBlockingQueue used for tasks in the thread pool is initialized without a capacity limit. This can lead to excessive memory usage if a large number of tasks are submitted and not processed quickly enough, potentially causing OutOfMemoryError under high load.

Recommendation:
Consider initializing the LinkedBlockingQueue with a specific capacity limit to prevent such issues. For example:

new LinkedBlockingQueue<Runnable>(1000);

public int getPoolSize() {
return executor.getPoolSize();
}
BootstrapLogger.LOG.threadsInUse(threadPoolSize);

Choose a reason for hiding this comment

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

The logging statement that logs the number of threads in use is placed immediately after the thread pool executor is created. At this point, the executor has not started processing any tasks, so this log might not provide meaningful information about the actual thread usage.

Recommendation:
Consider moving this logging statement to a location where it can reflect more accurate information, such as after some tasks have been executed, or modify it to log more relevant runtime information.

Comment on lines +91 to +94
@Message(id = 9, value = "Dynamic lookup of {0} is not supported",
format = Format.MESSAGE_FORMAT)
IllegalArgumentException
dynamicLookupOfBuiltInNotAllowed(Object param1);

Choose a reason for hiding this comment

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

The method dynamicLookupOfBuiltInNotAllowed throws an IllegalArgumentException with a generic message about dynamic lookup not being supported. While this is generally acceptable, it could be enhanced by providing more context about why the lookup is not allowed or under what conditions it might be allowed, if any. This would help developers understand the limitations more clearly and adjust their code accordingly.

Suggested Improvement:
Consider adding more details to the exception message or include a link to documentation or guidelines that explain this constraint in detail.

Comment on lines +285 to +290
invocationError(Object param1, Object param2, @Cause Throwable cause);

@Message(id = 50, value = "Cannot cast producer type {0} to bean type {1}",
format = Format.MESSAGE_FORMAT)
WeldException
producerCastError(Object param1, Object param2, @Cause Throwable cause);

Choose a reason for hiding this comment

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

The method producerCastError logs an error and throws a WeldException when a producer type cannot be cast to a bean type. This is critical as it directly affects the application's runtime behavior. However, the method could be improved by logging more diagnostic information.

Suggested Improvement:
Include additional logging before throwing the exception to capture the state or values that led to this error. This could be instrumental in diagnosing the issue faster, especially in production environments where debugging might not be straightforward.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
NO JIRA This PR does not have a Jira Ticket PR:CONFLICT This PR has a conflict PR:size/XXL Denotes a Pull Request that changes 1000+ lines. size/XXL
Projects
None yet
Development

Successfully merging this pull request may close these issues.