Arquillian and #BeforeClass, #AfterClass annotations - testing

It looks like mentioned annotations are executed inside the deployment. I need them to be run outside, let's say to start some simulator class on startup and stop it on the end. How can I do it? The simulator uses socket communication and it should not be started inside the server.
How to mix arquillian with "plain" junit(not executed in container).

You can use the arquillian #RunAsClient annotation combined with the junit #BeforeClass and #AfterClass:
#BeforeClass
#RunAsClient // runs as client
public static void shouldBeAbleToRunOnClientSideBeforeRemoteTest() throws Exception {
System.out.println("before!!");
}
#AfterClass
#RunAsClient // runs as client
public static void shouldBeAbleToRunOnClientSideAfterRemoteTest() throws Exception {
System.out.println("after!!");
}

The answer that Franck gives will certainly work, and will probably be what most users will want to use. If, however, you need to get some more detail about what's going on, or need some more control you can certainly hook into the Arquillian life cycle and register observers for all sorts of events that Arquillian emits. Unfortunately, it isn't as easy as listening to a CDI event.
You'll need to create a services entry in META-INF/services with the file name of org.jboss.arquillian.core.spi.LoadableExtension. The contents of that file will be the Fully Qualified Name (FQN) of the classes that implement the LoadableExtension interface from Arquillian. You can then in the register(ExtensionBuilder) method register any classes that will observe events. Those classes will simply need a public void methodName(#Observes EventType) method for all the events they want to listen for. The #Observes annotation is in the org.jboss.arquillian.core.api.annotation package.
You can see this in action the Arquillian Recorder Reporter extension here, here, and here. I understand this is probably more than what most people will want to do, but again, if you need the power and hooks, Arquillian should be able to give you what you need.

Related

Using Byte Buddy to expand Spring Boot's classpath

The AWS SDK can locate API call interceptors via classpath scanning (looking for software/amazon/awssdk/global/handlers/execution.interceptors and instantiating classes specified there).
I'm writing a Java Agent with the intention of causing my interceptors to be locatable by the AWS SDK.
My interceptor is bundled with the Java Agent.
My interceptor implements AWS's ExecutionInterceptor.
The AWS SDK is not bundled with my agent, because I'd like the end-user to provide their own AWS SDK version.
For regular standalone applications, this is a no-brainer, as the Java Agent is automatically added to the runtime classpath of the application. The AWS SDK finds my interceptors with no problem.
However, this approach completely breaks with Spring Boot applications where the AWS SDK is bundled as a dependency under BOOT-INF/lib. The reason boils down to Spring Boot's classloading hierarchy. My interceptor class can be found, but its loading fails due to inability to find AWS's ExecutionInterceptor, as it is loaded in a "lower" classloader in the hierarchy.
So I figured that my approach should be to somehow modify Spring Boot's classloader search. However, I'm facing these issues:
At the time of the agent being called, Spring Boot's "lower" classloader isn't created yet.
I am not entirely sure what it is that I need to instrument.
I've read of Byte Buddy being able to help in such "interesting" circumstances but haven't found a way to make this work yet. Any ideas?
(EDIT: I'm looking for a solution that doesn't require code/packaging changes, hence the Java Agent approach)
(EDIT: Things I've tried)
Following Rafael's answer: The method in the SDK that resolves all interceptors is in the class SdkDefaultClientBuilder, and is called resolveExecutionInterceptors.
The following, then, works for standalone JARs which are not SpringBoot applications:
public static void installAgent(Instrumentation inst) {
new AgentBuilder.Default()
.with(RedefinitionStrategy.DISABLED)
.type(ElementMatchers.nameEndsWith("SdkDefaultClientBuilder"))
.transform(
new Transformer() {
#Override
public Builder<?> transform(Builder<?> builder, TypeDescription typeDescription,
ClassLoader classLoader, JavaModule module) {
return builder.visit(Advice.to(MyAdvice.class).on(ElementMatchers.named("resolveExecutionInterceptors")));
}
}
).installOn(inst);
}
For SpringBoot applications, however, it looks like the advice isn't applied at all. I am guessing that this is because the SdkDefaultClientBuilder type isn't even available at the time when the agent starts. It is available during SpringBoot's runtime, in a different classloader.
Byte Buddy allows you to inject code in any method of any class, so the first and only major thing you would need to find out would be where your interceptor is instantiated. This can typically be done by setting a breakpoint in the constructor of the interceptor in the working scenario and investigating the methods in the stack. Find out where the classes are discovered, for example the method where software/amazon/awssdk/global/handlers/execution.interceptors is read.
Once you have identified this method, you would need to find a way to manually extract the interceptors defined by your agent and to manually add them. For example, if the file-extracted interceptors are added to an argument of type List<Interceptor>, you could use Byte Buddy to modify this method to also add those of your agent.
Normally, you use Byte Buddy's AgentBuilder in conjunction with Advice to do so. Advice let's you inline code into another method as for example, assuming you find a method with an argument of type List<Interceptor>:
class MyAdvice {
#Advice.OnMethodEnter
static void enter(#Advice.Argument(0) List<Interceptor> interceptors) {
interceptors.addAll(MyAgent.loadMyInterceptors());
}
}
You can now inline this code into the method in question by:
class MyAgent {
public static void premain(String arg, Instrumentation inst) {
new AgentBuilder.Default().type(...).transform((builder, ...) -> builder
.visit(Advice.to(MyAdvice.class).on(...))).install(inst);
}
}
You might need to use AgentBuilder.Transformer.ForAdvice if the classes in question are not available on the agent's class loader where Byte Buddy resolves the advice using both the target and the agent class loader.

How to define aspects and pointcuts in WildFly?

We are migrating from JBoss 5 to WildFly 8.2. Still using Spring 3.1. Suddenly none of our aspects can be found when application starts.
We might have solved (partially) the XML configuration (by placing more wildcards around), but annotation based configuration of aspects cannot be solved the same way (no wildcard possible for aspect itself since this is annotated class). Here is the Aspect class definition:
package com.mycompany.session;
#Aspect
#Component("mySessionManager")
public class SessionManager {
// intercepting any class, any method starting with com.mycompany.some
#Pointcut("execution(* com.mycompany.some.*.*(..))")
public void myPointcut() {}
#Around(value="myPointcut()")
public Object process(ProceedingJoinPoint jointPoint)
throws Throwable
{ ... the rest of code }
}
When starting this code without changes under WildFly we get this error:
java.lang.IllegalArgumentException: warning can't determine implemented interfaces of missing type com.mycompany.session.SessionManager
Anything wrong with code? Anything needs to be different in WildFly versus older jboss?
Thanks,
Nikolay

NSubstitute mocking a NLog logger fails

I have a test that looks like following:
[Test]
public void LoggerTest()
{
var log = Substitute.For<Logger>();
log.DidNotReceiveWithAnyArgs().Info("");
log.ReceivedWithAnyArgs().Info("");
}
The test succeeds, which it obviously shouldn't. To my best knowledge this is the syntax according to the NSubstitue website.
Can anybody tell me where the problem lies?
I use NSubstitue in version 1.7.2.0 from the NuGet package manager.
NLog.Logger is a concrete class with non-virtual members, so NSubstitute will not be able work with it (see the note on Creating a substitute).
If you need to test logging one option is to wrap the log functionality in your own, app-specific interface. This makes it easier to substitute in a new logger for testing purposes (can use NSubstitute or other mocking library, or hand-code your own TestLogger tailored for your test purposes).

Background thread running in a Webservice Apache CXF built

I'm new to webservices and I have some questions but I hope to get a more clear picture by asking.
I've created a simple webservice with Apache CXF and it works.
I what at startup to build some objects, like database connection or... for example a new thread.
I want the following scenario:
-all the requests should access only the published methods of the webservice.
-all the methods must access varialbes of the running background startup threads.
So the threads will run in background and the published methods will access their result stored in ...maybe a static varialbes.
At the moment I'm using TomcatServer7
The class that it's methods are published is looking like this:
public class OperatorClass {
public int add(int a, int b){
return a+b;
}
public int OneArgument(int a){
return a+45;
}
}
How is possible to implement this and where to write the startup thread clases? maybe a sample code or a link to see how it's done would be very useful.
Tks
If you are using Spring with CXF you can create a bean and implement InitializingBean interface, then in afterPropertiesSet() method you can start you threads depending on your needs. The other alternative with Spring is to use: #PostConstruct annotation on the method which you want to be called after dependency injection.
If you are not using Spring then you can set up ServletContextListener to do the job. See my answer here for more information how to set up context listener.
And now there are many ways of getting the data from the threads you've started on start up. You just need to come up with a more specific question (if you can't get it working) and we will be glad to help.

Configure WorkManager in JBoss 7

I'm pretty new with JSF (I'm a mobile developer) and I need to run a bulk of processes in a thread.
I've read I need to use WorkManager, but I can't find how is that, and how to configure it in JBoss 7.
Does anyody know an easy-to-follow tutorial about that?
Thanks a lot.
An #Aysnchronous EJB is probably the easiest solution.
Edit 1:
This will look more or less like this:
#Singleton
public BulkProcessor {
#Asynchronous
public void doWork(){
// code there
}
}
When you invoke the method it will immediately return but JBoss will then run #doWork in it's own thread. Just remember you'll have to #Inject the object and not instantiate it yourself.
Edit 2:
This is a quick and easy example
http://satishgopal.wordpress.com/2011/04/24/ejb-3-1-asynchronous-methods/