ContextConfiguration does not seem to load my beans for TestNg testcase - spring

I am new to TestNg. I am trying to test one sample hello world program.
Following is my project structure
Source Package
com.mycompany.mavenproject1 =>HelloWorld.java
Test Package
com.test => NewTestConfig.java & NewTestNGTest.java
Helloworld.java
package com.mycompany.mavenproject1;
public class HelloWorld {
String msg = "test";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
NewTestConfig.java
package com.test;
import com.mycompany.mavenproject1.HelloWorld;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class NewTestConfig {
#Bean
public HelloWorld helloWorldBean() {
HelloWorld hw = new HelloWorld();
return hw;
}
}
NewTestNGTest.java
package com.test;
import com.mycompany.mavenproject1.HelloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.springframework.test.context.ContextConfiguration;
#Test
#ContextConfiguration(classes={ NewTestConfig.class })
public class NewTestNGTest {
#Autowired
HelloWorld hw ;
#Test
public void exampleOfTestNgMaven() {
String s = hw.getMsg();
System.out.println("This is TestNG-Maven Example" + s);
}
#BeforeClass
public static void setUpClass() throws Exception {
}
#AfterClass
public static void tearDownClass() throws Exception {
}
#BeforeMethod
public void setUpMethod() throws Exception {
}
#AfterMethod
public void tearDownMethod() throws Exception {
}
}
My pom.xml looks like below:
<?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>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mavenproject1</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
When I try to run the test I get NullpointerException (at hw.getMsg();)
Error stack:
Test set: com.test.NewTestNGTest
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.209 sec <<< FAILURE!
exampleOfTestNgMaven(com.test.NewTestNGTest) Time elapsed: 0.003 sec <<< FAILURE!
java.lang.NullPointerException
at com.test.NewTestNGTest.exampleOfTestNgMaven(NewTestNGTest.java:25)
I tried to run test in debug mode, I always get HelloWorld bean as null. So eventually test fails due to NullPointerException. I tried many other variations such as instead of config class tried using applicationContext.xml but my bean never gets injected.
For last 2 days I am struggling to make simple test pass but unable to figure out what's going wrong. Why my context is not getting loaded for test?
Any help is greatly appreciated.
Thanks
Manisha

Related

JDK 11 JavaFX with Maven: can't add dependencies to project

I used the sample archetype of openjfx to create a simple FXML base project from here: https://openjfx.io/openjfx-docs/#maven
I want to add other functionalities (such as parsing of xml files etc.) but when i try to use the added dependency, for some reason the objects are not recognized.
pom.xml:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.msd</groupId>
<artifactId>MSDLog</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>15.0.1</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>15.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.12.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.5</version>
<configuration>
<mainClass>org.msd.App</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
App.java file:
You can see that the XmlMapper is commented out since it does not recognize it
package org.msd;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
/**
* JavaFX App
*/
public class App extends Application {
private static Scene scene;
#Override
public void start(Stage stage) throws IOException {
scene = new Scene(loadFXML("environment"), 640, 480);
stage.setScene(scene);
stage.show();
}
static void setRoot(String fxml) throws IOException {
//------- THIS FAILS -------
XmlMapper xmlMapper = new XmlMapper();
scene.setRoot(loadFXML(fxml));
}
private static Parent loadFXML(String fxml) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
return fxmlLoader.load();
}
public static void main(String[] args) {
launch();
}
}
Trying to import package:
Trying to "Add Maven dependency..." will suggest irrelevant packages
What am i missing???

maven project using rest controller and gave a basic request and gives 404. url : http://localhost:8080/Spring4MVCHelloWorldRestServiceDemo/testrest

I created a maven project using rest controller and gave a basic request but it is not hitting the method and gives 404.i am new to the rest controller. So it would be great if someone try to narrow down the issue.
the url : http://localhost:8080/Spring4MVCHelloWorldRestServiceDemo/testrest
HelloController
package com.fis.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping(value="/testrest", method = RequestMethod.GET)
public String welcome() {//Welcome page, non-rest
System.out.println("Test++++++++++++++");
return "Welcome to RestTemplate Example.";
}
/* #RequestMapping("/hello/{player}")
public Message message(#PathVariable String player) {//REST Endpoint.
Message msg = new Message(player, "Hello " + player);
return msg;
}*/
}
HelloInitialization
package com.fis.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class HelloInitialization extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
HelloConfiguration
package com.fis.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.fis.controller"})
public class HelloConfiguration {
}
http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.websystique.springmvc</groupId>
<artifactId>Spring4MVCHelloWorldRestServiceDemo</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>Spring4MVCHelloWorldRestServiceDemo Maven Webapp</name>
<properties>
<springframework.version>4.3.0.RELEASE</springframework.version>
<jackson.library>2.7.5</jackson.library>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring4MVCHelloWorldRestServiceDemo</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>Spring4MVCHelloWorldRestServiceDemo</finalName>
</build>

Issue with building pom

I have tried to run example of the project but unsuccessfully (problem with compilation project). Here is the link to this project https://github.com/serenity-bdd/serenity-demos/tree/master/jbehave-webtests
Now I'm trying to make an easy project to learn how to use Serenity with Jbehave but I have problem to create pom.xml. My pom is according to this project https://github.com/serenity-bdd/serenity-demos/tree/master/junit-webtests (I know it is not the best solution). I'm not pretty good in Maven. Here is my pom.xml:
<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>
<groupId>serenity-maven-jbehave</groupId>
<artifactId>imdb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<serenity.version>1.1.25-rc.3</serenity.version>
<serenity.maven.version>1.1.25-rc.3</serenity.maven.version>
<serenity.jbehave.version>1.8.0</serenity.jbehave.version>
<webdriver.driver>firefox</webdriver.driver>
</properties>
<!-- Define the Bintray repos for convenience -->
<repositories>
<repository>
<id>serenity</id>
<name>bintray</name>
<url>http://dl.bintray.com/serenity/maven</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>serenity</id>
<name>bintray-plugins</name>
<url>http://dl.bintray.com/serenity/maven</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
<version>${serenity.version}</version>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-junit</artifactId>
<version>${serenity.version}</version>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-rest-assured</artifactId>
<version>${serenity.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.lambdaj</groupId>
<artifactId>lambdaj</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>core</artifactId>
<version>1.0.47</version>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jbehave</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<parallel>classes</parallel>
<threadCount>5</threadCount>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.18</version>
<configuration>
<includes>
<include>src/main/java/*.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.maven.version}</version>
<dependencies>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
<version>1.1.25-rc.3</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Here is HomePage.
package pages;
import org.openqa.selenium.WebElement;
import net.serenitybdd.core.annotations.findby.By;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.PageObject;
import net.thucydides.core.annotations.DefaultUrl;
#DefaultUrl("https://www.imdb.com")
public class HomePage extends PageObject {
#FindBy(xpath="#navUserMenu.css_nav_menu.js_nav_item")
WebElement downArrowButton;
#FindBy(css="#first_name.reg_thick")
WebElement firstNameInput;
#FindBy(css="#last_name.reg_thick")
WebElement lastNameInput;
#FindBy(css="#year.reg_thick")
WebElement yearOfBirthInput;
#FindBy(css="#gender_m.reg_radio")
WebElement genderMaleRadioButton;
#FindBy(css="#postal.reg_thick")
WebElement zipPostalCodeInput;
#FindBy(css="#email.reg_thick")
WebElement emailInput;
#FindBy(css="#password1.reg_thick")
WebElement passwordInput;
#FindBy(css="#password2.reg_thick")
WebElement passwordConfirmInput;
#FindBy(css="div.reg_right input.btn2.large.primary")
WebElement RegisterButton;
public static String userName;
public void showMoreOptions(){
WebElement downArrow = getDriver().findElement(By.cssSelector("div[id='nb_personal'] span[class='downArrow']"));
downArrow.click();
}
public void clickRegisterButton() {
WebElement register = getDriver().findElement(By.linkText("Register"));
register.click();
}
public void fillRequiredFields(String firstName, String lastName, String email, String password) throws InterruptedException {
firstNameInput.sendKeys(firstName);
lastNameInput.sendKeys(lastName);
String yearOfBirth= String.valueOf(randomWithRange(1950, 1999));
yearOfBirthInput.sendKeys(yearOfBirth);
genderMaleRadioButton.click();
String zipPostalCode = String.valueOf(randomWithRange(10000, 99999));
zipPostalCodeInput.sendKeys(zipPostalCode);
userName= "usermail" + System.currentTimeMillis();
email = userName + "#mailinator.com";
emailInput.sendKeys(email);
passwordInput.sendKeys(password);
passwordConfirmInput.sendKeys(password);
RegisterButton.click();
Thread.sleep(5000);
}
public int randomWithRange(int min, int max) {
int range= (max-min) +1;
return (int) ((Math.random() * range) + min);
}
}
Here is ImdbSteps
package steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.steps.ScenarioSteps;
import pages.HomePage;
public class ImdbSteps extends ScenarioSteps {
private static final long serialVersionUID = 1L;
#Steps
HomePage homePage;
#Given("I am on the imdb site")
public void userWantsVisitSite() {
homePage.open();
}
#When ("I am cliking on register button")
public void userIsClickingRegisterButton() {
homePage.showMoreOptions();
homePage.clickRegisterButton();
}
#Then ("I am filling required fields")
public void userIsFillingRequiredFields(String firstName, String lastName, String email, String password) throws InterruptedException {
homePage.fillRequiredFields(firstName, lastName, email, password);
}
}
Edit:
How should I build pom.xml base on code above? I tried to build this pom.xml with the instruction in link belove
http ://thucydides.info/docs/serenity-staging/#introduction
but I haven't succeed.
Could someone give me a link to the workable project which uses Serenity, Jbehave and Maven? Or any clue how to solve this problem.Thank to in advance.

Using AspectJ to recognize method calls

I like to use AspectJ to recognize when a certain method is called within another OSGi bundle I don't have the source code for. Therefore, I build an aspect-bundle. For learning puposes the other bundle is implemented by a sample bundle which simply implements a "sayHello" method. The aspect-bundle is now supposed to recognize whenever this method is called.
Here is what I have so far:
normal bundle
HelloWorld.java
package com.mango.sample.helloworld;
public class HelloWorld {
public void sayHello() {
System.out.println("Hello world");
}
}
Activator.java
package com.mango.sample.helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
HelloWorld test = new HelloWorld();
test.sayHello();
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
pom.xml
<?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>
<groupId>com.mango.sample</groupId>
<artifactId>helloworld</artifactId>
<version>0.1</version>
<packaging>bundle</packaging>
<name>helloworld</name>
<prerequisites>
<maven>3.0.4</maven>
</prerequisites>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Import-Package>*</Import-Package>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.name}</Bundle-Name>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Activator>com.mango.sample.helloworld.Activator</Bundle-Activator>
</instructions>
<manifestLocation>${project.basedir}/META-INF</manifestLocation>
</configuration>
</plugin>
</plugins>
</build>
</project>
aspect-bundle
Activator.java
package com.mango.sample.helloworldj;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
AspectJTest.aj
package com.mango.sample.helloworldj;
public aspect AspectJTest {
before() : execution(* *.sayHello()) {
System.out.println("Before execution sum");
}
}
pom.xml
<?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>
<groupId>com.mango.sample</groupId>
<artifactId>helloworldj</artifactId>
<version>0.1</version>
<packaging>bundle</packaging>
<name>helloworldj</name>
<prerequisites>
<maven>3.0.4</maven>
</prerequisites>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Import-Package>*</Import-Package>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.name}</Bundle-Name>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Activator>com.mango.sample.helloworldj.Activator</Bundle-Activator>
<Export-Package>com.mango.sample.helloworldj;aspects=AspectJTest</Export-Package>
</instructions>
<manifestLocation>${project.basedir}/META-INF</manifestLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.3</version>
<configuration>
<complianceLevel>1.5</complianceLevel>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
After compiling, I start equinox (separately from eclipse)
configuration/config.ini
osgi.framework.extensions=org.eclipse.equinox.weaving.hook_1.0.200.I20130319-1000.jar
osgi.bundles=\
reference\:file\:../lib/org.apache.felix.fileinstall-3.1.6.jar#1:start,\
reference\:file\:../lib/org.eclipse.osgi.services-3.3.100.v20120522-1822#2:start,\
reference\:file\:../lib/org.eclipse.equinox.console-1.0.0.v20120522-1841.jar#start,\
reference\:file\:../lib/slf4j-api-1.7.2.jar#1:start,\
reference\:file\:../lib/logback-classic-1.0.9.jar#1:start,\
reference\:file\:../lib/logback-core-1.0.9.jar#1:start,\
reference\:file\:../lib/org.aspectj.runtime_1.7.3.20130613144500-a.jar#2:start
and the options:
-Daj.weaving.verbose=true
-Dorg.aspectj.weaver.showWeaveInfo=true
-Dorg.aspectj.osgi.verbose=true
Then, I install and start the aspect bundle and the other bundle afterwards. After starting the HelloWorld bundle, I expected something like this
Before execution
Hello world
But I got only Hello world. I guess there is going something wrong with weaving the aspects into the helloworld bundle. Is there something missing in the pom.xml files?
How can I solve it?

Mock aspect in junit failed to apply

I'm building up a simple project to learn aspectj.
It's from aspect in action 2nd and the idea is very simple ---- the MessageCommunicator will be responsible for delivering the message and it's the main business logic. Meanwhile, Authenticator will be responsible for authentication and will be weaved as declared SecurityAspect.
Though it's very straightforward to see in the log that the aspect is working. Still I want to ensure it works in junit case.
In my project, I'm using maven 3.0.4 with aspectj 1.7.3 and aspect-maven-plugin 1.5.
Now the problem is below warning is there when compile the test case. As the consequence, the aspects in test package doesn't work. However, if you write a Main class in source package and run, the aspect in source package will work.
The warning message while build:
[INFO] --- aspectj-maven-plugin:1.5:test-compile (test-compile_with_aspectj) # aspectj ---
[WARNING] advice defined in org.javen.study.aspectj.c02.aspects.MockAuthenticationAspect has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in org.javen.study.aspectj.c02.aspects.SecurityAspect has not been applied [Xlint:adviceDidNotMatch]
[WARNING] advice defined in org.javen.study.aspectj.c02.aspects.TrackingAspect has not been applied [Xlint:adviceDidNotMatch]
I will also attach all the related source code below:
MessageCommunicator who is responsible for the main business:
package org.javen.study.aspectj.c02;
public class MessageCommunicator {
public void deliver(String message) {
System.out.println(message);
}
public void deliver(String person, String message) {
System.out.println(person + ", " + message);
}
}
Simple version of authenticator which will do the authentication:
public class Authenticator {
public void authenticate() {
System.out.println("authenticated");
}
}
SecurityAspect which will advice on MessageCommunicator:
package org.javen.study.aspectj.c02.aspects;
import org.javen.study.aspectj.c02.Authenticator;
public aspect SecurityAspect {
private Authenticator authenticator = new Authenticator();
declare warning
: call(void Authenticator.authenticate())
&& !within(SecurityAspect)
: "Authentication should be performed only by SecurityAspect";
pointcut secureAccess() : execution(* org.javen.study.aspectj.c02.MessageCommunicator.deliver(..));
before() : secureAccess() {
System.out.println("Checking and authenticating user");
authenticator.authenticate();
}
}
MockAuthenticationAspect in test package to advice the authenticator to inject some verification logic(no need to look into advice detail, the advice implementation is problematic):
package org.javen.study.aspectj.c02.aspects;
import org.javen.study.aspectj.c02.Authenticator;
public aspect MockAuthenticationAspect {
declare parents: Authenticator implements Callable;
private boolean Callable.isCalled;
public void Callable.call() {
isCalled = true;
}
public boolean Callable.isCalled() {
return isCalled;
}
Object around(Callable accessTracked) : execution(* Authenticator.authenticate(..))
&& !execution(* Callable.*(..))
&& this(accessTracked) {
accessTracked.call();
return null;
}
private static interface Callable {
}
}
The pom of whole project:
<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>
<groupId>org.javen.study</groupId>
<artifactId>aspectj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<aspectj.version>1.7.3</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<complianceLevel>1.6</complianceLevel>
<includes>
<include>**/*.java</include>
<include>**/*.aj</include>
</includes>
</configuration>
<executions>
<execution>
<id>compile_with_aspectj</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile_with_aspectj</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
When build with command "mvn clean install", the warning texts will be printed and the test package advice will not work. However, if check with AJDT in eclipse, all the pointcut and advice is working.
Could someone help me? Thanks a lot.
The problem is solved by added below configuration in test-compile execution.
<execution>
<id>test-compile_with_aspectj</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<weaveDirectories>
<weaveDirectory>target/classes</weaveDirectory>
</weaveDirectories>
</configuration>
</execution>
Don't know it's a good pratice or not, but at least now it works.

Resources