I am very new to Apache Camel an please dont mind if I am wrong at any point.
I have two questions regarding apache camel.
In apache camel examples in internet, I can only see hitting a web service and routing the same to another. How can I call a WebService, unmarshall the object and use in my application instead of routing to another.
In the examples, for calling camel context, we have to call
CamelContext context = new DefaultCamelContext();
context.start()
and
context.stop()
Is there any other way in spring to create a Singleton object in the application context and autowire the bean in my service class in the enterprise project?
Also It will be very helpful if anyone could point me any resources such as pdf or websites that can help me with this.
Just declare camel context as a normal bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<package>my.package.with.routebuilders</package>
</camelContext>
And wire it in your service class
#Autowired
private CamelContext camelContext;
to 1st:
you can create a processor to handle data from your webservice. your processor can be wired to your route builder. your routebuilder could look like the follwoing:
public class MyRouteBuilder extends SpringRouteBuilder {
#Autowired
private MyProcessor myProcessor;
#Override
public void configure() throws Exception {
from("xy")
.process(myProcessor);
}
}
your processor:
public class MyProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
//do something with your message
}
}
of course you have to create a bean of your processor. you could do it with annotating it and enable the spring component scan or define it in your spring-context.xml:
<bean class="com.package.of.your.processor.MyProcessor" />
to 2nd:
it is like #Sergey said. you can instanciate your context in your spring config.
with my example your springconfig would look like:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean class="com.package.of.your.processor.MyProcessor" />
<bean id="myRouteBuilder" class="com.package.of.your.routbuilder.MyRouteBuilder" />
<camel:camelContext id="camelContext">
<camel:routeBuilder ref="myRouteBuilder" />
</camel:camelContext>
</beans>
Related
I have the WSDL file for the SOAP webservice that i need to invoke over http. Using cxf wsdl2java plugin i have created the stub methods.
I have created the webservice client using jaxws. The webservice has basic authentication enabled. I am trying to configure http conduit
my application.properties
--------------------------
webservices.http.auth.username=username
webservices.http.auth.password=password
fold.webservices.http.auth.authtype=Basic
webservices.http.conduit.property.name=https://fixed_deposits-test.co.in/fold-webservices/services.*
fold.updateservice.soap.address=https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
----------------------------
My Spring Context...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="properties" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer">
<property name="locations">
<util:list>
<value>file:${config.dir}/application.properties</value>
</util:list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<jaxws:client id="updateServiceClient" serviceClass="com.fold.facade.v1.UpdateService" address="${fold.updateservice.soap.address}" >
<jaxws:inInterceptors>
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:outInterceptors>
</jaxws:client>
<http-conf:conduit name="***?????????***">
<http-conf:authorization>
<sec:UserName>${fold.webservices.http.auth.username}</sec:UserName>
<sec:Password>${fold.webservices.http.auth.password}</sec:Password>
<sec:AuthorizationType>${fold.webservices.http.auth.authtype}</sec:AuthorizationType>
</http-conf:authorization>
</http-conf:conduit>
I have done a lot of searching online so as to what should be the valid value for name attribute..
accouring to CXF documentation it should be...
{WSDL_endpoint_target_namespace}PortName.http-conduit
my WSDL File has..
...
targetNamespace="http://facade.fold.com/" and
...
<wsdl:port binding="tns:UpdateServiceImplServiceSoapBinding"
name="UpdateServiceImplPort">
<soap:address
location="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService" />
</wsdl:port>
so i tried with these..
<http-conf:conduit name="{http://facade.fold.com/}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="*UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com/}*.http_conduit">
But none of them work as i get 401 unauthorized exception..
org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
THERE ARE COUPLE OF WAYS I GOT IT TO WORK
a) <http-conf:conduit name="*.http_conduit">
but i really don't want to do it this way...
b) <http-conf:conduit name="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService">
this is hardcoding the SOAP service URL... which i don't want as i am looking for externalizing URL as my SOAP URL's are different for different environment..(dev /test /prod etc)
Below is my best shot at externalization, but it failed with 401 Unauthorized Exception...
properties were replaced in all other instances in my spring context, but not for http-conf:conduit name attribute :(
<http-conf:conduit name="${webservices.http.conduit.property.name}">
As a workaround i am currently using the regex approach which works..
<http-conf:conduit name="*.*/fold-webservices/services/UpdateService">
But i really want to figure out if it possible to externalize it and read from properties file. And i want to do it the Spring
configuration way. Please help me !!!
We had the same issue with JBoss Fuse 6.1 (Camel CXF 2.12.0).
You can see what the http-conf:conduit name is set to by enabling DEBUG log level and looking at your log, there should be a log line such as:
DEBUG 10:40:41,437 [Camel (cnpms-as-mnp-ctx) thread #0 - JmsConsumer[cnpms-queue]] org.apache.cxf.transport.http.HTTPConduit.setTlsClientParameters(HTTPConduit.java:901) - Conduit '{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit' has been (re)configured for plain http.
So in this case you would set the name as:
<http-conf:conduit name="{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit"
But the Web Service (WS) Interface Class is defined as:
#WebService(targetNamespace = "http://acme.com/manageporting/v1", name = "ManageportingPort")
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface ManageportingPort {
Generated from WSDL:
<wsdl:portType name="ManageportingPort">
Note that by following the CXF documentation you would expect the port name component to be "ManageportingPort" NOT "ManageportingPortPort" i.e. with "Port" appended to it.
However looking at how the portQName is resolved in org.apache.cxf.jaxws.support.JaxWsImplementorInfo.getEndpointName(), if the port name is not set in the WS Interface Class, and the name is not null or blank, it sets the port name to portName = name + "Port" otherwise it sets it to portName = implementorClass.getSimpleName() + "Port".
I had the same problem...
In my case the following 2 changes helped:
1) add "Port" postfix to the port name, despite it is not defined in the wsdl this was
e.g wsdl:
<wsdl:port name="XXXSoap">
will be "XXXSoapPort" in the conduit definition
2) remove the "\" at the end of the target namespace name
==> therefore try
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPortPort.http_conduit">
I came across the same challenge and found no existing solution. Spring doesn't seem to resolve placeholders in bean names (make lots of sense). However, this is a valid case unless cxf allows conduit matching using another attribute.
There are a few ways to solve this problem:
Define conduit beans programmatically (lose the neat of xml declaration)
Find a way to resolve the bean names which contains placeholders
I prefer option 1 and this is the implementation which I'm happy with. Please note that PropertyPlaceholderResolver is our own utility which uses the same defined resolver bean.
public class NameWithPlaceholderBeanFactoryPostProcessor implements BeanFactoryPostProcessor
{
#Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException
{
if (!(beanFactory instanceof DefaultListableBeanFactory))
return;
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory;
String[] names = bf.getBeanDefinitionNames();
for (String name : names)
{
if (name.indexOf('$') < 0)
continue;
BeanDefinition bd = bf.getBeanDefinition(name);
bf.removeBeanDefinition(name);
bf.registerBeanDefinition(PropertyPlaceholderResolver.resolvePlaceHolders(name), bd);
}
}
}
The final step is to define this as a spring bean.
I have written Webservice in java which has successfully created WSDL. I am stuck in writing a webservice client for my webservice in java. I would like to use my webservice from some jsp classes. How do i do it?
#WebService
public interface AddService {
double getMultipicationResult(double M1, double M2);
}
#WebService(endpointInterface = "com.sample.AddService")
public class AddServiceImpl implements AddService {
public AddServiceImpl() {
}
#Override
public double getMultipicationResult(double M1, double M2) {
M1 = M1*M2;
return M1;
}
}
I have written the client something like :-
public class AddServiceClient {
private AddServiceClient() {
}
public static void main(String args[]){
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"SpringClientWebServices.xml"});
AddService client = (AddService)context.getBean("client");
double response = 0.0;
response = client.getMultipicationResult(10.0, 20.5);
}
}
and SpringClientWebServices.xml is as follows :-
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="client" class="com.sample.AddService"
factory-bean="clientFactory" factory-method="create"/>
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
<property name="serviceClass" value="com.sample.AddService"/>
<property name="address" value="http://localhost:8080/sample/services/Addition"/>
</bean>
</beans>
I am getting exception as follows:-
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.cxf.jaxws.JaxWsProxyFactoryBean] for bean with name 'clientFactory' defined in class path resource [SpringClientWebServices.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.cxf.jaxws.JaxWsProxyFactoryBean
First of all you are missing the CXF jars as evident from the ClassNotFoundException. Please include the cxf jars.
Second regarding using the service in JSPs then you have to first initialize the Spring container via web.xml and not via main method. Use Spring MVC and implement controller which makes calls to webservice and provide data to the JSP.
If you want to consume a service directly from the JSP, consider a JavaScript client like mentioned: http://cxf.apache.org/docs/javascript-client-samples.html
I prefer to use a jar that contains the service interface and create a dynamic Spring client using CXF and Spring in a separate jar, then bring in both f those dependencies. This is also documented in the CXF site.
I need to configure the camel route endpoint using WSDL file.
I don't know the service classes and I don't want to put the service class files in my class path. I have only the WSDL file.
How can I solve my task ?
Define the camel cxf endpoint as follows
<cxf:cxfEndpoint id="testServiceEndpoint" address="http://localhost:9000/web-service/TestService" wsdlURL="TestService.wsdl" serviceClass="com.webservice.AllServiceService" endpointName="s:TestServiceHttpSoap11Endpoint" serviceName="s:TestPutService" xmlns:s="http://webservices/testService"/>
Route configuration
<route>
<from uri="cxf:bean:testServiceEndpoint"/>
<to uri="log:output?showAll=true" />
</route>
Note that I have mentioned a serviceClass attribute, but this class can be made generic to handle all webservices by using #WebServiceProvider annotation
#WebServiceProvider
#ServiceMode(Mode.PAYLOAD)
public class AllServiceService implements Provider<StreamSource> {
#Override
public StreamSource invoke(StreamSource request) {
}
}
I'm a java beginner. I'm in trouble to configure a persistance unit using JTA transactions.
I need to use a PostgreSQL database that is already defined, configured and populated. Using netbeans, i created the persistance.xml and glassfish-resources.xml as fallows:
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="WellWatcherPU" transaction-type="JTA">
<jta-data-source>WellWatcherDB</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.logger" value="org.eclipse.persistence.logging.DefaultSessionLog"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
and
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_geowellex_geowellexPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="5432"/>
<property name="databaseName" value="DBNAME"/>
<property name="User" value="USER"/>
<property name="Password" value="PASSWORD"/>
<property name="URL" value="jdbc:postgresql://localhost:5432/DBNAME"/>
<property name="driverClass" value="org.postgresql.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="WellWatcherDB" object-type="user" pool-name="post-gre-sql_geowellex_geowellexPool"/>
</resources>
And this is how i get the EntityManagerFactory and EntityManager (as used in the netBeans example)
public class EUserDao {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "WellWatcherPU")
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager(); <-------- NullPointerException here
}
public EUser getOne(long userId){
EntityManager em = getEntityManager();
try {
return em.find(EUser.class, userId);
} finally {
em.close();
}
}
EDIT:
And here is my glassfish deploy log:
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1901223982)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin(
platform=>DatabasePlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1462281761)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--Connected: jdbc:postgresql://localhost:5432/geowellex?loginTimeout=0&prepareThreshold=0
User: geowellex
Database: PostgreSQL Version: 9.1.3
Driver: PostgreSQL Native Driver Version: PostgreSQL 8.3 JDBC3 with SSL (build 603)
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(766700859)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin(
platform=>PostgreSQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
What's wrong?
Most likely problem is that your EUserDao is just regular class. Injection works only for container managed classes. Annotations like #PersistenceUnit and #Resource are not processed for normal classes.
Following types of classes are container managed classes (and in those #PersistenceUnit can be used):
Servlet: servlets, servlet filters, event listeners
JSP: tag handlers, tag library event listeners
JSF: scoped managed beans
JAX-WS: service endpoints, handlers
EJB: beans, interceptors
Managed Beans: managed beans
CDI: CDI-style managed beans, decorators
Java EE Platform: main class (static), login callback handler
I see that in your code declare:
private EntityManagerFactory emf = null;
but never create one... like this
emf = Persistence.createEntityManagerFactory("WellWatcherPU");
Thats why you get a Null Pointer Exception when use the object!
public EntityManager getEntityManager() {
return emf.createEntityManager(); <-------- NullPointerException here
}
I have the following class
public class HeaderClass{
#Resource
private WebServiceContext webServiceContext;
public String getUserAgent() {
MessageContext msgCtx = webServiceContext.getMessageContext();
HttpServletRequest request = (HttpServletRequest)msgCtx.get(AbstractHTTPDestination.HTTP_REQUEST);
return request.getHeader("user-agent")
}
In my service bean class I want to inject this HeaderClass, so that I can use it there as follows:
package mypack;
#Path("/MyService")
public class MyServiceClass {
//May be some annotation has to be given here which I don't know
HeaderClass header;
public void useHeader() {
//Code to use the header
System.out.println(header.getUserAgent());
}
}
I have the following inside beans.xml file
<jaxrs:server id="SampleService" address="/">
<jaxrs:features>
<cxf:logging />
</jaxrs:features>
<jaxrs:serviceBeans>
<ref bean="MyServiceClass"/>
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="MyServiceClass" class="mypack.MyServiceClass"/>
I don't know how to add the property HeaderClass in the bean "MyServiceClass"
I am using apache cxf with spring configuration file (beans.xml).
Please help.
One way to achieve this is to add those lines to your beans.xml:
<bean id="HeaderClass" class="mypack.HeaderClass"/>
<bean id="MyServiceClass" class="mypack.MyServiceClass">
<property name="header" ref="HeaderClass" />
</bean>
You may also need to add a setHeader() method to your MyServiceClass.