标签: jersey-2.0

使用jersey-spring3从JerseyTest容器中检索托管bean

此问题是从上一个问题指定自定义应用程序上下文的后续问题.

我们正在使用泽西弹簧3将泽西1.x的一些数据服务从泽西1.x迁移到泽西2.x.

我们有一些继承自JerseyTest的测试类.其中一些类使用未在web.xml文件中指定的自定义applicationContext.xml文件.

出于对象模拟的目的,我们将在Jersey资源中模拟一些组件.

在Jersey 1.x中,我们可以通过模拟应用程序上下文文件中的对象

<bean id="mockBean" class="org.easymock.EasyMock" 
    factory-method="createStrictMock" autowire="byName">
    <constructor-arg index="0" value="com.xxx.xxx.ClassToMock" /> 
</bean>
Run Code Online (Sandbox Code Playgroud)

并按如下方式检索这些模拟的实例

ClassToMock obj = (ClassToMock)ContextLoader
    .getCurrentWebApplicationContext()
    .getAutowireCapableBeanFactory()
    .getBean("mockBean");
Run Code Online (Sandbox Code Playgroud)

如何使用Jersey 2.x使用jersey-spring3实现同样的目标?

我已经梳理了API文档,用户指南和一些来源,但无法找到答案.

谢谢.

编辑:

我们将在JAX-RS资源中使用模拟bean.我们的服务接口属于@Autowired我们的资源.

例如

@Path(ProductResource.RESOURCE_PATH)
@Component
@Scope("prototype")
public class ProductResource 
extends GenericResource<Product, BaseModel> {

    /*
     * Members
     */

    public static final String RESOURCE_PATH = "product/";

    @Autowired
    protected ProductService productService;

    ...
Run Code Online (Sandbox Code Playgroud)

我们想要模拟并设定对这些服务的期望.

例如

<bean id="productService" class="org.easymock.EasyMock" 
    factory-method="createStrictMock">
    <constructor-arg index="0" 
        value="com.xxx.xxx.service.ProductService" /> 
</bean>
Run Code Online (Sandbox Code Playgroud)

java spring unit-testing jersey-2.0

9
推荐指数
1
解决办法
4960
查看次数

球衣休息和csv反应

我创建了一个休息调用,使用Jersey回复CSV文件.

休息电话代码是:

@GET
@Path("/ReportWithoutADEStatus")
@Produces({ "application/ms-excel"})
public Response generateQurterlyReport(){
    QuarterlyLabelReport quartLabelReport = new QuarterlyLabelReport();
    String fileLoc=quartLabelReport.generateQurterlyLblRep(false);
    File file=new File(fileLoc);
    return Response.ok(fileLoc,"application/ms-excel")
            .header( "Content-Disposition","attachment;filename=QuarterlyReport_withoutADE.csv")
            .build();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码读取在临时位置创建的csv文件,并使用rest调用响应csv.这完全正常.但现在要求已经改变了.在内存中传输文件内容,并以Rest API中的csv格式对其进行响应.
我从来没有完成流式传输到内存中的文件并回复REST中的内容.

有人可以帮我这个吗?

提前致谢.

java rest jersey-1.0 jersey-2.0

9
推荐指数
1
解决办法
1万
查看次数

泽西和春天的全球异常处理?

我正在使用Jersey&Spring 3.2和Open CMIS开发RESTful Web服务.

我没有使用Spring的MVC模式,它只是Spring IOC和Jersey SpringServlet,控制器类就像下面的代码

@GET
@Path("/{objId:.+}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

public statusMsg addObject(@PathParam("objId") String objId{

    return repoService.addObject(objId);
}
Run Code Online (Sandbox Code Playgroud)

在repoService我正在执行业务逻辑以使用CMIS添加对象,我的问题是我正在捕获与CMIS相关的5个异常然后基本异常即异常但是对于每个服务方法我必须重复它我不想做.

我在Google上搜索并发现@ControllerAdvice是解决此类问题的最佳解决方案,您可以定义所有已检查和未检查的异常以及从应用程序中删除所有try catch块的位置.但它只适用于MVC模式.

问题1:有没有办法在Jersey-Spring框架中使用它?

经过更多研究后,我发现Jersey提供ExceptionMapper来处理自定义异常,但我想捕获更多CMIS异常或默认异常或IO异常等.

问题2:如何使用ExceptionMapper执行此操作?

问题3:我是否采用了正确的方法,或者您是否建议采用更好的方法来处理此类问题.

提前致谢.

java rest spring jersey-2.0

9
推荐指数
1
解决办法
1万
查看次数

找不到媒体类型= text/plain的Jersey MessageBodyWriter

如果发生错误,我正在尝试关注Jersey文档以启用非200响应(https://jersey.java.net/documentation/latest/representations.html#d0e3586)

我的代码看起来像:

@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseBuilder getData(@FormParam("one") String one,@FormParam("two") String two,@FormParam("three") String three) {
    if(one.isEmpty() || two.isEmpty() || three.isEmpty()) {
        logger.error("Missing params for getData");
        throw new WebApplicationException(501);
    }
    return Response.ok();
}
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这会产生以下错误:

[2015-02-01T16:13:02.157 + 0000] [glassfish 4.1] [SEVERE] [] [org.glassfish.jersey.message.internal.WriterInterceptorExecutor] [tid:_ThreadID = 27 _ThreadName = http-listener-1(2 )] [timeMillis:1422807182157] [levelValue:1000] [[找不到媒体类型= text/plain的MessageBodyWriter,类型= class org.glassfish.jersey.message.internal.OutboundJaxrsResponse $ Builder,genericType = class javax.ws.rs .core.Response $ ResponseBuilder.]

java rest glassfish jersey jersey-2.0

9
推荐指数
1
解决办法
2万
查看次数

当@Context用于setter/field/constructor注入时,在Jersey过滤器之前调用HK2 Factory

我已经能够根据如何将对象注入到球衣请求上下文中从过滤器注入我的球衣资源.这允许我成功注入方法参数:

@GET
public Response getTest(@Context MyObject myObject) { // this works
Run Code Online (Sandbox Code Playgroud)

但是,对于setter/field/constructor注入,HK2 Factory 在jersey过滤器之前调用,这意味着provide()方法返回null:

@Override
public MyObject provide() {
    // returns null because the filter has not yet run,
    // and the property has not yet been set
    return (MyObject)context.getProperty("myObject");
}
Run Code Online (Sandbox Code Playgroud)

有没有办法定义何时运行HK2 Factory以便在过滤器运行调用它?如果没有,则解决方法是将MyObject定义为接口,并定义在其构造函数中采用ContainerRequestContext的其他实现; 任何实际使用该实例的尝试都将懒惰地委托给在ContainerRequestContext属性上设置的实现(可能在过滤器运行之前你不会实际使用该实例 - 此时将设置该属性).

但我想了解是否有可能延迟HK2工厂运行的点,使其在过滤器之后运行(在方法参数注入的情况下,它已在过滤器之后运行).如果不可能,那么我想了解是否存在根本原因.

java dependency-injection jersey-2.0 hk2

9
推荐指数
1
解决办法
4477
查看次数

使用Jersey 2.21在REST API请求中的可选参数

我正在玩Jersey 2.21,我想知道是否有可能有一个"可选"的参数,它可以或不存在于对服务器的请求中.

我想成功访问这两种方法:

http://localhost:8080/my_domain/rest/api/myMethod/1
http://localhost:8080/my_domain/rest/api/myMethod
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试使integer(id)参数成为可选参数.

我已声明myMethod如下:

@GET
@Path("myMethod/{id}")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String myMethod(@PathParam("id") Integer id, @Context HttpHeaders hh)
Run Code Online (Sandbox Code Playgroud)

这有效:

http://localhost:8080/my_domain/rest/api/myMethod/1
Run Code Online (Sandbox Code Playgroud)

这也有效:

http://localhost:8080/my_domain/rest/api/myMethod/
Run Code Online (Sandbox Code Playgroud)

但这不起作用,我不明白为什么.它抛出一个404 Not Found错误:

http://localhost:8080/my_domain/rest/api/myMethod
Run Code Online (Sandbox Code Playgroud)

你能指出我正确的方向来解决这个问题吗?我不喜欢斜线在所有REST方法调用中都是强制性的,并且如果可能的话想要压缩它.

java rest jersey jersey-2.0

9
推荐指数
2
解决办法
5628
查看次数

无法通过@Context jersey2.x和weblogic 12.1.3在ContainerRequestFilter中注入HttpServletRequest

我无法使用weblogic 12.1.3通过Jersey 2.22.1中的@Context在ContainerRequestFilter中注入HttpServletRequest.我研究了这个问题存在的几个地方,并且在很多地方我看到它在Jersey 2.4中得到修复,但我仍然看到这个问题.我的实现和代码已附加.如果我遗失任何东西,请告诉我.

AuthFilter筛选

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthFilter implements ContainerRequestFilter {
    @Context
    HttpServletRequest webRequest;

    @Context
    HttpServletResponse webResponse;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        final HttpSession session = webRequest.getSession();
        final String userName = (String)session.getAttribute("USER_NAME");
Run Code Online (Sandbox Code Playgroud)

web.xml中

<servlet>
        <servlet-name>jersey-application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
                  <param-name>jersey.config.server.provider.packages</param-name>
                  <param-value> xyz.xyz.xyz.xyz.xyz.resource</param-value>
              </init-param>

    </servlet>
    <servlet>
        <servlet-name>authentication-servlet</servlet-name>
        <servlet-class>xyz.xyz.xyz.xyz.xyz.xyz.AuthenticationServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>jersey-application</servlet-name>
        <url-pattern>/jaxrs/*</url-pattern>
    </servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

的pom.xml

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>2.22.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.22.1</version>
</dependency>

<dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>2.22.1</version>
        <exclusions>
            <exclusion>
                <artifactId>spring-context</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion>
                <artifactId>spring-beans</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion> …
Run Code Online (Sandbox Code Playgroud)

weblogic12c jersey-2.0

9
推荐指数
1
解决办法
2476
查看次数

通用<?>类型的泽西警告"无法解析为具体类型"

我在我的服务中使用Jersey 2.25Google Guava BiMap.我已经声明了我的webservice类的成员变量BiMap<String, myClass<? >>.我的Jetty服务器启动后,我收到警告:

警告:类型com.google.common.collect.BiMap<java.lang.String, myClass<?>>from的参数1 public myProvider(com.google.common.collect.BiMap<java.lang.String, myClass<?>>无法解析为具体类型.

我无法删除<?>运算符,因为没有运算符,myClass的某些元素将无法正确解析<?>.我也尝试过外观模式,但在模式中我也需要<?>操作员.

我该如何修复此警告?

java generics jersey-2.0

9
推荐指数
0
解决办法
1144
查看次数

将JacksonJsonProvider与ObjectMapper + JavaTimeModule一起注册到Jersey 2 Client

我正在尝试编组包含ISO格式的时间戳的响应,如下所示:

{
...
    "time" : "2014-07-02T04:00:00.000000Z"
...
}
Run Code Online (Sandbox Code Playgroud)

进入ZonedDateTime我的域模型对象中的字段.最终,如果我使用在以下片段中注释的解决方案,它会起作用.在SO上有许多类似的问题,但我想得到一个具体的答案,另一种使用的方法JacksonJsonProviderObjectMapper + JavaTimeModule什么问题?

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        JacksonJsonProvider provider = new JacksonJsonProvider(mapper);
        Client client = ClientBuilder.newBuilder()
//                .register(new ObjectMapperContextResolver(){
//                    @Override
//                    public ObjectMapper getContext(Class<?> type) {
//                        ObjectMapper mapper = new ObjectMapper();
//                        mapper.registerModule(new JavaTimeModule());
//                        return mapper;
//                    }
//                })
                .register(provider)
                .register(JacksonFeature.class)
                .build();
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.ZonedDateTime: no String-argument constructor/factory method to deserialize from String …
Run Code Online (Sandbox Code Playgroud)

java jackson jsr310 jersey-2.0

9
推荐指数
2
解决办法
1万
查看次数

在简单的Jersey网络应用程序中获取大量"从多个位置扫描"警告

一段时间后回到Java,我正在尝试使用命令行在Java 8,Jersey 2.27和Jetty 9.4.9上使用简单的RESTful API.该应用程序确实有效,但我不断收到数百条警告:

2018-04-27 01:17:24.845:WARN:oeja.AnnotationParser:main: Unrecognized runtime asm version, assuming 393216
2018-04-27 01:17:24.945:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.ArrayELResolver scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/ArrayELResolver.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/ArrayELResolver.class
2018-04-27 01:17:24.949:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.BeanELResolver$BeanProperties scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/BeanELResolver$BeanProperties.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/BeanELResolver$BeanProperties.class
2018-04-27 01:17:24.952:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.BeanELResolver$BeanProperty scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/BeanELResolver$BeanProperty.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/BeanELResolver$BeanProperty.class
2018-04-27 01:17:24.954:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.BeanELResolver scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/BeanELResolver.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/BeanELResolver.class
2018-04-27 01:17:24.959:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.CompositeELResolver scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/CompositeELResolver.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/CompositeELResolver.class
2018-04-27 01:17:24.961:WARN:oeja.AnnotationParser:qtp988458918-12: javax.el.ELContext scanned from multiple locations: jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/el-api-2.2.jar!/javax/el/ELContext.class, jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/el/ELContext.class
2018-04-27 01:17:24.962:WARN:oeja.AnnotationParser:qtp988458918-15: javax.annotation.Generated scanned from multiple locations: jar:file:///paste4j/deployment/jetty-runner-9.4.9.v20180320.jar!/javax/annotation/Generated.class, jar:file:///tmp/jetty-0.0.0.0-8081-paste4j.war-_-any-8355640322316327743.dir/webapp/WEB-INF/lib/javax.annotation-api-1.2.jar!/javax/annotation/Generated.class
2018-04-27 01:17:24.962:WARN:oeja.AnnotationParser:qtp988458918-15: …
Run Code Online (Sandbox Code Playgroud)

java jersey-2.0

9
推荐指数
1
解决办法
1841
查看次数