How to intercept or aop javax.sql.Datasource.getConnection() using spring aop - spring-aop

I am trying to aspect the javax.sql.Datasource.getConnection() so that I can set clientInfo properties before the connection is used.
I tried spring ConnectionInterceptor with COnnectionPreparer but it did not work.
I tried pointcut with javax.sql.datasource.getConnection() but not working.
now , am trying pointcut with the below but my advise is not executed rather the call just passes through.
pom.xml has
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
main class
#SpringBootApplication
#Configuration
#EnableAutoConfiguration
#ComponentScan({ "com.xyz" })
#EnableAspectJAutoProxy
public class MainApplication extends SpringBootServletInitializer {
// spring configuration here
// cxf end point configuration
}
aspect class
#Component
#Aspect
public class ClientIdentifierConnectionPreparer {
#AfterReturning(pointcut="execution(java.sql.Connection org.springframework.jdbc.datasource.ConnectionHandle.getConnection())", returning="conn")
public void prepare(Connection conn) {
System.out.println("prepare connection aspect 1");
}
#Before("execution(java.sql.Connection org.springframework.jdbc.datasource.ConnectionHandle.getConnection())")
public void prepareBefore() {
System.out.println("prepare connection aspect 2");
}
}
can you pls help

Related

Working with apache camel Bean in Quarkus framework

I am trying to use apache camel with Quarkus. Previously I was using the spring-boot framework to develop camel integration. So there are lots of questions that I am still trying to figure out w.r.t. Quarkus framework.
Regarding: Bean
In spring-boot I could do something like this
#Configuration
public class JABXContextConfig {
#Bean
Unmarshaller jaxbUnmarshaller() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(MyPOJO.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return jaxbUnmarshaller;
}
}
and then I could inject it into the class using DI
#Component
public class MyRestServiceRoute extends RouteBuilder {
private final JaxbDataFormat jaxb;
#Autowired
public MyRestServiceRoute(JaxbDataFormat jaxb) throws Exception{
this.jaxb = jaxb;
}
....
}
QUESTION:
How can I do the same in the Quarkus framework?
P.S> I tried replacing #Configuration with #ApplicationScoped and #Bean with #Dependent but it's not working.
Thanks,
I recommend taking a read through the Quarkus CDI documentation:
https://quarkus.io/guides/cdi
https://quarkus.io/guides/cdi-reference
There's also a basic overview of using CDI to configure Camel:
https://camel.apache.org/camel-quarkus/latest/user-guide/bootstrap.html#_cdi
https://camel.apache.org/camel-quarkus/latest/user-guide/cdi.html
In your examples, #Bean could be replaced by a producer method like:
public class JaxbDataFormatProducer {
#ApplicationScoped
JaxbDataFormat jaxbDataFormat() {
return new JaxbDataFormat();
}
}
And the #Autowired constructor argument might look like this (If there’s only one constructor then there's actually no need for #Inject):
#ApplicationScoped
public class MyRestServiceRoute extends BaseRouteBuilder {
private final JaxbDataFormat jaxb;
#Inject
public MyRestServiceRoute(JaxbDataFormat jaxb) throws Exception{
super(properties);
this.jaxb = jaxb;
}
}

Spring Boot GUI Testing Selenium WebDriver

I developped a Spring Boot / Angular JS app. Now I'm trying to implement some GUI interface tests.
I tryed to use the Selenium ChromeDriver, so I added the Selenium dependency :
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
And I created my first test :
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MyMainClass.class)
public class SeleniumTest {
private WebDriver driver;
#Before
public void setup() {
System.setProperty("webdriver.chrome.driver", "my/path/to/chomedriver");
driver = new ChromeDriver();
}
#Test
public void testTest() throws Exception {
driver.get("https://www.google.com/");
}
}
This works fine. But now I want to get my app pages with :
driver.get("http://localhost:8080/");
But I get an "ERR_CONNECTION_REFUSED" in the chrome browser.
I think it's because I need to set up my test to run my web app before to run the test but I don't find how to achieve this ?
In your case service is not started. Try something like this this.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SeleniumTest {
#LocalServerPort
private int port;
private WebDriver driver;
#Value("${server.contextPath}")
private String contextPath;
private String base;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "my/path/to/chromedriver");
driver = new ChromeDriver();
this.base = "http://localhost:" + port;
}
#Test
public void testTest() throws Exception {
driver.get(base + contextPath);
}
}
UPDATE:
Add the dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Change EndPoint details in CXF ServiceInfo

The environment CXF2.2.6 and Spring 2.5. On Startup JBOSS I need to read CXF properties and change End point details. From basic reading it gives me the idea that CXF Service Info class (org.apache.cxf.service.model.ServiceInfo) handle bindings,endpoints,messages,schemas and so on.
I can Extend CXFServlet and create my own custom servlet. Please advise me the way I can give my own details to Endpoint in startup and override what is given in Spring.xml
The below Spring bean should do what you wanted. Why do you want to override ServiceInfo class ? Any particular reason ?
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
public class CXFConfig implements InitializingBean{
#Autowired
Bus cxfBus;
#Override
public void afterPropertiesSet() throws Exception {
EndpointImpl endpoint = new EndpointImpl(cxfBus, new GdsAutomationServiceProviderImpl());
endpoint.setAddress("/public/api/service/v1");//WSDL URL
endpoint.setPublishedEndpointUrl(getEndPointAddress());
endpoint.publish();
}
public Bus getCxfBus() {
return cxfBus;
}
public void setCxfBus(Bus cxfBus) {
this.cxfBus = cxfBus;
}
public String getEndPointAddress() {
// Soap address location you need to define here
return "address"
}
#Override
public void setServletContext(ServletContext context) {
context.getServerInfo();
}
}

Invoking JAX-WS Web service from Camel

I need to invoke a JAX-WS Web service available on WildFly 8. I've started with a simple example to get started. Here is my Web service:
import javax.jws.WebService;
#WebService
public class HelloWorld implements Hello{
#Override
public String greet(String s) {
return "Hello "+s;
}
}
The WSDL is available at: http://localhost:8080/DemoWS/HelloWorld?wsdl
Taking a look at the Tomcat-CXF example, I have coded the following route:
public class CamelRoute extends RouteBuilder {
private String uri = "cxf:http://localhost:8080/helloWorld?serviceClass=com.sample.HelloWorld";
#Override
public void configure() throws Exception {
from(uri)
.to("log:input")
.recipientList(simple("direct:${header.operationName}"));
from("direct:greet")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
String id = exchange.getIn().getBody(String.class);
exchange.getOut().setBody(id);
}
})
.to("log:output");
}
}
By running the above code in a Camel Context, the following error is returned:
Exception in thread "main" org.apache.camel.FailedToCreateRouteException: Failed to create route route1: Route[[From[cxf:http://localhost:8080/helloWorld?serviceClas... because of Failed to resolve endpoint: cxf://http://localhost:8080/helloWorld?serviceClass=com.sample.HelloWorld due to: No component found with scheme: cxf
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:177)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:731)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1803)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1589)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1453)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:60)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1421)
at com.sample.Main.main(Main.java:15)
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: cxf://http://localhost:8080/helloWorld?
serviceClass=com.sample.HelloWorld due to: No component found with scheme: cxf
It seems I'm not even able to invoke it. Any help ?
Thannks
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
</dependency>

Migrating from CamelTestSupport to AbstractCamelTestNGSpringContextTests

I've been using Apache Camel since 3-4 months on Spring 4.0.7.RELEASE
I have several Camel 2.14.0 TestNG tests based on extending CamelTestSupport, in which I use some MockEndpoints.
I configured my routes by overriding the createRouteBuilder() method.
Now I would need also to inject some Spring beans in one of them, by #Autowired annotation.
By reading what is said at http://camel.apache.org/spring-testing.html, I understood that I've to extend AbstractCamelTestNGSpringContextTests now, which supports #Autowired, #DirtiesContext, and #ContextConfiguration.
While I understood that all MockEndpoints are no more accessible by getMockEndpoint() method, but by using #EndpointInject annotation, it is not clear to me is how I can express my routes, because createRouteBuilder() is not more available.
I saw that is possible to define producers and consumers by using annotations, but I cannot manage to understand how routes can be designed.
Many thanks to the community.
Alternatively to the solution given here, you may use the TestNG helper CamelSpringTestSupport in combination with AnnotationConfigApplicationContextif you want to initialize an annotated based Spring configuration context without the need of an additional XML Spring configuration file.
Camel configuration bean class using Spring annotations:
#Configuration
public class MyConfig extends SingleRouteCamelConfiguration {
#Bean
#Override
public RouteBuilder route() {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("direct:test").to("mock:direct:end");
}
};
}
}
The TestNG test class extends CamelSpringTestSupport and the Spring configuration MyConfig is initialized with AnnotationConfigApplicationContext:
public class TestNGTest extends org.apache.camel.testng.CamelSpringTestSupport {
#EndpointInject(uri = "mock:direct:end")
protected MockEndpoint errorEndpoint;
#Produce(uri = "direct:test")
protected ProducerTemplate testProducer;
#Override
protected AbstractApplicationContext createApplicationContext() {
return new AnnotationConfigApplicationContext(MyConfig.class);
}
#DirtiesContext
#Test
public void testRoute() throws InterruptedException {
// use templates and endpoints
}
}

Resources