Aspectj internal error unable to add stackmap attributes null

Hi , guys I setup Java 1.8 and can't run UI test with Allure. Seems that AspectJ and java 1.8 issue. Then I run test. I have error: Maven Settings: 1.7</compiler.vers...

Hi , guys

I setup Java 1.8 and can’t run UI test with Allure. Seems that AspectJ and java 1.8 issue. Then I run test. I have error:

Maven Settings:

<compiler.version>1.7</compiler.version>
<allure.version>1.4.4</allure.version>
<aspectj.version>1.8.4</aspectj.version>


… TestNG 6.8.2beta_20130330_0839 by C�dric Beust (cedric@beust.com)

AspectJ Internal Error: unable to add stackmap attributes. null

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.17:test (default-test) on project ui-test: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.17:test failed: There was an error in the forked process
[ERROR] java.lang.VerifyError: Expecting a stackmap frame at branch target 56
[ERROR] Exception Details:
[ERROR] Location:
[ERROR] com/zoomdata/base/CustomTestListener.onTestFailure(Lorg/testng/ITestResult;)V @44: ifnull
[ERROR] Reason:
[ERROR] Expected stackmap frame at this location.
[ERROR] Bytecode:
[ERROR] 0000000: 2ab7 0010 572a b400 04bb 0005 59b7 0006
[ERROR] 0000010: 1211 b600 082b b900 0e01 00b6 0008 b600
[ERROR] 0000020: 0bb9 000c 0200 2bb9 0012 0100 c600 0c2b
[ERROR] 0000030: b900 1201 00b6 0013 b1
[ERROR] 
[ERROR] at java.lang.Class.getDeclaredConstructors0(Native Method)
[ERROR] at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
[ERROR] at java.lang.Class.getConstructor0(Class.java:2964)
[ERROR] at java.lang.Class.newInstance(Class.java:403)
[ERROR] at org.testng.internal.ClassHelper.newInstance(ClassHelper.java:49)
[ERROR] at org.testng.TestRunner.initListeners(TestRunner.java:324)
[ERROR] at org.testng.TestRunner.init(TestRunner.java:238)
[ERROR] at org.testng.TestRunner.init(TestRunner.java:205)
[ERROR] at org.testng.TestRunner.<init>(TestRunner.java:153)
[ERROR] at org.testng.SuiteRunner$DefaultTestRunnerFactory.newTestRunner(SuiteRunner.java:522)
[ERROR] at org.testng.SuiteRunner.init(SuiteRunner.java:157)
[ERROR] at org.testng.SuiteRunner.<init>(SuiteRunner.java:111)
[ERROR] at org.testng.TestNG.createSuiteRunner(TestNG.java:1299)
[ERROR] at org.testng.TestNG.createSuiteRunners(TestNG.java:1286)
[ERROR] at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
[ERROR] at org.testng.TestNG.run(TestNG.java:1057)
[ERROR] at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:293)
[ERROR] at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
[ERROR] at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:91)
[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

Содержание

  1. Java 11 and AspectJ LTW #909
  2. Comments
  3. Steps to reproduce
  4. Expected behaviour
  5. Actual behaviour
  6. Footer
  7. JaCoCo 0.8.4 and Java 11 Agent Conflict #68
  8. Comments
  9. Unable to weave classes with java 1.8 #103
  10. Comments
  11. VAT/P.I.: IT06275970967

Java 11 and AspectJ LTW #909

After updating to JDK 11 the Maven Surefire plugin fails to run when both Jacoco agent and AspectJ weaver agent present.

Steps to reproduce

JaCoCo version: 0.8.4
Operating system: Windows 10
JDK: open-jdk-11.0.1
Tool integration: Maven
aspectjweaver: 1.9.4

Expected behaviour

Tests to run as they did in JDK 8.

Actual behaviour

The text was updated successfully, but these errors were encountered:

Seems to be resolved by using 0.8.3

Seems to be resolved by using 0.8.3

the only change in JaCoCo version 0.8.4 that can explain this — is usage of condy (https://openjdk.java.net/jeps/309) for Java 11+ classes introduced by #845. Therefore I’m pretty sure that version of AspectJ weaver agent that you use doesn’t correctly/fully support Java 11 bytecode.

Looking only at the error message in stacktrace

Method «$jacocoData» in class #/function/bank/BankFeedRuleFunctionTest has illegal signature «Ljava/lang/Object;»

one can only say that $jacocoData generated by JaCoCo for Java 11+ classes is not method, but a name of dynamic constant aka condy with absolutely valid signature of type Ljava/lang/Object; — see https://github.com/jacoco/jacoco/blob/v0.8.4/org.jacoco.core/src/org/jacoco/core/internal/instr/CondyProbeArrayStrategy.java#L56-L57 Addition of complete reproducer might help to nail why/how AspectJ messes this.

In any case please report this to developers of AspectJ weaver agent.

Thank you for your quick response.

FYI, if anyone else has the same problem in the future: This is neither a JaCoCo nor an AspectJ problem, but simply caused by the fact that aspects were applied too broadly during load-time weaving, AspectJ also weaving aspects into Surefire, JUnit and JaCoCo itself. Proper AspectJ configuration avoids this, as explained in eclipse/org.aspectj#68 (comment) and proven in https://github.com/kriegaex/AJ_LTWJacocoWeavingProblem_549438. That it worked before in JDK 8 was pure luck.

@Godin @kriegaex tried your options but still doesn’t work with Java 17. My aspects applied only within my app packages and i can confirm that from the .dumpstream files.
AspectJ: 1.9.8.RC3 (tried 1.9.7 as well)
JDK: Zulu 17.0.1
OS: Win 10
Jacoco: 0.8.7

@ibragfir, please do not hijack this closed issue. Firstly, it was created in July 2019 when the most recent Java release was 12. The LTS was 11, and this question also is about Java 11. Like I have proven in my answer, the issue was simply wrong AspectJ load-time weaving configuration and neither a JaCoCo problem nor an AspectJ bug.

I am not actually a JaCoCo user and only was involved here because AspectJ was in the game. But if you read the JaCoCo 0.8.7 release notes, you will see that Java 17 support is marked as «experimental» there. That using another JaCoCo build with a special patch works for you, indicates that there is an actual JaCoCo problem with Java 17. This should be dealt with in a separate issue, not in this one, because the two topics are unrelated. I suggest you create one (please first check if one exists already), add an MCVE and feel free to link back to your comment here where the story started accidentally. Thank you.

Besides, if you want to use the AspectJ compiler with Java 17, 1.9.8.RC3 is the correct version. 1.9.7 knows nothing about Java 17. For LTW that might still work, if there are not bytecode constructs unknown to the aspect weaver. But to be on the safe side, stick to 1.9.8.RC3.

@kriegaex thanks. I don’t see a problem with aspects being applied too broadly in this case. Does it explain the underlying issue?
I commented here because that patch solved the issue for me with Java 11 and Jacoco 0.8.4 as well and I believe this is the same problem that was introduced with Jacoco 0.8.4 and might be helpful for others. Thanks for your reply and recommendations.

It explains the issue as described here. You are, according to your own words, using my solution for the issue, experiencing a completely different problem solved by upgrading JaCoCo. Therefore, you are off topic here and should open a new issue for your problem, like I said. If you disagree, publish an MCVE proving your point.

I’m experiencing exactly the same issue with Java 11 and Java 17 which can be solved by using that patched version of JaCoCo.
I can’t publish the code of the company here but I have checked out your example and in that you’re not actually reproducing the same issue.

The author here raised this problem which is exactly the one I’m trying to find a solution for.

AspectJ Internal Error: unable to add stackmap attributes. null
Method «$jacocoData» in class #/function/bank/BankFeedRuleFunctionTest has illegal signature «Ljava/lang/Object;»
[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
[ERROR] Method «$jacocoData» in class #/function/bank/BankFeedRuleFunctionTest has illegal signature «Ljava/lang/Object;»

And I don’t think it was pure luck that it was working with Java 8 but the fact that the author upgraded from 0.8.3 to 0.8.4 along with Java 11. He wouldn’t be able to use 0.8.4 with Java 8 since JaCoCo 0.8.4 is using Java 11+ feature (https://openjdk.java.net/jeps/309).

Actually he could and worked because there’s a condition not to use dynamic constants if the version is not >=11

I’m experiencing exactly the same issue with Java 11 and Java 17

Why did you not say that right from the beginning? You only talked about Java 17 and different JaCoCo and AspectJ versions than the ones in this issue.

I can’t publish the code of the company here

That is a lame excuse, unworthy of a developer. I said MCVE, not «original code». Simply fork my repository and adjust it until it reproduces the problem. Basically, your claim is «it does not work the way @kriegaex suggested» without even a scintilla of proof. I cannot debug what I cannot see. Can you?

I have checked out your example and in that you’re not actually reproducing the same issue.

That might be true, my solution is still to be applied — maybe in addition to whatever fix there might be necessary in JaCoCo — in order to avoid instrumenting the bytecode of tools like JaCoCo, JUnit and Surefire when running tests including aspects which apply too broadly.

I can’t publish the code of the company here

That is a lame excuse, unworthy of a developer. I said MCVE, not «original code». Simply fork my repository and adjust it until it reproduces the problem.

OK, I just did that for you, see my latest commits. I managed to reproduce the problem now, despite excluding foreign packages, by adding something using virtual methods (a Shape interface and a class Circle implementing it), then adding a test for same. My original class under test was simpler than that.

It is actually #1151, which also the patch you mentioned relates to. See also JEP 309. I built the current JaCoCo snapshot locally without the patch, and it still reproduces the problem. With the patch, like you said, the problem goes away. Now we have something reproducible to look into for AspectJ.

OK, the solution is actually very simple, see eclipse/org.aspectj#68 (comment). Quote:

When running Maven with debug logging, I see (with added line breaks and comments):

I.e., the JaCoCo agent is applied first and then the AspectJ weaver needs to deal with JaCoCo-instrumented byte code, whereas it should be the other way around: JaCoCo should create a coverage report for AspectJ-enhanced classes. So I added commit 487552b8, simply reversing the order of agents on the Surefire command line. This fixes the problem.

Bottom line: The order of Java agents simply was wrong. JaCoCo has to be applied after AspectJ. I had not thought of that before, but should have suggested it in the first place, in addition to limiting the aspect scope, which is still necessary.

Incorrect Surefire configuration:

Correct Surefire configuration:

OK, reversing the order of instrumentation agents is suboptimal, because it might lead to incorrect coverage data, applying JaCoCo instrumentation to byte code no longer corresponding to the source code it was compiled from, now also containing aspect code. Today I found a better solution when re-investigating a related problem, see eclipse/org.aspectj#170 (comment): use the -XnoInline AspectJ compiler or weaver option. This even enables you to get coverage data for the aspects themselves, if they are also compiled in the same module and have been instrumented by JaCoCo. This solution works in the current AspectJ version 1.9.9.1 and also back to 1.9.8 which fixed an old condy bug. In 1.9.9.2 (or 1.9.10, whatever comes first, a maintenance release or the Java 19 one), I will also improve the still incomplete AspectJ condy support some more, but for JaCoCo that is not necessary.

If a JaCoCo maintainer like @Godin is listening here: The fact that JaCoCo uses the exact same dynamic constant name and initialisation method name in each instrumented class is what causes problem with byte code engineering tools inlining code from class A into class B due to name clashes. Unique names like $jacocoData_[something_unique] and $jacocoInit_[something_unique] would help in this case. AspectJ would not be the only tool profiting from this enhancement. I remember that Byte Buddy advice code can also be inlined. That should lead to similar problems, if the BB code is covered by JaCoCo.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

JaCoCo 0.8.4 and Java 11 Agent Conflict #68

Expected behaviour Tests to run as they did in JDK 8. Actual behaviour [INFO] ——————————————————- [INFO] T E S T S [INFO] ——————————————————- AspectJ Internal Error: unable to add stackmap attributes. null [INFO] [INFO] Results: [INFO] [INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— [INFO] Total time: 30.903 s [INFO] Finished at: 2019-07-19T15:04:42+01:00 [INFO] Final Memory: 79M/280M [INFO] ———————————————————————— [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project ***: There are test failures. [ERROR] [ERROR] Please refer to C:Users#IdeaProjects#servicestargetsurefire-reports for the individual test results. [ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream. [ERROR] There was an error in the forked process [ERROR] Method «$jacocoData» in class #/function/bank/BankFeedRuleFunctionTest has illegal signature «Ljava/lang/Object;» [ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process [ERROR] Method «$jacocoData» in class #/function/bank/BankFeedRuleFunctionTest has illegal signature «Ljava/lang/Object;» [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:656) [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:282) [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:245) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1183) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1011) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:857) [ERROR] at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) [ERROR] at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) [ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) [ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) [ERROR] at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) [ERROR] at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) [ERROR] at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) [ERROR] at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:566) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) [ERROR] at org.codehaus.classworlds.Launcher.main(Launcher.java:47)»>

from myself it is reproducible on

  • openjdk 11
  • jacoco 0.8.4 (and later)
  • aspectj 1.9.6 (also tried 1.9.7 milestones)

this issue is pretty well described (with sample project) in jacoco/jacoco#909
see comment jacoco/jacoco#909 (comment)

current workaround: downgrade jacoco to 0.8.3

The text was updated successfully, but these errors were encountered:

Источник

Unable to weave classes with java 1.8 #103

Hi,
i’ve receive this warning when I try to build a project with maven and jcabi-aspects:

[WARNING] Found @DeclareAnnotation while current release does not support it (see ‘org.aspectj.weaver.bcel.AtAjAttributes’)

Indeed, I receive this error

AspectJ Internal Error: unable to add stackmap attributes. null

I’m using jcabi-maven-plugin:0.9.4 and jcabi-aspects:0.20

Thank for your support.

The text was updated successfully, but these errors were encountered:

The strange thing is that if I build the project inside eclipse (using m2e) it works.

try the new version of jcabi-maven-plugin.

Thank you for merge, now it just works.
I must add these lines in the build section of my pom file otherwise jcabi-maven-plugin use an old version of ajc (1.7.3) also if in other part of my pom I use the new version of aspectj !

Maybe you create a short site documentation page about it? Other users may have similar problems, would be great to have an «example» page on the site to explain the solution.

I am just writing it on the Readme.md of my forked version.
May you tell me a better solution?
Thanks in advance.

On Thu, Nov 6, 2014 at 4:05 PM, Yegor Bugayenko notifications@github.com
wrote:

Maybe you create a short site documentation page about it? Other users may
have similar problems, would be great to have an «example» page on the site
to explain the solution.


Reply to this email directly or view it on GitHub
#103 (comment).

Emiliano Bonassi
AssBenaz.COM
Via Alpamayo 13
20854 Vedano Al Lambro (MI) IT
Mob/Cell: +39 349 49 93 036

VAT/P.I.: IT06275970967

NOTICE TO RECIPIENTS: The information contained in and accompanying this
communication may be confidential, subject to legal privilege, or otherwise
protected from
disclosure, and is intended solely for the use of the intended
recipient(s). If you are not
the intended recipient of this communication, please delete and destroy all
copies in your
possession, notify the sender that you have received this communication in
error, and note that
any review or dissemination of, or the taking of any action in reliance on,
this communication is
expressly prohibited.

«INFORMAZIONE PER IL RICEVENTE: Le informazioni che sono contenute o che
accompagnano questa comunicazione potrebbero essere riservate, coperte da
segreto professionale, o altrimenti protette da altre restrizioni alla loro
divulgazione, e sono destinate esclusivamente alle persone alle quali
questa comunicazione é indirizzata. Se questa comunicazione non é
indirizzata a Voi, siete pregati di distruggerne tutte le copie in Vostro
possesso, di notificarci che avete ricevuto questa comunicazione per
errore, e di considerare che sono espressamente vietate la lettura, la
diffusione o la distribuzione totale o parziale di questa comunicazione,
nonché l’agire sulla base di (informazioni contenute in) questa
comunicazione.

Источник

Table of Contents

  1. Maven Dependencies
  2. logback configuration
  3. AOP Annotations
  4. Update
  5. Summary

Have you ever found yourself in situation wherein your application is not behaving as expected in staging or production? If it’s the case in your local, you can easily debug the code but debugging a remotly running application is not easy & definitly not recommened. In such situation, the very first thing that comes to our mind is logging.

Logging is simple & easy to implement. You want to log something, just go ahead & add the log statement in your code. The only issue with logging is that it’s dependent upon the person adding the log statement. For some it’s a good thing to have, for other’s don’t add unless it’s really required. But once things start to go wrong in production, the very first thing we say to ourself is .. uhh I should have logged the method call. This is where AOP(Aspect Oriented Programming) comes into picture. The idea behind AOP is simple, you annotate your code & the AOP library replaces those annotations with appropriate runtime code. AOP is two step process :

  • Language compiler compiles the code
  • AOP library goes through the compiled class files & replaces the AOP specific annotations. This process is called weaving.

In this blog post, I am going to use an open source library called jcabi-aspects for implementing loggable aspect.

Before we can see AOP in action, we will have to get following things done :

  • Create new maven project
  • Add dependency for
    • logback library for logging
    • jcabi-aspects
  • SetUp logback logging framework
  • Create relevant class & methods for AOP demo

So go ahead & create a new maven project & give it a name of your choice.

Maven Dependencies


You can copy paste the content below in your pom.xml file & if you have enabled auto-import, then maven will download the relevant dependencies for you.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <dependencies>
        <dependency>
            <groupId>com.jcabi</groupId>
            <artifactId>jcabi-aspects</artifactId>
            <version>0.22.5</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.9</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.10</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-ext</artifactId>
            <version>1.7.10</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>log4j-bridge</artifactId>
            <version>0.9.7</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

In the above pom files, we have included following dependencies :

  • aspectjrt is the AOP library & jcabi-aspects contains the annotations that we are going to use in our application
  • logback & dependent slf4j library dependencies for adding logging support
  • groovy-all for parsing the logback.groovy file which in turn will contain our log configuration
  • In the build section, I have included maven compiler plugin & configuration for copying dependency jars in target/lib directory

logback configuration


Normally log configuration is done via xml file but we are going to use groovy script file. Add a file called logback.groovy at ~/src/main level and in that file add the following content :

import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy

import static ch.qos.logback.classic.Level.INFO

appender("console", ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        pattern = "%d %-8X{name} version=%-15X{version} loglevel=%-6p category=%-40.40c{0} message=%m%n"
    }
}

root(INFO, ["console"])

Unlike file based logging, we are going to log everything in console. Lets test if logging is working fine or not.

Add Main.java file at ~src/main/java level and add the following content :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by mishrapaw on 7/25/16.
 */
public class Main
{
    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(Main.class);
        logger.info("Starting main");
    }
}

Next we have to compile & run the code. For compilation run the following commands via command line :

mvn clean install
mvn compile

If compilation is successful, then we can go ahead & run the main method in Main.java class file via command :

/usr/local/java18/bin/java -cp target/classes/:target/lib/* Main

The code will run & it will print the following :

21:52:44.965 [main] INFO  Main - Starting main

With this we are done with our logging related work. Lets go ahead & experience AOP awasomness.

AOP Annotations

In order to test, AOP in action, we are going to create a new class say Weaving.java & add some public methods to it. Next we will annotate that class & methods to see the AOP loggable behavior in action. Go ahead & add a class called Weaving.java with following code at ~/src/main/java level.

import com.jcabi.aspects.Loggable;

@Loggable
public class Weaving
{
    public void printWeaving()
    {
        System.out.println("Printing waeving!!");
    }

    public void printWeavingMessage(String message)
    {
        System.out.println("Print message : " + message);
    }

    public String printAndReturnWeavingMessage(String message)
    {
        System.out.println("Print return message : " + message.toUpperCase());
        return message.toUpperCase();
    }

    public void printAnotherWeavingMessage()
    {
        System.out.println("Another waving message");
    }

    private void testMethod()
    {

    }
}

Notice that I have annotated the class with @Loggable annotation. Next in Main.java main method, add following lines :

public static void main(String[] args) {
        Weaving weaving = new Weaving();
        weaving.printWeaving();
        weaving.printWeavingMessage("From main");
        weaving.printAndReturnWeavingMessage("fromMain");
    }

Next same old steps :

$ mvn clean install
$ mvn compile
$ /usr/local/java18/bin/java -cp target/classes/:target/lib/* Main

The code will run fine but it print the following output, which though seems correct is not what we wanted. Did we forget something?

Printing waeving!!
Print message : From main
Print return message : FROMMAIN

In the beginning of the article, I mentioned about how AOP library weaves the class files & replaces the annotations with appropriate code. In our case, our code compiled fine but weaving didn’t happen. You can confrm this by checking the mvn compile console log statements. In order to fix this just add the following plugin xml content in pom.xml file under tag.

<plugin>
    <groupId>com.jcabi</groupId>
    <artifactId>jcabi-maven-plugin</artifactId>
    <version>0.9</version>
    <executions>
        <execution>
            <goals>
                <goal>ajc</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Next go ahead and run mvn clean followed by mvn install command. This time in console, you will see aspectj related log statements :

[INFO] --- jcabi-maven-plugin:0.9:ajc (default) @ aspectj-weaving ---
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] JSR-303 validator org.hibernate.validator.internal.engine.ValidatorImpl instantiated by jcabi-aspects 0.10/7ee832c
[INFO] jcabi-aspects 0.10/7ee832c started new daemon thread jcabi-loggable for watching of @Loggable annotated methods
[INFO] jcabi-aspects 0.10/7ee832c started new daemon thread jcabi-cacheable for automated cleaning of expired @Cacheable values
AspectJ Internal Error: unable to add stackmap attributes. null
[WARNING] advice defined in com.jcabi.aspects.aj.ExceptionsLogger has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.Repeater has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodValidator has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.SingleException has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodInterrupter has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.QuietExceptionsLogger has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.Parallelizer has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodAsyncRunner has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodCacher has not been applied [Xlint:adviceDidNotMatch]
[INFO] ajc result: 6 file(s) processed, 4 pointcut(s) woven, 0 error(s), 12 warning(s)

Inore the warning for now. The very last line says ajc result: 6 file(s) processed, 4 pointcut(s) woven, 0 error(s), 12 warning(s). So now aspectjrt has weaved our class files. It’s time to run our application.

/usr/local/java18/bin/java -cp target/classes/:target/lib/*  Main

But now you will get another crazy error :

Exception in thread "main" java.lang.VerifyError: Expecting a stackmap frame at branch target 52
Exception Details:
  Location:
    WeavingTest/Weaving.printWeaving()V @15: ifne
  Reason:
    Expected stackmap frame at this location.
  Bytecode:
    0x0000000: b200 422a 2ab8 0048 4cb2 0067 b600 6d9a
    0x0000010: 0025 b800 5d05 bd00 0e4d 2c03 2a53 2c04
    0x0000020: 2b53 bb00 4d59 2cb7 0050 1251 b600 57b6
    0x0000030: 0061 57b1 2a2b b800 63b1       
        at Main.main(Main.java:13)

Well fixing this error is easy(discussing though is not, may be some other time). Just add -noverify flag to our previous statement :

/usr/local/java18/bin/java -cp target/classes/:target/lib/* -noverify Main

And this time the magic happens :

22:18:41.729 [main] INFO  com.jcabi.aspects.aj.NamedThreads - jcabi-aspects 0.22.5/4a18718 started new daemon thread jcabi-loggable for watching of @Loggable annotated methods
Printing waeving!!
22:18:41.754 [main] INFO  WeavingTest.Weaving - #printWeaving(): in 1.01ms
Print message : From main
22:18:41.756 [main] INFO  WeavingTest.Weaving - #printWeavingMessage('From main'): in 70.50µs
Print return message : FROMMAIN
22:18:41.757 [main] INFO  WeavingTest.Weaving - #printAndReturnWeavingMessage('fromMain'): 'FROMMAIN' in 55.11µs

As we can see from above, just by adding @Loggable annotation, the framework is logging for us the input & return values along with the total running time of the method.

Update


The above mentioned error : “Expecting a stackmap frame at branch target 52” was happening because I was using old version of jcabi-maven-plugin. Migrating to latest version(0.14) solves the problem. With the stackmap error gone, we won’t require the -noverify flag as well.

Summary


This is just the basic usage of @Loggable annotation. The annotation can be overloaded with additional flags and there are other annotations too that you can try & use as per your convinience. You can read more about it here.

Recently upgraded a large project from Java 11 to 13. I am using AspectJ for logging purposes and I am now getting this error on startup :

AspectJ Internal Error: unable to add stackmap attributes. Unsupported class file major version 57

Looks clear as day that Java 13 is not supported and looking at the AspectJ site they mention Java 12 support added in version 1.9.3 but as of the latest one, 1.9.4, still no mention of Java 13 support.

Any idea if there is a way around this or if the project will be updated again soon? The last release was in May…

UPDATE

As requested, here are my dependency declarations :

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
    </dependency>

And here are my Java Agent declarations :

-javaagent:lib/aspectjweaver-1.9.4.jar -javaagent:lib/spring-instrument-5.2.0.RELEASE.jar

Thanks

Hi,

I am seeing the following error in console —

AspectJ Internal Error: unable to add stackmap attributes. null
[WARNING] advice defined in com.jcabi.aspects.aj.MethodLogger has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.ImmutabilityChecker has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodScheduler has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.ExceptionsLogger has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.Repeater has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodValidator has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.SingleException has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodInterrupter has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.QuietExceptionsLogger has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.Parallelizer has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodAsyncRunner has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in com.jcabi.aspects.aj.MethodCacher has not been applied [Xlint:adviceDidNotMatch]

Later when I try to run the application without «-noverify» flag, I get the following error —

Exception in thread "main" java.lang.VerifyError: Expecting a stackmap frame at branch target 52
Exception Details:
  Location:
    WeavingTest/Weaving.printWeaving()V @15: ifne
  Reason:
    Expected stackmap frame at this location.
  Bytecode:
    0x0000000: b200 422a 2ab8 0048 4cb2 0067 b600 6d9a
    0x0000010: 0025 b800 5d05 bd00 0e4d 2c03 2a53 2c04
    0x0000020: 2b53 bb00 4d59 2cb7 0050 1251 b600 57b6
    0x0000030: 0061 57b1 2a2b b800 63b1       
        at Main.main(Main.java:13)

With «-noverify» things are running fine but I am curious if it’s a known issue?

Именно это и планируется.

Вот с этого и надо начинать

То бишь, как мне запустить тесты на Амазоне

через вышеозначенную связку

Нет, не так.
Тесты на амазоне запускаются. Как запустить я знаю

Другое дело, что не подхватываются стэпы, хотя отчет генерируется, скрины и видео прикладываются

Помнится обсуджали тут эту проблему

@Miroshinsv можно использовать aspectj compiler, тогда все ок будет

@Miroshinsv Вот видишь, уже и помощь подошла :)

либо надо будет добавлять javaagent при запуске, т.е. java -jar -javaagent:aspectjweaver.jar testjar.jar

Добрый день. Testng тесты не запускаются, если включаю allure плагин в gradle. В плагине прописано
allure {
version = '2.10.0'
autoconfigure = true
aspectjweaver = true
}

Java — 11
Падает с ошибкой
`AspectJ Internal Error: unable to add stackmap attributes. null

Expecting a stackmap frame at branch target 27
Exception Details:
Location:
TestStep.step()V @9: invokestatic
Reason:
Expected stackmap frame at this location.
Bytecode:
0000000: b200 272a 2ab8 002d 4cb8 0033 2bb6 0037
0000010: b200 0212 03b6 0004 a700 0d4d b800 332c
0000020: b600 3b2c bfb8 0033 b600 3eb1
Exception Handler Table:
bci [9, 27] => handler: 27

java.lang.VerifyError: Expecting a stackmap frame at branch target 27
Exception Details:
Location:
TestStep.step()V @9: invokestatic
Reason:
Expected stackmap frame at this location.
Bytecode:
0000000: b200 272a 2ab8 002d 4cb8 0033 2bb6 0037
0000010: b200 0212 03b6 0004 a700 0d4d b800 332c
0000020: b600 3b2c bfb8 0033 b600 3eb1
Exception Handler Table:
bci [9, 27] => handler: 27`
после отключения плагина, все работает. Поскажите, пожалуйста, в чем может быть проблема/куда копать?

привет, java какой версии

добавь aspectjVersion = 1.9.4 еще

ребятушки, писала, но не получила ответа. может все же кто-то сможет подсказать?
использую allure-pytest. у меня в тестах используется настройка логгера для записи в нужном мне формате. но при этом, аллюр обрабатывает вызовы лога по-своему, в другом формате. это можно настроить как-то?
например, у меня для записи в файл:
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
в файловом логе это выглядит как 2019-06-09 11:13:08,335 - run_tests - INFO - start of smth
в репорте (и в аттачментах) выглядит как INFO run_tests:test_filename.py:21 start_of_smth
очень не хочется костылять с прикреплением лога к каждому тесту, раз аллюр умничка и сам умеет(

а еще подскажите, пожалуйста, что в итоге сейчас с установкой на линухи? ppa-шка из доки ёк?

всем привет. правильно ли я помню, что был адаптер для Shell? или я что-то путаю? )

Всем доброго дня.
Никто не подскажет, почему к аллюру не аттачатся тесты с successPercentage ?

Если запилить плагин для геренации по шаблону freemarker, то где должен находиться шаблон?
configuration.requireContext(FreemarkerContext.class).getValue().getTemplate(«abc.ftl»);

в джарке, в lib?

freemarker.template.TemplateNotFoundException: Template not found for name «abc.ftl».
The name was interpreted by this TemplateLoader: ClassTemplateLoader(classLoader=»sun.misc.Launcher$AppClassLoader@4e25154f», basePackagePath=»tpl/»).

Всем привет! Подскажите пожалуйста, у меня тесты на TestNG с spring-test, пытаюсь в @BeforeMethod через AllureLifecycle добавить link, но упорно ругается на ERROR io.qameta.allure.AllureLifecycle — Could not update test case: test case with uuid not found. Возможно кто-то подскажет красивое решение этой проблемы?

Всем привет! Может кто подскажет, как можно прикрутить allure, если тесты написаны на котлине с использованием какао? сборщик gradle

@dr29bart tpl/abc.ftl в класспасе

Всем привет. При прохождении одного и того же теста с набором данных в дата провайдере в отчете отображается только один пройденный тест. TestNG показывает, что пройдены 2 теста. Встречал кто-то такое? TestNG 6.8, Allure 2.9.0

Посмотри, нет ли второго теста в Retries

если попадаю в retries, то проблема с сигнатурами отдельных кейсов

если сигнатуры будут уникальными, то allure их разложит, как и полагается, на отдельные тесты

Что вы понимаете под сигнатурами?

Сигнатура метода — это имя метода плюс параметры (причем порядок параметров имеет значение). В сигнатуру метода не входит возвращаемое значение, а также бросаемые им исключения.

так определяется сигнатура java-метода

Allure — это делает чуть по-другому

вот только я уже не помню как :)

Там есть новая аннотация, которая может помочь

Если через конструктор параметризация — надо добавить аннотацию TestInstanceParameter на поля класса, которые параметры

Через метод возвращаются данные провайдера. Не через конструктор

Всем привет! В процессе внедрения Allure столкнулись с проблемой: иногда в каком-либо из тестов отображаются степы из других тестов, тех, что были запущены параллельно (параллельно запускаем классы, внутри классов тесты идут последовательно).

Anton Aftakhov

@simple-elf

@AnikRush явно дело в паблик переменных, например драйвера и тд. Параллелите через surefire или средствами testng?

Каким образом буде лучше передать параметр в алюр плагин?

AlexP

@AlexanderPoleschuk

лучше всего почтой России передавать… а если серьезно — нужно больше конкретики

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <testSourceDirectory>${basedir}/src/main/java</testSourceDirectory>
                    <testClassesDirectory>${project.build.directory}/classes</testClassesDirectory>
                    <testFailureIgnore>true</testFailureIgnore>
                    <systemPropertyVariables>
                        <propertyName>baseURL</propertyName>
                        <propertyName>browser</propertyName>
                        </systemPropertyVariables>
                    <suiteXmlFiles>
                        <file>${suiteXML}</file>
                    </suiteXmlFiles>
                    <argLine>
                        -javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
                    </argLine>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>2.10.0</version>
                <configuration>
                    <reportVersion>${allure-testng.version}</reportVersion>
                </configuration>
            </plugin>
        </plugins>
    </build>

примерно так можно заюзать

<propertyName>baseURL</propertyName>
<propertyName>browser</propertyName>
и тогда можно при вызове передавать -Dbrowser и -DbaseUrl

Anton Aftakhov

@simple-elf

аллюр плагин — плагином называется ТОЛЬКО jenkins и teamcity

Ты показываешь для адаптеров

AlexP

@AlexanderPoleschuk

потому и говорю, нужно больше инфы :)

Ashish-Pandey-Imprivata

AspectJ Internal Error: unable to add stackmap attributes. Unsupported class file major version 61

When trying to use AspectJ version 1.9.9 (or 1.9.9.1) with JDK 17, I am getting below error:

AspectJ Internal Error: unable to add stackmap attributes. Unsupported class file major version 61

I have seen related errors that report issue with «version 58» or «version 60» etc e.g. https://bytemeta.vip/repo/allure-framework/allure2/issues/1378, but haven’t found how to resolve this JDK17 specific issue.

kriegaex

Please add a link to a project reproducing the problem. Thank you. I cannot debug prose without code. My preliminary working hypothesis is that somehow am older AspectJ compiler version has crept into your build.

kriegaex

@Ashish-Pandey-Imprivata, because you did not respond within 11 days after I responded the very same day you created the issue, I am closing this issue as invalid. I will consider reopening it, if you provide the MCVE I requested.

Недавно обновил большой проект с Java 11 до 13. Я использую AspectJ для ведения журнала и теперь получаю эту ошибку при запуске:

AspectJ Internal Error: unable to add stackmap attributes. Unsupported class file major version 57

Похоже, что Java 13 не поддерживается, и, глядя на сайт AspectJ, они упоминают поддержку Java 12, добавленную в версии 1.9.3, но в последней версии 1.9.4 о поддержке Java 13 по-прежнему не упоминается.

Есть идеи, есть ли способ обойти это или скоро ли проект будет обновлен снова? Последний релиз был в мае …

ОБНОВИТЬ

По запросу, вот мои объявления зависимостей:

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
    </dependency>

А вот и мои объявления Java Agent:

-javaagent:lib/aspectjweaver-1.9.4.jar -javaagent:lib/spring-instrument-5.2.0.RELEASE.jar

Благодарность

1 ответ

Лучший ответ

AspectJ 1.9.5 только что упал с официальной поддержкой Java 13. Spring Boot 2.2.1 по-прежнему имеет зависимость 1.9.4 (вероятно, будет обновлена ​​в 2.2.2), поэтому сейчас вам нужно указать версию переопределения в файле POM.xml:

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version><!--$NO-MVN-MAN-VER$-->
</dependency>


1

Martin
5 Дек 2019 в 06:04

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Asp net error 500 internal server error
  • Asp net err ssl protocol error
  • Asp net custom error page
  • Asp net core return internal server error
  • Asp net core cors error