Sometimes it is necessary to make the test of web-service client and service.
If you have an Apache CXF service and client then you can try to use local transport for your test.
So, here is an example.
The client you define like this:
<jaxws:client id="client" serviceClass="IIdentificationService" address="local://test"/>.
And here is how you test the integration:
IIdentificationServiceImpl impl = new IIdentificationServiceImpl();
Endpoint ep = Endpoint.publish("local://test", impl);
IIdentificationService client = (IIdentificationService) context.getBean("client");
Result res = client.call("123");
ep.stop();
What is important here is the address of endpoint and client. Both uses the prefix "local". This means that messages will transport inside the JVM.
For reference see http://cxf.apache.org/docs/local-transport.html.
This blog is a collection of minds around linux, java, javascript, etc. Looking for great opportunities.
Показаны сообщения с ярлыком Apache CXF. Показать все сообщения
Показаны сообщения с ярлыком Apache CXF. Показать все сообщения
вторник, 19 февраля 2013 г.
четверг, 27 декабря 2012 г.
Make friends: Apache CXF client + WSS4J + CryptoPro
Many of you who worked with government webservices know that the information passed to the service should be signed with GOST algorithm. This leads to the use of CryptoPro library. So here is the interesting part. What I have:
Then, configure the crypto.properties file for wss4j: org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.type=HDImageStore
org.apache.ws.security.crypto.merlin.keystore.password=1234567890
org.apache.ws.security.crypto.merlin.keystore.alias=tester
org.apache.ws.security.crypto.merlin.keystore.file=c:/cert.store
Then, configure your client:
Here is the example of client:
For this to work I had to patch WSS4j. Download the sources for WSS4j 1.6.6 and edit the file org.apache.ws.security.message.WSSecSignature.java. Find the init method and replace it with this code:
Compile the file and add the compiled class to the wss4j jar.
After this, I could successfully run the client.
- jdk 1.6.0.38 + JCP CryptoPro
- ready to use keystore
- wss4j 1.6.6
- apache cxf 2.6.1
- XMLDSigRI.jar
Then, configure the crypto.properties file for wss4j: org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.type=HDImageStore
org.apache.ws.security.crypto.merlin.keystore.password=1234567890
org.apache.ws.security.crypto.merlin.keystore.alias=tester
org.apache.ws.security.crypto.merlin.keystore.file=c:/cert.store
Then, configure your client:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <!-- The SOAP client bean --> <jaxws:client id="client" serviceClass="ru.my.IService" address="http://test/IService/IdentificationService.svc"> <jaxws:inInterceptors> <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/> </jaxws:inInterceptors> <jaxws:outInterceptors> <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/> <ref bean="wss4jOutConfiguration" /> </jaxws:outInterceptors> </jaxws:client> <bean id="wss4jOutConfiguration" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor"> <property name="properties"> <map> <entry key="action" value="Signature"/> <entry key="signaturePropFile" value="crypto.properties"/> <entry key="signatureKeyIdentifier" value="DirectReference"/> <entry key="user" value="tester"/> <entry key="signatureUser" value="tester"/> <entry key="passwordCallbackClass" value="ru.client.KeystorePasswordCallback"></entry> <entry key="signatureDigestAlgorithm" value="http://www.w3.org/2001/04/xmldsig-more#gostr3411"/> <entry key="signatureAlgorithm" value="http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"/> </map> </property> </bean> </beans>Everything seems good, but your client won't work.
Here is the example of client:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
ru.IService client = (ru.IService) context.getBean("client");
ru.CryptoPro.JCPxml.XmlInit.init();
if(!JCPXMLDSigInit.isInitialized()){
JCPXMLDSigInit.init();
}
Result res = client.callMethod(123);
For this to work I had to patch WSS4j. Download the sources for WSS4j 1.6.6 and edit the file org.apache.ws.security.message.WSSecSignature.java. Find the init method and replace it with this code:
private void init() {
Provider xmlDSigProvider = new ru.CryptoPro.JCPxml.dsig.internal.dom.XMLDSigRI();
signatureFactory = XMLSignatureFactory.getInstance("DOM", xmlDSigProvider);//XMLSignatureFactory.getInstance("DOM");
keyInfoFactory = KeyInfoFactory.getInstance("DOM", xmlDSigProvider);
}
Compile the file and add the compiled class to the wss4j jar.
After this, I could successfully run the client.
воскресенье, 2 сентября 2012 г.
Сравнение Apache CXF и Spring WS
-->
Попробуем сравнить 2
известных фреймворка для написания
веб-сервисов и клиентов к ним.
К этим фреймворкам
относятся: Spring Web Services, Apache CXF.
Проект Apache CXF активно
развивается, в то время как Spring WS
представляет собой законченное решение.
Архитектура Spring WS довольно простая, что
при желании позволит разобраться в её
исходном коде и поправить замеченные
ошибки.
Я знаком с обоими
фреймворками, но испробовал не все их
возможности. Сравнение представлено в
таблице ниже и представляет собой
попытку свести информацию в табличный
вид.
По итогам сравнения
можно сказать следующее:
- Apache CXF обладает большим количеством возможностей по сравнению с Spring WS.
- В проекте, когда интерфейс WSDL довольно часто меняется, то проще использовать Spring WS.
- Обе библиотеки довольно просты в освоении, однако с CXF много времени можно потратить на настройке.
- Следует отметить, что с обоими библиотеками поставляется набор примеров.
- Выбор в пользу той или иной библиотеки необходимо делать исходя из требований к проекту, а также исходя из приверженности работы по стандарту JAX-WS.
Spring
WS
|
Apache
CXF
|
|
|---|---|---|
Поддержка
разработки типов сервисов
|
сверху-вниз
|
сверху-вниз,
снизу-вверх.
|
Обработка
входящих сообщений
|
DOM,
SAX, StAX, JDOMs, dom4j, XOM, JAXB, Castor, Apache XMLBeans,
XStream. Определение обработчика входящего
XML запроса на основе запроса, заголовка
SOAP Action или Xpath выражения.
|
DOM,
SAX, StAX, InputStream, JAXB 2.x, Aegis, Apache XMLBeans, Service
Data Objects (SDO), JiBX.
|
Поддержка
спецификаций
|
WS-Security,
WS-Addressing.
Интеграция
с Acegi Security.
|
JAX-WS,
JAX-RS, WS-Basic Profile, WS-Addressing, WS-Policy, WS-Reliable
Messaging, WS-Security, WS-SecurityPolicy, WS-SecureConversation,
WS-Trust (partial support).
|
Поддержка
транспорта
|
JMS,
Email, XMPP, HTTP, Embedded HTTP.
|
HTTP,
Servlet, JMS, In-VM and many others via the Camel
transport for CXF such as SMTP/POP3, TCP and Jabber.
|
Документация
|
Неплохая,
есть tutorial.
Простота
в использовании.
|
Крайне
разрозненная. Трудно понять с чего стоит начинать, и где найти нужную информацию.
|
Наличие
инструментов
|
Отсутствует.
|
|
Версионность
сервисов
|
Через
XSLT преобразование запроса. Возможность
быстрого внесения изменений в интерфейс
сервиса, что полезно при изменяющемся
контракте.
|
Написание
собственного перехватчика
(http://cxf.apache.org/docs/service-routing.html).
|
Клиенты
|
Простой
синхронный клиент, интеграция с http
client.
|
Возможность
создания клиента на javascript, асинхронного
клиента.
|
Отказоустойчивость
|
Необходимо
придумывать самому.
|
Возможность
создания клиентов, использующих
возможность работы с другим сервисом
в случае отказа сервера.
|
Управление
|
Отсутствует
|
Поддержка
JMX.
|
Тестирование
сервисов
|
Поддержка
для тестирования клиентов и сервисов.
|
Необходимо
писать самому. Можно использовать локальный или in-VM транспорт.
|
Интеграция
с IDE
|
Отсутствует.
|
Интеграция
с Eclipse.
|
вторник, 21 августа 2012 г.
Apache cxf 2.6.1 и Eclipse (part 2)
В этой части я решил избавиться от зависимости в виде Eclipse и научиться генерировать веб-сервис с помощью CXF.
суббота, 18 августа 2012 г.
Apache cxf 2.6.1 и Eclipse
В этой заметке мы опишем, как можно с помощью ant в Eclipse создавать веб сервис apache cxf.
среда, 27 июня 2012 г.
Apache CXF. Ошибка Property is already defined. Use to resolve this conflict.
При попытке сгенерировать java клиента с помошью WSDL2JAVA Apache CXF выдал ошибку Property is already defined. Use <jaxb:property> to resolve this conflict.
Проблема оказалась в том, что атрибут и элемент имеют одинаковые имена. Вот такой бред выдаёт JAXB. Что с этим делать? Нужно создать файлик xml, в котором необходимо определить, что дубликат имени будет отображаться на другое имя. Например, так:
Проблема оказалась в том, что атрибут и элемент имеют одинаковые имена. Вот такой бред выдаёт JAXB. Что с этим делать? Нужно создать файлик xml, в котором необходимо определить, что дубликат имени будет отображаться на другое имя. Например, так:
<jxb:bindings version="2.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="Dummy.xml" node="/xsd:schema">
<jxb:bindings node="//xsd:complexType[@name='complexTypeOne']">
<jxb:bindings node=".//xsd:attribute[@name='value']">
<jxb:property name="ValueToFixError1"/>
</jxb:bindings>
</jxb:bindings></jxb:bindings></jxb:bindings> После этого необходимо WSDL2JAVA с помощью ключа -b указать созданный файлик.
Подписаться на:
Сообщения (Atom)