繁体   English   中英

将CXF REST服务从XML移植到JSON响应

[英]Porting CXF REST Service from XML to JSON response

我尝试转换一个包含非常简单的REST服务(应部署到karaf中)的教程。

蓝图定义为

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.1.0"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xmlns:cxf="http://cxf.apache.org/blueprint/core"
xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0  http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://www.osgi.org/xmlns/blueprint-ext/v1.1.0 https://svn.apache.org/repos/asf/aries/tags/blueprint-0.3.1/blueprint-core/src/main/resources/org/apache/aries/blueprint/ext/blueprint-ext.xsd http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/schemas/blueprint/jaxws.xsd http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.1.0.xsd http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.1.0 http://aries.apache.org/schemas/blueprint-ext/blueprint-ext-1.1.xsd">

    <cxf:bus id="personRestBus">
    </cxf:bus>
    <bean id="personServiceImpl" class="net.lr.tutorial.karaf.cxf.personrest.impl.PersonServiceImpl"/>
    <jaxrs:server address="/person" id="personService">
        <jaxrs:serviceBeans>
            <ref component-id="personServiceImpl" />
        </jaxrs:serviceBeans>
        <jaxrs:features>
            <cxf:logging />
        </jaxrs:features>
    </jaxrs:server>
</blueprint>

PersonService接口非常简单:

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface PersonService {
    @GET
    @Path("/")
    public Person[] getAll();

    @GET
    @Path("/{id}")
    public Person getPerson(@PathParam("id") String id);

    @PUT
    @Path("/{id}")
    public void updatePerson(@PathParam("id") String id, Person person);

    @POST
    @Path("/")
    public void addPerson(Person person);
}

该模型如下所示:

package net.lr.tutorial.karaf.cxf.personrest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    String id;
    String name;
    String url;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }

}

这就是实现:package net.lr.tutorial.karaf.cxf.personrest.impl;

import java.util.HashMap;
import java.util.Map;

import net.lr.tutorial.karaf.cxf.personrest.model.Person;
import net.lr.tutorial.karaf.cxf.personrest.model.PersonService;

public class PersonServiceImpl implements PersonService {
    Map<String, Person> personMap;

    public PersonServiceImpl() {
        personMap = new HashMap<String, Person>();
        Person person = createExamplePerson();
        personMap.put("1", person);
    }

    private Person createExamplePerson() {
        Person person = new Person();
        person.setId("1");
        person.setName("Ruediger");
        return person;
    }

    public Person[] getAll() {
        return personMap.values().toArray(new Person[]{});
    }

    public Person getPerson(String id) {
        return personMap.get(id);
    }

    public void updatePerson(String id, Person person) {
        person.setId(id);
        System.out.println("Update request received for " + person.getId() + " name:" + person.getName());
        personMap.put(id, person);
    }

    public void addPerson(Person person) {
        System.out.println("Add request received for " + person.getId() + " name:" + person.getName());
        personMap.put(person.getId(), person);
    }

}

测试如下所示:package net.lr.tutorial.karaf.cxf.personservice.impl;

import java.io.InputStream;

import javax.ws.rs.core.Response;

import net.lr.tutorial.karaf.cxf.personrest.impl.PersonServiceImpl;
import net.lr.tutorial.karaf.cxf.personrest.model.Person;
import net.lr.tutorial.karaf.cxf.personrest.model.PersonService;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class PersonServiceRestTest {

    private static final String PERSONSERVICE_TESTURL = "http://localhost:8282/person";
    private static Server server;

    @BeforeClass
    public static void startServer() {
        PersonService personService = new PersonServiceImpl();;
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
        factory.setAddress(PERSONSERVICE_TESTURL);
        factory.setServiceBean(personService);
        server = factory.create();
        server.start();
    }

    @Test
    public void testInterface() {
        PersonService personService = JAXRSClientFactory.create(PERSONSERVICE_TESTURL, PersonService.class);
        Person person = new Person();
        person.setId("1002");
        person.setName("Christian Schneider");
        personService.updatePerson("1002", person);

        Person person2 = personService.getPerson("1002");
        assertCorrectPerson(person2);
    }

    @Test
    public void testWebClient() {
        WebClient client = WebClient.create(PERSONSERVICE_TESTURL + "/1001");
        putPerson(client);
        Person person = client.get(Person.class);
        assertCorrectPerson(person);
    }

    private void putPerson(WebClient client) {
        InputStream is = this.getClass().getResourceAsStream("/person1.json");
        Response resp = client.put(is);
        System.out.println(resp);
    }

    @AfterClass
    public static void stopServer() {
        server.stop();
    }


    private void assertCorrectPerson(Person person) {
        Assert.assertNotNull(person);
        Assert.assertEquals("Christian Schneider", person.getName());
    }

}

testWebClient测试产生此警告,但这意味着我没有得到结果:

2016-08-16 11:02:52,306 [tp1293680734-19] WARN WebApplicationExceptionMapper-javax.ws.rs.ClientErrorException:HTTP 415 org.apache.cxf.jaxrs.utils.SpecExceptions.toHttpException(SpecExceptions.java: 117),位于org.apache.cxf.jaxrs.utils.ExceptionUtils.toHttpException(ExceptionUtils.java:162),位于org.apache.cxf.jaxrs.utils.JAXRSUtils.findTargetMethod(JAXRSUtils.java:530),位于org.apache.cxff org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)处的.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:177),位于org.apache.cxf.phase.PhaseInterceptorChain。 .java:308),位于org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121),位于org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:253)。 org.apache.cxf.trans上的cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:234) 位于org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1129)的port.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:70)在org.eclipse.jetty.server.handler.ContextHandler.doScope( org.eclipse.jetty.server.handler.ScopedHandler.handle(ContextdHandler.java:141)位于org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215) org.eclipse.jetty.server.Server.handle(Server.java:499)上的.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)org.eclipse.jetty.server.HttpChannel.handle上的.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) (HttpChannel.java:310)在org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)在org.eclipse.jetty.io.AbstractConnection $ 2.run(AbstractConnection.java:540)在org.eclipse org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run(QueuedThreadPool.java:555)的.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)在java.lang.Thread.run(Thread。 java:745)

因此测试失败。

testInterface测试产生此错误:

2016-08-16 11:20:34,232 [main]警告PhaseInterceptorChain-{{ http://model.personrest.cxf.karaf.tutorial.lr.net/ }的拦截器} PersonService已引发异常,现已取消org.apache.cxf .interceptor.Fault:找不到类net.lr.tutorial.karaf.cxf.personrest.model.Person的消息正文编写器,ContentType:org.apache.cxf.jaxrs.client.ClientProxyImpl $ BodyWriter上的application / json。 org.apache.cxf.jaxrs.client.AbstractClient $ AbstractBodyWriter.handleMessage(AbstractClient.java:1091)的doWriteBody(ClientProxyImpl.java:882)org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)在org.apache.cxf.jaxrs.client.AbstractClient.doRunInterceptorChain(AbstractClient.java:649)在org.apache.cxf.jaxrs.client.ClientProxyClientImpl.doChainedInvocation(ClientProxyImpl.java:747)在org.apache.cxf.jaxrs net.lr.tutorial.karaf.cxf.personservice.i上com.sun.proxy。$ Proxy19.updatePerson(未知源)的.client.ClientProxyImpl.invoke(ClientProxyImpl.java:228) mpl.PersonServiceRestTest.testInterface(PersonServiceRestTest.java:47)位于sun.reflect.NativeMethodAccessorImpl.invoke0(本地方法)位于sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)位于sun.reflect.DelegatingMethodAccessorImpl.invoke在org.junit.internal.runners的org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)的java.lang.reflect.Method.invoke(Method.java:498)的java:43)。 org.junit.runners.model.FrameworkMethod.invoke上的model.ReflectiveCallable.run(ReflectiveCallable.java:12)org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java: 17)在org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java)上org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)上org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) :57)at org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290) 在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)在org.junit.runners.ParentRunner.access $ 000(ParentRunner.java) :58)在org.junit.inner.runners处$ 2.evaluate(ParentRunner.java:268)在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)在org.junit.internal.runners org.junit.runners.ParentRunner.run(ParentRunner.java:363)的.statements.RunAfters.evaluate(RunAfters.java:27)org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java :86),位于org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)上的org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) org.eclipse上的org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)上的org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)。 jdt.internal.junit.runner.RemoteTestRun ner.main(RemoteTestRunner.java:192)原因:javax.ws.rs.ProcessingException:找不到类net.lr.tutorial.karaf.cxf.personrest.model.Person的消息正文编写器,ContentType:application / json

我能够将服务部署到karaf中并进行交互。 但是测试无法解决。 如果可能,我想避免使用像jackson这样的外部框架。

谢谢!

您的服务接受任何MediaType,因为您尚未为@Consumes设置默认值(请参阅文档 )。 建议将内容类型设置为接受

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface PersonService {

您需要在客户端中设置内容类型

client.type( MediaType.APPLICATION_JSON);

我不确定,但是我认为您需要在<jax-rs_server>定义JSON提供程序

<bean id="jackson" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />

<jaxrs:server address="/person" id="personService">
    <jaxrs:serviceBeans>
        <ref component-id="personServiceImpl" />
    </jaxrs:serviceBeans>
    <jaxrs:features>
        <cxf:logging />
    </jaxrs:features>
   <jaxrs:providers>
        <ref bean="jackson" />
    </jaxrs:providers>
</jaxrs:server>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM