I am trying to use the JCA and CICSECI functionality to connect to IBM Mainframe via the CICS Transaction Gateway.
My Servlet code is:
package com.ebs.jca.web;
import java.io.IOException;
import javax.annotation.Resource;
import javax.resource.ResourceException;
import javax.resource.cci.Connection;
import javax.resource.cci.ConnectionFactory;
import javax.resource.cci.Interaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ebs.cics.copybook.T060.T060REQUEST;
import com.ebs.cics.copybook.T060.T060RESPONSE;
import com.ibm.connector2.cics.ECIInteractionSpec;
/**
* Servlet implementation class CICSServlet1
*/
#WebServlet("/CICSServlet1")
public class CICSServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(lookup="eis/cicsECI_CF")
private ConnectionFactory cf = null;
/**
* #see HttpServlet#HttpServlet()
*/
public CICSServlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
T060REQUEST t060Req = new T060REQUEST();
t060Req.setAccountNumber("10917683");
t060Req.setApplication("ST");
t060Req.setTransactionId("T060");
T060RESPONSE t060Resp = new T060RESPONSE();
try {
Connection eciConn = cf.getConnection();
Interaction eciInt = eciConn.createInteraction();
// Setup the interactionSpec.
ECIInteractionSpec eSpec = new ECIInteractionSpec();
eSpec.setCommareaLength(8000);
//eSpec.setReplyLength(20);
eSpec.setFunctionName("EBOT060");
eSpec.setInteractionVerb(ECIInteractionSpec.SYNC_SEND_RECEIVE);
eciInt.execute(eSpec, t060Req, t060Resp);
//eciInt.execute(eSpec, t060Req, t060Resp);
/*System.out.println("return code is:");
System.out.println(t060Resp.getReturnCode());
icbResp.setResp__code(Short.toString(t060Resp.getReturnCode()));
icbResp.setResp__text(t060Resp.getReturnText());*/
} catch (ResourceException e) {
e.printStackTrace();
//throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
response.getWriter().append("Resp: ").append(Short.toString(t060Resp.getReturnCode())).append(", text: ").append(t060Resp.getReturnText());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The exeption that I am getting is:
[err] com.ibm.connector2.cics.CICSUserInputException: CTG9628E InteractionSpec passed to execute() not of type ECIInteractionSpec
[err] at com.ibm.connector2.cics.ECIInteraction.execute(Unknown Source)
[err] at com.ebs.jca.web.CICSServlet1.doGet(CICSServlet1.java:62)
[err] at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
[err] at [internal classes]
[err] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[err] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[err] at java.lang.Thread.run(Thread.java:748)
My server.xml is as follows:
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>localConnector-1.0</feature>
<feature>javaee-7.0</feature>
<feature>jca-1.7</feature>
</featureManager>
<keyStore id="defaultKeyStore" password="{xor}NDomDCswLToPKDs="/>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>
<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>
<library id="ebsPropertiesFiles">
<folder dir="C:\ICBFiles\Properties\EBS\"/>
</library>
<!--The location of the cicseci.rar needs to be updated to the full path-->
<resourceAdapter autoStart="true" id="eciResourceAdapter" location="C:\ICBFiles\SharedLibs\cicseci9002.rar"/>
<connectionFactory id="cicsECI_CF" jndiName="eis/cicsECI_CF">
<!--The properties need to be updated to the location of the CICS Transaction Gateway-->
<properties.eciResourceAdapter ServerName="CICSQ2V5" connectionUrl="tcp://EBS-WSDEV2-2012.ad.xxx.pri" portNumber="2006"/>
</connectionFactory>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="jca-web" location="jca-web.war" name="jca-web"/>
</server>
And my POM is:
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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">
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>https://raw.github.com/WASdev/ci.maven.tools/master/LICENSE</url>
<distribution>repo</distribution>
</license>
</licenses>
<modelVersion>4.0.0</modelVersion>
<groupId>com.ebs.jca</groupId>
<artifactId>jca-web</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>jca-web</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>net.wasdev.maven.tools.targets</groupId>
<artifactId>liberty-target</artifactId>
<version>RELEASE</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.ibm.websphere.ws</groupId>
<artifactId>wsadie.marshall</artifactId>
<version>1.0.0</version>
<type>jar</type>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>com.ebs.cics.copybooks</groupId>
<artifactId>T060</artifactId>
<version>1.2.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.resource</groupId>
<artifactId>javax.resource-api</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.ibm.cicseci</groupId>
<artifactId>cicseci</artifactId>
<version>9.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.ibm.cicseci</groupId>
<artifactId>cicsframe</artifactId>
<version>9.0.0</version>
<type>jar</type>
</dependency>
</dependencies>
<build>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I google the error code. The IBM docs state:
https://www.ibm.com/support/knowledgecenter/en/SSZHFX_9.2.0/CTG9628E.html
"Review your Java client application. Refer to the product documentation for further details."
I have reviewed the following tutorials but they do not show a complete build environment.
https://developer.ibm.com/cics/2014/05/06/using-jca-with-the-cics-tg-in-websphere-liberty-profile/
https://github.com/cicsdev/cicstg-jca-liberty-sample
And I get the same error when using the sample code.
I have also tried to setting up a connectionFactory as described in this link:
https://www.ibm.com/support/knowledgecenter/SSGMCP_5.3.0/com.ibm.cics.ts.java.doc/topics/dfhpj2_jca_remote_eci_devconfig.html
When I set up a connectionFactory as shown:
<connectionFactory id="com.ibm.cics.wlp.jca.local.eci" jndiName="eis/ECI">
<properties.com.ibm.cics.wlp.jca.remote.eci serverName="CICSQ2V5" connectionUrl="tcp://EBS-WSDEV2-2012.ad.xxxx.pri" portNumber="2006"/>
</connectionFactory>
the dependency injection breaks.
CWNEN0030E: The server was unable to obtain an object instance for the java:comp/env/com.ibm.ctg.samples.liberty.JCAServlet/cf reference. The exception message was: CWNEN1003E: The server was unable to find the eis/ECI binding with the javax.resource.cci.ConnectionFactory type for the java:comp/env/com.ibm.ctg.samples.liberty.JCAServlet/cf reference.
Many Thanks
Looking at your server.xml configuration, the web application doesn't have the classloader definition required to load the InteractionSpec class from the resource adapters.
So it should be specified as
<webApplication id="jca-web" location="jca-web.war" name="jca-web">
<classloader classProviderRef="eciResourceAdapter" />
</webApplication>
Posting the process that I have followed to solve the issue.
There was obviously a class version conflict as stated by Trilarion and crshnburn.
Thanks for the help.
1 Install new Liberty profile.
2 Extract the cics.jar from the RAR archive for compile purposes.
3 Do not include the jcaRemoteEci-1.0 feature in the server.xml.
4 Use the following server.xml:
<?xml version="1.0" encoding="UTF-8"?>
<server description="ejb server">
<!-- Enable features -->
<featureManager>
<feature>javaee-7.0</feature>
<feature>localConnector-1.0</feature>
</featureManager>
<!-- Encoded password can be generated using bin/securityUtility -->
<keyStore password="change1me"/>
<basicRegistry id="basic" realm="BasicRealm">
<user name="user1" password="change1me"/>
</basicRegistry>
<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>
<library id="ebsPropertiesFiles">
<folder dir="C:\\ICBFiles\\Properties\\EBS" />
</library>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint id="defaultHttpEndpoint"
httpPort="9080"
httpsPort="9443" />
<!--The location of the cicseci.rar needs to be updated to the full path-->
<resourceAdapter autoStart="true" id="eciResourceAdapter" location="C:\ICBFiles\SharedLibs\cicseci9200.rar"/>
<connectionFactory id="cicsECI_CF" jndiName="eis/cicsECI_CF">
<!--The properties need to be updated to the location of the CICS Transaction Gateway-->
<properties.eciResourceAdapter connectionUrl="tcp://EBS-WSDEV2-2012.ad.aib.pri" portNumber="2006" ServerName="CICSUWV5"/>
</connectionFactory>
<enterpriseApplication id="icb-liberty-ear" location="icb-liberty-ear.ear" name="icb-liberty-ear">
<classloader commonLibraryRef="ebsPropertiesFiles" classProviderRef="eciResourceAdapter"/>
</enterpriseApplication>
</server>
4 Use the following pom.xml. Note that cicseci is defined with the 'provided' scope allow compiler dependency but to avoid packaging into the war archive.
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.icb</groupId>
<artifactId>icb-liberty</artifactId>
<version>1.0</version>
</parent>
<artifactId>icb-liberty-war</artifactId>
<packaging>war</packaging>
<name>ICB WAR Module</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<log4j.version>2.8.2</log4j.version>
<apache.commons.version>3.5</apache.commons.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ibm.cicseci</groupId>
<artifactId>cicseci</artifactId>
<version>9.0.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.ibm.websphere.ws</groupId>
<artifactId>wsadie.marshall</artifactId>
<version>1.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.ebs.cics.copybooks</groupId>
<artifactId>LAICBRES</artifactId>
<version>1.0.0</version>
<type>jar</type>
</dependency>
</dependencies>
<build>
<finalName>icb-liberty-war</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<packagingExcludes>pom.xml</packagingExcludes>
<warName>icb-liberty-war</warName>
<fileNameMapping>no-version</fileNameMapping>
</configuration>
</plugin>
</plugins>
</build>
</project>
Related
I am new to the Gherkin / cucumber BDD. I have been trying to create a framework using Maven, TestNG and Cucumber. I created feature file, StepDefinitiions and TestRunner. When I run feature file my scenarios are executed successfully. However, when I try to run using 'TestRunner' I am getting InitialisationError I believe I have added all required dependencies in Maven-POM.xml
I am attaching screenshot of error:
TestRunnerInitialisationError
I am attaching additional information
Project Sttructure
Project Structure
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>auto</groupId>
<artifactId>AAFramework</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>AAFramework</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<resources>
<resource>
<directory>src/main/java/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/gherkin -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>gherkin</artifactId>
<version>15.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>
<!-- Log4j dependencies: https://logging.apache.org/log4j/2.x/maven-artifacts.html#Using_Log4j_in_your_Apache_Maven_build -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
<!-- For Screenshots: https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>6.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>6.6.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>6.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
Testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel = "tests">
<listeners>
<listener class-name="aaframework.Listeners"/>
</listeners>
<test name="AmazonHomeLins">
<classes>
<class name="cucumberOptions.TestRunner"/>
</classes>
</test>
</suite> <!-- Suite -->
Feature File
Feature: Verify Amazon India homne page header links are working and redirected to respective pages
Scenario: Mobile link is working on Amazon home page
Given I am on Amazon India home page
When I click on Mobiles link
Then I am redirected to Mobiles web page
Scenario: Best Sellers link is working on Amazon home page
Given I am on Amazon India home page
When I click on 'BestSellers' link
Then I am redirected to Best Sellers web page
Step Definitions
package stepDefs;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObject.HomePagePF;
import resources.Base;
public class AmazonHome extends Base{
public WebDriver driver;
HomePagePF hp;
#Given("I am on Amazon India home page")
public void i_am_on_amazon_india_home_page() throws IOException {
// Write code here that turns the phrase above into concrete actions
driver = initialiseBrowser();
driver.get(prop.getProperty("url"));
}
#When("I click on Mobiles link")
public void i_click_on_mobiles_link() {
// Write code here that turns the phrase above into concrete actions
hp = new HomePagePF(driver);
hp.getMobiles().click();
}
#Then("I am redirected to Mobiles web page")
public void i_am_redirected_to_mobiles_web_page() throws InterruptedException {
// Write code here that turns the phrase above into concrete actions
Thread.sleep(2000);
String actualMobile = driver.getTitle();
// System.out.println(actualMobile);
String expectedMobile = "Mobile Phones: Buy New Mobiles Online at Best Prices in India | Buy Cell Phones Online - Amazon.in";
Assert.assertEquals(actualMobile, expectedMobile);
driver.close();
}
#When("^I click on 'BestSellers' link$")
public void i_click_on_bestsellers_link() throws Throwable {
hp = new HomePagePF(driver);
hp.getBestSellersLink().click();
}
#Then("^I am redirected to Best Sellers web page$")
public void i_am_redirected_to_best_sellers_web_page() throws Throwable {
Thread.sleep(2000);
String actualTitle = driver.getTitle();
// System.out.println(actualTitle);
String expectedTitle = "Amazon.in Bestsellers: The most popular items on Amazon";
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
}
TestRunner
package cucumberOptions;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(features = "/src/test/java/features",
glue= {"src/test/java/stepDefs"})
public class TestRunner {
}
There are the following lines in the example of Spring-ws spring guide
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
I get the following error
The constructor ServletRegistrationBean(MessageDispatcherServlet, String) is undefined
How can I fix this error?. What version of Spring boot I have to use?
****EDITED
This is the pom.xml. I think it's the same than the guide. I work with Eclipse.
<?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>org.springframework</groupId>
<artifactId>gs-producing-web-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- tag::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<!-- end::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::xsd[] -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- end::xsd[] -->
</plugins>
</build>
</project>
Java class
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter{
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
}
Do I have to add dependencies to the pom.xml. What is the dependency wher is ServletRegistrationBean(servlet, "/ws/*");
The MetricsServlet needs to implement javax.servlet.Servlet dependency. You need to have this class in your project/classpath. To do this, declare this maven dependency:
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
Im trying to build an application based on wicket, Spring jpa repositories, and Mysql.
The problem is, my Service classes just don't want to autowire. I got a nullpointer exception if i want to use my autowired class.
In fact, i got double nullpointer: My BaseServiceConfig.java doesnt autowire the implementation, and the autowired repository in the itnerface is also null. So, the question is why.
public final class ArmyBuilderPanel extends Panel {
#Autowired
DiskService diskService; //--> frist null, before setting it.
public ArmyBuilderPanel(String id) {
super(id);
add(new Label("armyPanel", "Content placeholder: Army builder panel"));
diskService = new DiskServiceImpl();
diskService.save(new Disk()); //--> second nullpointer
} }
Im trying to do this with minimal to no xml, all the coniguration was done in java classes. Let me show you the code:
Repository interface:
#Transactional
public interface DiskRepository extends JpaRepository<Disk, Long> {
}
Service itnerface:
public interface DiskService {
public Disk save(Disk entity);
}
Service impementation:
#Service
public class DiskServiceImpl implements DiskService {
#Autowired
DiskRepository diskRepo;
#Override
public Disk save(Disk entity) {
return diskRepo.save(entity);
}
}
BaseServiceConfig.java
#Configuration
#EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {
#Bean
DiskService diskService() {
return new DiskServiceImpl();
}
}
PersistenceJPAConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"hu.diskwars"}) public class
PersistenceJPAConfig implements DisposableBean {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"hu.diskwars"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/whdiskwars_db");
dataSource.setUsername("Westy");
dataSource.setPassword("pass");
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
return new Properties() {
{ // Hibernate Specific:
setProperty("hibernate.hbm2ddl.auto", "create-drop");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
}
};
}
#Override
public void destroy() throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} }
BaseServiceConfig.java (autowiring the implementation)
#Configuration #EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {
#Bean
DiskService diskService() {
return new DiskServiceImpl();
}
}
web.xml
> <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"
> xmlns="http://java.sun.com/xml/ns/javaee"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
>
> <display-name>diskwars</display-name>
> <context-param>
> <param-name>contextClass</param-name>
> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
> </context-param>
>
> <context-param>
> <param-name>contextConfigLocation</param-name>
> <param-value>hu.diskwars.config</param-value> </context-param>
>
> <listener>
> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
> </listener>
> <filter> <filter-name>wicket.diskwars</filter-name> <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
> <init-param> <param-name>applicationClassName</param-name>
> <param-value>hu.diskwars.view.application.WicketApplication</param-value>
> </init-param> </filter>
>
> <filter-mapping> <filter-name>wicket.diskwars</filter-name>
> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
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>hu.dwdb</groupId>
<artifactId>diskwars</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>diskwars</name>
<description></description>
<properties>
<wicket.version>6.13.0</wicket.version>
<jetty.version>7.6.13.v20130916</jetty.version>
<wtp.version>none</wtp.version>
<slf4j.version>1.6.1</slf4j.version>
<spring.version>3.2.2.RELEASE</spring.version>
<jpa.version>1.2.0.RELEASE</jpa.version>
<hibernate.version>4.2.0.Final</hibernate.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${jpa.version}</version>
<type>jar</type>
</dependency>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- LOGGING DEPENDENCIES - LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- JUNIT DEPENDENCY FOR TESTING -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- JETTY DEPENDENCIES FOR TESTING -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<!-- HIBERNATE DEPENDENCIES -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MYSQL DRIVER -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<filtering>false</filtering>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>3600000</maxIdleTime>
</connector>
<connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
<port>8443</port>
<maxIdleTime>3600000</maxIdleTime>
<keystore>${project.build.directory}/test-classes/keystore</keystore>
<password>wicket</password>
<keyPassword>wicket</keyPassword>
</connector>
</connectors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<wtpversion>${wtp.version}</wtpversion>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>Apache Nexus</id>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
Here is a picture of my workspace:
Thanks for the help!
http://i.stack.imgur.com/P32oV.png
EDIT:
Added SpringInjector to my base wicket application
#Override
public void init() {
super.getComponentInstantiationListeners().add(new SpringComponentInjector(this));
}
And suddenly a completly new, error pops out, in conncetion with my persistance unit.
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined in class
path resource [hu/diskwars/config/PersistenceJPAConfig.class]:
Invocation of init method failed; nested exception is
java.lang.IllegalStateException: Conflicting persistence unit
definitions for name 'diskwarsPU':
file:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/,
file:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/
The main problem is, i dont even have a persistance.xml file. I used to (with the same exact name 'diskwarsPU', but i throw it out, when i got to know, that i can do all the configurations without it.
I cleaned, builded the project again, even deleted the target folder, no use.
Wicket know really nothing about Spring #Autowired annotation. Use Wicket #SpringBean annotation and SringComponentInjector to inject a Sring bean into Wicket components.
The full example how to use #SpringBean annotation is in question How can I get a Spring bean injected in my custom Wicket model class?
I added an aspect to a working Spring+Wicket application to log thrown exceptions, and now I get the following error whenever I load the Report page:
ERROR | 2013-12-09 08:42:06,149 | qtp1559334851-16 | DefaultExceptionMapper:123 - Unexpected error occurred
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public org.jonblack.ReportPage() throws java.lang.Exception'. An exception has been thrown during construction!
at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:194)
at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:67)
...
Caused by: java.lang.IllegalStateException: bean of type [org.jonblack.ReportController] not found
at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.getBeanNameOfClass(AnnotProxyFieldValueFactory.java:236)
at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.getBeanName(AnnotProxyFieldValueFactory.java:179)
...
I'm using java configuration for the project, so there is no applicationContext.xml. All configuration is done via annotations, the bulk of which are in AppConfig.java.
All the code for my application is shown below. I've left out the HTML templates and HomePage as they aren't integral to the problem.
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.jonblack</groupId>
<artifactId>sw-p2</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<!-- TODO project name -->
<name>sw-p2</name>
<description></description>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<aspectj.version>1.7.4</aspectj.version>
<spring.version>3.2.4.RELEASE</spring.version>
<wicket.version>6.11.0</wicket.version>
<jetty.version>7.6.3.v20120416</jetty.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.wicketstuff</groupId>
<artifactId>wicketstuff-annotation</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- LOGGING DEPENDENCIES - LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- JUNIT DEPENDENCY FOR TESTING -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- JETTY DEPENDENCIES FOR TESTING -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<filtering>false</filtering>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>3600000</maxIdleTime>
</connector>
<connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
<port>8443</port>
<maxIdleTime>3600000</maxIdleTime>
<keystore>${project.build.directory}/test-classes/keystore</keystore>
<password>wicket</password>
<keyPassword>wicket</keyPassword>
</connector>
</connectors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
</configuration>
</plugin>
</plugins>
</build>
</project>
AppConfig.java
package org.jonblack;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
//import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
#Configuration
#ComponentScan("org.jonblack")
#EnableAsync
#EnableAspectJAutoProxy()
public class AppConfig {
private static final Logger log = LoggerFactory.getLogger(AppConfig.class);
#Bean
public ReportController reportController() {
log.info("Getting ReportController");
return new ReportController();
}
#Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(5);
pool.setMaxPoolSize(10);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
#Bean
public ExceptionLoggingAspect exceptionLoggingAspect() {
return new ExceptionLoggingAspect();
}
#Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
AnnotationAwareAspectJAutoProxyCreator aop = new AnnotationAwareAspectJAutoProxyCreator();
return aop;
}
}
ExceptionLoggingAspect.java
package org.jonblack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class ExceptionLoggingAspect {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionLoggingAspect.class);
#AfterThrowing(pointcut="execution(* org.jonblack.ReportController.getReportData(..))", throwing="ex")
public void afterThrowing(Throwable ex) {
LOG.error(ex.getMessage());
}
}
ReportController.java
package org.jonblack;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
#Controller
public class ReportController {
private static final Logger log = LoggerFactory.getLogger(ReportController.class);
#Autowired
private ThreadPoolTaskExecutor taskExecutor;
#Async
public Future<String> getReportData() throws Exception {
log.info("Entered into getReportData()");
try {
log.info("Throwing an exception");
throw new Exception("Something went wrong");
} catch(Exception ex) {
log.error("In catch block: {}", ex.getMessage());
}
final Future<String> result = taskExecutor.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "not a fancy result";
}
});
log.info("Returning from getReportData()");
return result;
}
}
ReportPage.java
package org.jonblack;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;
#MountPath("report")
public class ReportPage extends WebPage {
private static final Logger log = LoggerFactory.getLogger(ReportPage.class);
#SpringBean
ReportController reportController;
public ReportPage() throws Exception {
log.info("Starting ReportPage");
reportController.getReportData();
}
}
WicketApplication.java
package org.jonblack;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.wicketstuff.annotation.scan.AnnotatedMountScanner;
public class WicketApplication extends WebApplication
{
#Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
#Override
public void init()
{
super.init();
// Spring
getComponentInstantiationListeners().add(
new SpringComponentInjector(this));
// Annotation-driven page mounting
new AnnotatedMountScanner().scanPackage("org.jonblack").mount(this);
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>sw-p2</display-name>
<!-- Configuration loading -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.jonblack.AppConfig</param-value>
</context-param>
<!-- Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Wicket -->
<filter>
<filter-name>wicket.sw-p2</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>org.jonblack.WicketApplication</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>wicket.sw-p2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I've followed the Spring reference for Aspects but it's very thin on the ground when it comes to java configurations (and I do find the reference to be quite hard to follow).
I've also done the obligatory DuckDuckGo search and found only references to XML configurations.
On stackoverflow itself I have found this post which explains the same problem, but the cause in that instance was an incorrect annotation and incorrectly named applicationContext.xml file: neither of these helped resolve my situation. I tried using #Autowired instead of #SpringBean, and got the same NullPointerException. Given that the linked post resolved it without this change, I assume this isn't the right path to take.
The problem lies in your configuration.
#Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
AnnotationAwareAspectJAutoProxyCreator aop = new AnnotationAwareAspectJAutoProxyCreator();
return aop;
}
This bean leads to creation of a proxy of a proxy. The #EnableAspectJAutoProxy annotation already registers an AutoProxyCreator and due to the existence of multiple, different instances, this will lead to proxy duplication.
Next to that the additional declaration of your aspect might lead to 2 aspects being instantiated.
#Bean
public ExceptionLoggingAspect exceptionLoggingAspect() {
return new ExceptionLoggingAspect();
}
Your #Aspect is also an #Component and as such will be detected by the #ComponentScan functionality.
Basically removing both beans should fix your problem.
public Future<String> getReportData() throws Exception {
log.info("Entered into getReportData()");
try {
log.info("Throwing an exception");
throw new Exception("Something went wrong");
} catch(Exception ex) { // This catch blocks swallows the exception
log.error("In catch block: {}", ex.getMessage());
}
}
Next to your configuration problems, you also have a problem with your code. Basically your aspect is useless. You have a try/catch block in your code which swallows the Exception. This swallowing leads to a situation where your aspect never sees the exception and will never trigger. From your aspects point of view the exception never happened.
Either don't catch and simply let the Exception bubble up the stack or rethrow the Exception.
Before talking about the issue, I want to explain something first.
I have a basic project with 4 files:
The project contains:
1.testbase01.java: contains information to preparing for initial parameter of testing like: get driver before testing...
2.test01.java: contains some tests and this class extends from testbase01.java
3.test01.xml: contains parameter for test file test01.java
4.pom.xml: contains where to store test report, which xml suite is called for testing, which listener is using...
The flow is:
I use 'mvn test' to run project
Test is run but the report is failed.
It cannot generate report to specified folder as I configured in pom.xml (timestamp).
I found that if I change the report folder to a fixed name (my report for example), it works.
Can you help me to fix this issue?
I dont know where to fix it.
Thank you
The issue is:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
...
... TestNG 6.8.2beta_20130330_0839 by Cédric Beust (cedric#beust.com)
...
LOCAL URL IS http://192.168.10.26:8000/enigma/candidate/index#candidates
NAME= Hoang
[TestNG] Reporter org.uncommons.reportng.JUnitXMLReporter#584534b2 failed
org.uncommons.reportng.ReportNGException: Failed generating JUnit XML report.
at org.uncommons.reportng.JUnitXMLReporter.generateReport(JUnitXMLReporter.java:83)
at org.testng.TestNG.generateReports(TestNG.java:1115)
at org.testng.TestNG.run(TestNG.java:1074)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:217)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:92)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
**Caused by: java.io.FileNotFoundException: D:\WORK\Workspace\bmp\test.reports\20131003-1346\xml\testsample.test01_results.xml (The system cannot find the path specified)**
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileWriter.<init>(FileWriter.java:90)
at org.uncommons.reportng.AbstractReporter.generateFile(AbstractReporter.java:99)
at org.uncommons.reportng.JUnitXMLReporter.generateReport(JUnitXMLReporter.java:77)
... 8 more
[TestNG] Reporter org.uncommons.reportng.HTMLReporter#41ce5a9 failed
org.uncommons.reportng.ReportNGException: Failed generating HTML report.
This is my first test
This is my second test
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 20.441 sec - in TestSuite
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:117)
at org.testng.TestNG.generateReports(TestNG.java:1115)
at org.testng.TestNG.run(TestNG.java:1074)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:217)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:92)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: java.io.FileNotFoundException: D:\WORK\Workspace\bmp\test.reports\20131003-1346\html\index.html (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileWriter.<init>(FileWriter.java:90)
at org.uncommons.reportng.AbstractReporter.generateFile(AbstractReporter.java:99)
at org.uncommons.reportng.HTMLReporter.createFrameset(HTMLReporter.java:129)
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:104)
... 8 more
1.testbase01.java:
package common;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
public class testbase01{
#Parameters({"localurl"})
#BeforeSuite(alwaysRun = true)
public void beforeSuite(ITestContext context, String localurl){
// get all UI controls
System.out.println("LOCAL URL IS "+localurl);
try
{
//init web driver
WebDriver driver = new FirefoxDriver();
driver.get(localurl);
// add driver into context. This is used for ScreenshotHTMLReporter
context.setAttribute("driver", driver);
}
catch (Exception ex)
{
Assert.assertTrue(false,ex.getMessage());
}
}
}
2.test01.java:
package testsample;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import common.TestBase;
import common.testbase01;
public class test01 extends testbase01 {
#Parameters({"user"})
#Test
public void getUser(String user)
{
System.out.println("NAME= " + user);
}
#Test
public void test01_no01()
{
System.out.println("This is my first test");
}
#Test
public void test01_no02()
{
System.out.println("This is my second test");
}
}
3.test01.xml:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="test01" verbose="3" parallel="false">
<parameter name="localurl" value="http://192.168.10.26:8000/enigma/candidate/index#candidates"/>
<test name="test01">
<parameter name="user" value="Hoang"/>
<classes>
<class name="testsample.test01"/>
</classes>
</test>
</suite>
4.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>BasicMavenProj</groupId>
<artifactId>bmp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyyMMdd-HHmm</maven.build.timestamp.format>
<test.suite.dir>test.suites</test.suite.dir>
<test.report.dir>test.reports</test.report.dir>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.uncommons</groupId>
<artifactId>reportng</artifactId>
<version>1.1.2</version>
<exclusions>
<exclusion>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${test.suite.dir}/test01.xml</suiteXmlFile>
</suiteXmlFiles>
<reportsDirectory>${test.report.dir}/${timestamp}</reportsDirectory>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
<property>
<name>listener</name>
<value>org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>
<!-- <value>com.validant.enigma3.reports.ScreenshotHTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>-->
</property>
</properties>
<systemPropertyVariables>
<test.screenshot.dir>${test.report.dir}/${timestamp}</test.screenshot.dir>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
Did you try using ReportNG with default settings like described in this tutorial?I see some differences in your settings, so make that work for default settings and then you add your own configuration so you will what exactly caused your error.
One note - convention for naming Java classes is Camel Case with first letter in capital.