标签: jax-rs

继泽西岛教程之后

我正在尝试使用Grizzly作为Web容器来遵循泽西教程的第一部分.我只是在"你好世界!" 部分并尝试运行我的代码.这是我尝试部署的Web服务的主要部分.

    public class Main {

    public static void main(String [] args) throws IOException {
        final String baseUri = "http://localhost:9998";
        final Map<String, String > initParams = new HashMap<String, String>();


        initParams.put("com.sun.jersey.config.property.packages", "com.sun.ws.rest.samples.helloworld.resources");

        System.out.println("Starting grizzly");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri,initParams);

        System.out.println(String.format("Jersey app started with WADL available at %sapplication.wadl Try out %shelloworld. Hit enter to stop it...", baseUri, baseUri));

        System.in.read();
        threadSelector.stopEndpoint();
        System.exit(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我跑这个,我总是得到

Exception in thread "main" java.lang.IllegalArgumentException: The URI path, of the URI http://localhost:9998, must be present
at com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory.create(GrizzlyWebContainerFactory.java:236)
at …
Run Code Online (Sandbox Code Playgroud)

java jax-rs jersey grizzly

3
推荐指数
1
解决办法
2264
查看次数

REST如何在URI中传递空路径参数?

我正在开发一个安静的webapp.在这里,我采用的参数是userid和orderid.

useridnull.
URI是@Path("api/user/userid/order/orderid") 我的方法是,

void add(@PathParam("userid") String userId, @PathParam("orderid") String orderId);
Run Code Online (Sandbox Code Playgroud)

我想userId在URI中传递null值.

我试过了api/user//order/1234.但在这种情况下,userid取值orderId(即1234并且orderIdnull.(这是错误的)

我也试过改变路径@Path("api/user/userid: .*/order/orderid").然而与之前的结果相同.

其他方式解决,这可能是使用@QueryParamuserid或创建的另一种方法userid null.

不过,我想知道是否有办法有userId作为PathParameter,而不是QueryParam和传递价值useridnull

java rest jax-rs

3
推荐指数
1
解决办法
5674
查看次数

Resteasy,使用RestEasy的服务器端模拟框架制作Http-Put或Http-Post

我写了一个Rest-Service,我想测试一下.我想在没有运行服务器的情况下运行JUnit测试.为此,我使用RestEasy的服务器端模拟框架.

我的问题是,如何使用这个框架在Http-Body中使用编组的Java对象来发出Http-Put或Http-Post请求?

下面的代码适用于Http-Get,但如何制作Put或Post,也许有人为此获得了一些示例代码?

@Test
public void testClient() throws Exception {

    Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();

    POJOResourceFactory noDefaults = new POJOResourceFactory(
            MyClass.class);
    dispatcher.getRegistry().addResourceFactory(noDefaults);

    {
        MockHttpRequest request = MockHttpRequest.get("/message/test/"
                + requestParam);
        MockHttpResponse response = new MockHttpResponse();

        dispatcher.invoke(request, response);
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());

    }
}
Run Code Online (Sandbox Code Playgroud)

rest unit-testing http jax-rs resteasy

3
推荐指数
1
解决办法
4207
查看次数

@GET可以为JAX-RS实现定义Consumes Content-Type吗?

我一直在JAXRS上尝试一些示例(本例中使用Jersey).以下是我的示例存根实现:

    @Path("stubservice")
public class StubImpl
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getString(@QueryParam("first")
    int first, @QueryParam("second")
    int second)
    {
        return "first: " + first + " second: " + second;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getSize(@QueryParam("size")
                              int size,
                              @Context
                              HttpHeaders headers)
    {
        Gson gson = new Gson();
        return gson.toJson("something else");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果没有在其定义中getSize具有的方法@Consumes(MediaType.APPLICATION_JSON),则该类在初始化期间具有错误.但是有了它,StubImpl类会正确初始化并根据传入的请求是否具有Content-Typeas 来处理请求application/json.

初始化过程中发生错误:

SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Producing media …

java rest get jax-rs jersey

3
推荐指数
1
解决办法
5341
查看次数

@RolesAllowed总是在Jersey资源上拒绝(禁止)

我正在尝试根据我通过Jersey/JAX-RS公开的资源的角色设置身份验证.此资源存在于Glassfish实例中,其中基于角色(特别是通过@RolesAllowed)的身份验证当前正在按需运行.我在servlet容器中运行Jersey:

    <servlet-class>
        com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
Run Code Online (Sandbox Code Playgroud)

并在我的资源上执行基本身份验证; 该要求正在按预期执行.我还为Jersey提供了以下初始化参数:

    <init-param>
        <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>
        <param-value>com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory</param-value>
    </init-param>
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试实际添加@RolesAllowed注释时,所有访问都会失败.例如:

@Path("/my/resource")
@ManagedBean
@RolesAllowed({"SYSTEM"})
public class Resource {
    // Accesses with credentials for a user that has the SYSTEM role fail!
}
Run Code Online (Sandbox Code Playgroud)

如果我注入安全上下文并调用context.isUserInRole(),则会为所有角色返回false.非常奇怪的是,如果我删除此资源的@RolesAllowed注释,并使用有效凭据发出请求,则此类可以成功访问EJB,这需要用户与我最初尝试测试的角色相同.似乎泽西可能正在使用错误的SecurityContext进行身份验证,或者其他一些.还有其他人经历过这个吗?

java authentication rest jax-rs jersey

3
推荐指数
1
解决办法
1508
查看次数

使用自定义对象而不是@FormParam作为JAX-RS资源输入

我有一个示例代码:

@PUT
public String method(@FormParam("firstName") String firstName, 
                     @FormParam("lastName") String lastName ) {
    Person person = new Person(firstName, lastName);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我想停止使用@FormParams并使用Person代替:

@PUT
public String method(@Person person) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

我正在尝试使用自定义BodyReader,但我必须"手动"解析readFrom方法中的InputStream .

这是正确的方法吗?如果是,将InputStream转换为KEY => VALUE HashMap的最佳方法是什么?

java jax-rs jersey

3
推荐指数
1
解决办法
6370
查看次数

RESTful API - 批量操作的分块响应

我正在研究类似REST的API,它将支持某些资源上的批量操作.由于完成此类请求可能需要一些时间,因此我希望在分块响应中返回操作的状态.媒体类型应为JSON.如何使用JAX-RS?

(我知道有StreamingOutput,但它需要手动序列化数据.)

java rest json jax-rs chunked

3
推荐指数
1
解决办法
5698
查看次数

JAX-RS服务抛出404 HTTPException但客户端接收HTTP 500代码

我有一个RESTful资源,它调用EJB来进行查询.如果查询没有结果,则EJB抛出EntityNotFoundException.在catch块中,将抛出一个代码为404的javax.xml.ws.http.HTTPException.

@Stateless
@Path("naturezas")
public class NaturezasResource {

    @GET
    @Path("list/{code}")
    @Produces(MediaType.APPLICATION_JSON)
    public String listByLista(
            @PathParam("code") codeListaNaturezasEnum code) {
        try {
            List<NaturezaORM> naturezas = this.naturezaSB
                    .listByListaNaturezas(code);
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(naturezas);
        } catch (EntityNotFoundException e) { // No data found
            logger.error("there is no Natures with the code " + code);
            throw new HTTPException(404);
        } catch (Exception e) { // Other exceptions
            e.printStackTrace();
            throw new HTTPException(500);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

当我使用没有结果的代码调用Rest Service时,将EntityNotFoundException打印catch块内的日志消息.但是,我的客户端收到HTTP代码500而不是404.为什么我没有收到404代码?

谢谢,

Rafael Afonso

java jax-rs

3
推荐指数
1
解决办法
4272
查看次数

使用JAX-RS客户端从REST服务下载文件

我试图使用JAX-RS从REST服务下载文件.这是我的代码,它通过发送GET请求来调用下载:

private Response invokeDownload(String authToken, String url) {
    // Creates the HTTP client object and makes the HTTP request to the specified URL
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);

    // Sets the header and makes a GET request
    return target.request().header("X-Tableau-Auth", authToken).get();
}
Run Code Online (Sandbox Code Playgroud)

但是,我遇到将Response转换为实际File对象的问题.所以我做的是以下内容:

public File downloadWorkbook(String authToken, String siteId, String workbookId, String savePath)
        throws IOException {
    String url = Operation.DOWNLOAD_WORKBOOK.getUrl(siteId, workbookId);
    Response response = invokeDownload(authToken, url);

    String output = response.readEntity(String.class);
    String filename; 
// some code to retrieve the …
Run Code Online (Sandbox Code Playgroud)

java jax-rs

3
推荐指数
1
解决办法
5063
查看次数

将spring-boot与RESTEasy集成

我正在尝试原型Spring Boot应用程序.我来自Guice JAX-RS应用程序,因此我更喜欢Spring MVC的标准JAX-RS注释.我已经让Jetty起来服务了:

@Configuration
@Import({ResteasyBootstrap.class, SpringBeanProcessorServletAware.class, HttpServletDispatcher.class})
public class EmbeddedJetty {
    @Bean
    @Singleton
    public EmbeddedServletContainerFactory servletContainer() {
        JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
        factory.setPort(9000);
        factory.setSessionTimeout(10, TimeUnit.MINUTES);
        return factory;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我只是无法弄清楚如何正确连接RESTEasy.有了上面的SpringBeanProcessorServletAware保释,似乎在它最终被使用之前ServletContext没有注入ServletContextAware:

java.lang.NullPointerException: null
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessorServletAware.getRegistry(SpringBeanProcessorServletAware.java:30)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:247)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:680)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
Run Code Online (Sandbox Code Playgroud)

我也试过使用SpringContextLoaderListener,但这似乎与spring-boot AnnotationConfigEmbeddedWebApplicationContext类冲突.

我使用的是spring-boot 1.3.3和spring-framework 4.3.0.rc1

spring jax-rs resteasy spring-boot

3
推荐指数
1
解决办法
4479
查看次数