[JERSEY-2844] Content-Type header in response not set correctly when CXF present on classpath and 'Accept' header present Created: 20/Apr/15  Updated: 20/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.16, 2.17
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: jgriswold Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Thank you all for your amazing work on Jersey!

I have a Jersey app which uses the CXF client package for some web service requests. While upgrading to 2.16, I came across an issue when an incoming request includes an 'Accept' header. It looks like the response's ContentType header contains the result of AcceptableMediaType#toString, e.g.

Content-Type: {text/plain, q=1000}

The curly braces are causing problems for clients which inspect the response headers, so unfortunately this issue prevents me from upgrading. From my testing this issue is present as of 2.16 and cannot be reproduced in earlier versions.

Steps to reproduce:
1) Create a new app using the quickstart maven archetype

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example \
-DarchetypeVersion=2.16

2) Add a dependency on the latest CXF client in simple-service/pom.xml. One important note is that I can only reproduce this issue when the dependency is listed before jersey-container-grizzly2-http

      <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-client</artifactId>
        <version>3.0.4</version>
      </dependency>

3) Start the service via mvn compile exec:java
4) Requests to /myapp/myresource will include a malformed Content-Type response header if the Accept request header is present:

simple-service% curl -v localhost:8080/myapp/myresource 2>&1 | grep '< Content-Type:'
< Content-Type: text/plain

vs.

simple-service% curl -H 'Accept: text/plain' -v localhost:8080/myapp/myresource 2>&1 | grep '< Content-Type:'
< Content-Type: {text/plain, q=1000}





[JERSEY-2843] InboundMessageContext.hasEntity() fails to catch IllegalStateException even though it tries to. Created: 17/Apr/15  Updated: 17/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: dadowns Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

InboundMessageContext.hasEntity() fails to catch IllegalStateException even though it tries to.

Example:

if (response.hasEntity())

{ Object object = response.readEntity(....) .... do stuff }

If the response stream has been closed then the response.hasEntity() will throw an exception due to an extra entityContent.ensureNotClosed() check inside hasEntity(), skipping the try catch that follows, and never return false. Under such conditions there is no safe way to check whether an entity exists.

The fix and updated unit test is included in:
https://github.com/jersey/jersey/pull/138






[JERSEY-2842] Improve error when http response is written Created: 17/Apr/15  Updated: 17/Apr/15

Status: Open
Project: jersey
Component/s: containers
Affects Version/s: 2.16
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: sebadiaz Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

all



 Description   

need to return the response in sending the actual response.

java.lang.IllegalArgumentException: setContentLength(0) when already written 159
at org.eclipse.jetty.server.Response.setContentLength(Response.java:990)
at org.glassfish.jersey.servlet.internal.ResponseWriter.writeResponseStatusAndHeaders(ResponseWriter.java:142)
at org.glassfish.jersey.server.ServerRuntime$Responder$1.getOutputStream(ServerRuntime.java:611)
at org.glassfish.jersey.message.internal.CommittingOutputStream.commitStream(CommittingOutputStream.java:200)
at org.glassfish.jersey.message.internal.CommittingOutputStream.flushBuffer(CommittingOutputStream.java:305)
at org.glassfish.jersey.message.internal.CommittingOutputStream.commit(CommittingOutputStream.java:261)
at org.glassfish.jersey.message.internal.CommittingOutputStream.close(CommittingOutputStream.java:276)
at org.glassfish.jersey.message.internal.OutboundMessageContext.close(OutboundMessageContext.java:834)
at org.glassfish.jersey.server.ContainerResponse.close(ContainerResponse.java:411)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:691)






[JERSEY-2841] @NameBinding is not working on method Created: 16/Apr/15  Updated: 16/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: zeckson Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

jetty 8, java 7, mac os, jersey 2.17



 Description   

I have the following RootResource class

@Path(value = "/root")
@Produces(value = {MediaType.APPLICATION_XML + RestUtil.CHARSET_UTF8, MediaType.APPLICATION_JSON + RestUtil.CHARSET_UTF8})
public class RootResource implements Resource {
  public RootResource() {
  }

  @Path(value = "/mysubresource")
  @OAuth
  public SubresourceSubresource sub_Mysubresource() {
    return new SubresourceSubresource();
  }
}

There is a filter @OAuth on method sub_Mysubesource() but it's never called for some reason.

OAuth.java

@Retention(RetentionPolicy.RUNTIME)
@NameBinding
public @interface OAuth {
}

OAuthRequestFilter.java

@OAuth
public class OAuthRequestFilter implements ContainerRequestFilter, ContainerResponseFilter {

  public OAuthRequestFilter() {
  }

  public void filter(ContainerRequestContext request) {
    System.out.println("Start OAUTH!");
  }

  public void filter(ContainerRequestContext request, ContainerResponseContext response) {
    System.out.println("End OAUTH!");
  }
  
}

Documentation says that it's a valid case to attach @NameBinding to method. https://jersey.java.net/apidocs/2.17/jersey/javax/ws/rs/NameBinding.html






[JERSEY-2840] jersey-apache-connector.jar missing OSGI properties Created: 10/Apr/15  Updated: 10/Apr/15

Status: Open
Project: jersey
Component/s: connectors, osgi
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Mark Woon Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Please add OSGI bundle properties to jersey-apache-connector.jar.






[JERSEY-2839] Invocable.create return Source.UNKNOWN on @Valid entity param Created: 09/Apr/15  Updated: 09/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: icode Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   
A resource method
@Inject
private ExtendedUriInfo extendedUriInfo;

@PUT
@Path("{id}")
public final Response replace(@PathParam("id") final String id, @NotNull @Valid final T model) {
extendedUriInfo.getMatchedResourceMethod().getInvocable().getParameters().get(1).getSource();// UNKNOWN
    ...
}
org.glassfish.jersey.server.model.Parameter
public static Parameter create(
            Class concreteClass,
            Class declaringClass,
            boolean keepEncoded,
            Class<?> rawType,
            Type type,
            Annotation[] annotations) {
.....
for (Annotation annotation : annotations) {  //annotations=[@NotNull,@Valid]
            if (ANNOTATION_HELPER_MAP.containsKey(annotation.annotationType())) {
                ParamAnnotationHelper helper = ANNOTATION_HELPER_MAP.get(annotation.annotationType());
                paramAnnotation = annotation;
                paramSource = helper.getSource();
                paramName = helper.getValueOf(annotation);
            } else if (Encoded.class == annotation.annotationType()) {
                paramEncoded = true;
            } else if (DefaultValue.class == annotation.annotationType()) {
                paramDefault = ((DefaultValue) annotation).value();
            } else {
                // Take latest unknown annotation, but don't override known annotation
                if ((paramAnnotation == null) || (paramSource == Source.UNKNOWN)) {
                    paramAnnotation = annotation;
                    paramSource = Source.UNKNOWN;
                    paramName = getValue(annotation);
                }
            }
        }
if (paramAnnotation == null) {
            paramSource = Parameter.Source.ENTITY;
}
.....
}





[JERSEY-2838] Response.created(URI) does not convert relative URI to absolute Created: 08/Apr/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.17
Fix Version/s: None

Type: Bug Priority: Major
Reporter: briehman Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Returning a Response based upon a relative URI under Jersey 2.17 does not convert the URI to an absolute path relative to the request URI as defined by the jax-rs Response class declares:

Response Javadoc

If a relative URI is supplied it will be converted into an absolute URI by resolving it relative to the request URI

Modifying the provided HelloWorldResource as follows:

@Path("helloworld")
public class HelloWorldResource {
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public Response post() throws Exception {
        return Response.created(new URI("relative")).build();
    }
}

POST to http://localhost:8080/helloworld-webapp/helloworld:
Expected Location header: http://localhost:8080/helloworld-webapp/helloworld/relative
Actual Location header: http://localhost:8080/helloworld-webapp/relative

This works correctly in Jersey 1.x and appears to be a regression in 2.x.



 Comments   
Comment by briehman [ 08/Apr/15 ]

This is potentially a duplicate of https://java.net/jira/browse/JERSEY-1910 but I cannot link it.





[JERSEY-2837] GrizzlyConnector can cause Jersey to return premature end stream Created: 08/Apr/15  Updated: 17/Apr/15  Resolved: 17/Apr/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.17
Fix Version/s: 2.18

Type: Bug Priority: Critical
Reporter: luengnat Assignee: Marek Potociar
Resolution: Fixed Votes: 0
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

There is a bug in handling byte stream that contains 0xFF byte. When it does, it will treat the byte as EOF marker instead. This is due to mishandling of negative byte values



 Comments   
Comment by Libor Kramolis [ 08/Apr/15 ]

@luengnat May you provide us more information about the issue? Where the bug is and how to reproduce it. May you prepare reproducible test case? Thanks.

Comment by luengnat [ 08/Apr/15 ]

The test case is already there in the patch.
https://github.com/jersey/jersey/pull/155

Comment by luengnat [ 08/Apr/15 ]

It's a duplicate of JERSEY-2817, JERSEY-2498

Comment by luengnat [ 16/Apr/15 ]

Code is ready to be merged
https://github.com/jersey/jersey/pull/155





[JERSEY-2836] Use of private class in httpsclientservergrizzly example Created: 08/Apr/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: examples
Affects Version/s: 2.17
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Opher Shachar Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The httpsclientservergrizzly example in version 2.17 uses an internal private class org.glassfish.jersey.internal.util.Base64 and a jersey specific class org.glassfish.jersey.server.ContainerRequest.
The problem is that programmers - in my team but, I believe also elsewhere - will copy paste that code into production software causing a dependence on Jersey and worse, on an internal class of Jersey.

Luckily there's an easy fix to the use of both these classes.
A patch is here: https://gist.github.com/ophers/1a810a6ca90b1448c1e6

This should be an easy fix. And it is important.

Thanks.






[JERSEY-2835] Add new ApacheClientProperties.DISABLE_AUTOMATIC_RETRIES flag Created: 07/Apr/15  Updated: 07/Apr/15

Status: Open
Project: jersey
Component/s: connectors
Affects Version/s: 2.17
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: khaing211 Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Add new ApacheClientProperties.DISABLE_AUTOMATIC_RETRIES flag
Calling HttpClientBuilder#disableAutomaticRetries






[JERSEY-2834] Jersey async API can't handle no result case Created: 07/Apr/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: hongxingli Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

any



 Description   

for the case below, after logout, no result need to return, but if I assign null, then Jersey will throw an exception

    @POST
    @Path("logout")
    @ManagedAsync
    public void logout(@Suspended final AsyncResponse asyncResponse) {
      .......  
      asyncResponse.resume(null);
    }


 Comments   
Comment by Libor Kramolis [ 08/Apr/15 ]

I think you should return something. I guess you would like to return 2xx response code. What about returning 204 No Content:

asyncResponse.resume(Response.noContent().build());




[JERSEY-2833] JS client disconnect leaves SSE connections in CLOSE_WAIT Created: 05/Apr/15  Updated: 05/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.13, 2.17
Fix Version/s: None

Type: Bug Priority: Major
Reporter: jvxr Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Production



 Description   

There seems to be a problem with Jersey SSE closing the underlying connections of ChunkedOutput. On client disconnect, the connections stay in CLOSE_WAIT till the tomcat server that is running the webapp is restarted.

Steps to replicate the issue

Create a singleton instance of a subclass of SseBroadcaster, constructor must call super(SseBroadcaster.class); Override onClose and onException methods.
Add a resource that uses this custom broadcaster and provide method to subscribe to SSE

Build a JS client that subscribes to SSE events as mentioned here
https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events

Try closing the eventSource from the browser, the connection immediately goes into the CLOSE_WAIT state.

Problem

onClose of the custom broadcaster never gets invoked, so the ChunkedOutput is never closed, and since the ChunkedOutput corresponds to a connection it lingers around bleeding the server of connections till it chokes and cannot accept any more connections.






[JERSEY-2832] Inconsistent behavior using @BeanParam, a ParamConverter, and an ExceptionMapper Created: 30/Mar/15  Updated: 09/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.17
Fix Version/s: None

Type: Bug Priority: Major
Reporter: atomala Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

This bug only seems to be happening when using a custom ParamConverter, a @BeanParam wrapper object, and a custom ExceptionMapper.

I am using a custom ParamConverter for some of my @QueryParam and @PathParam objects. When the ParamConverter throws a custom exception because it couldn't be converted correctly (i.e. bad parameters passed in), Jersey will catch my custom exception and wrap it in a ParamException.QueryParamException or a ParamException.PathParamException. I can write my exception handling logic to unwrap the Jersey exception and get my custom exception and then I am able to return a useful error message to the user using the ExceptionMapper.

When I use a @BeanParam object with the exact same @QueryParam and @PathParam objects contained within, the behavior is not the same. If an error is thrown in the ParamConverter, Jersey catches the exception and throws a NotFoundException instead of a ParamException.QueryParamException or a ParamException.PathParamException. It is not possible to create a custom error message since there is no context in the NotFoundException, which is also thrown when an endpoint is not found. It seems like Jersey should still throw a ParamException.QueryParamException or a ParamException.PathParamException instead of a NotFoundException when using the @BeanParam wrapper object.

I have switched my code to use the @QueryParam and @PathParam objects and manually mapped them to my bean object. It would be much nicer to use the @BeanParam object instead to keep my code clean.



 Comments   
Comment by Libor Kramolis [ 01/Apr/15 ]

Hello @atomala and thanks for issue report. May you provide us reproducible test case? E.g. simple JerseyTest app to reproduce the problem. Thanks.

Comment by atomala [ 07/Apr/15 ]

@Libor I have created a test application. How can I upload it to this ticket? I don't have the ability to attach anything.

Comment by Libor Kramolis [ 08/Apr/15 ]

@atomala Thanks. May you store it in https://gist.github.com/?

Comment by atomala [ 09/Apr/15 ]

@Libor

I just put the project on github since it's a complete project. It's built using maven and spring-boot. If you clone it and run the following command, it will start the jersey application on port 8080.

mvn clean verify spring-boot:run

There is documentation in the DemoController class that contains the curl messages that produce the error.

If you have any questions about the project, please let me know.

https://github.com/atomala1/jerseyDemo





[JERSEY-2831] Unable to parse wald.xsd schemas with newer jaxb plugin Created: 27/Mar/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 1.18.1
Fix Version/s: None

Type: Task Priority: Major
Reporter: puntogil Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

org.jvnet.jaxb2.maven2:maven-jaxb22-plugin:0.12.3

Apache Maven 3.1.1 (NON-CANONICAL_2013-11-08_14-32_mockbuild; 2013-11-08 15:32:41+0100)
Maven home: /usr/share/maven
Java version: 1.7.0_75, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75-2.5.4.2.fc20.i386/jre
Default locale: it_IT, platform encoding: UTF-8
OS name: "linux", version: "3.18.9-100.fc20.i686", arch: "i386", family: "unix"



 Description   

Newer jaxb plugin as jaxb package required a web connection for generate source code
I disabled schema validation since the validation code
doesn't respect the catalog and will do online lookups
and i used bindings.cat [1] instead of catalog.xml
Added this configuration to the jaxb plugin:

<executions>
  <execution>
    <id>bindings</id>
    <phase>generate-sources</phase>
    <goals>
      <goal>generate</goal>
    </goals>
    <configuration>
      <generatePackage>com.sun.research.ws.wadl</generatePackage>
      <catalog>${basedir}/etc/bindings.cat</catalog>
      <schemaDirectory>${basedir}/etc</schemaDirectory>
      <bindingDirectory>${basedir}</bindingDirectory>
      <bindingIncludes>
	<bindingInclude>wadl.xsd</bindingInclude>
      </bindingIncludes>
      <forceRegenerate>false</forceRegenerate>
      <episode>true</episode>
      <specVersion>2.2</specVersion>
      <extension>true</extension>
      <strict>false</strict>
      <args>
	<arg>-npa</arg>
      </args>
    </configuration>
  </execution>
</executions>

Our builder system don't provides a web connection
Please, consider these changes

Task info: http://koji.fedoraproject.org/koji/taskinfo?taskID=9346670

[1]

PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "XMLSchema.dtd"
PUBLIC "http://www.w3.org/2001/XMLSchema.dtd" "XMLSchema.dtd"
SYSTEM "http://www.w3.org/2001/XMLSchema.dtd" "XMLSchema.dtd"

PUBLIC "datatypes" "datatypes.dtd"
SYSTEM "datatypes.dtd" "datatypes.dtd"

SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"


 Comments   
Comment by puntogil [ 27/Mar/15 ]

sorry forgot again one thing
modified also wadl.xsd
schemaLocation="./xml.xsd

Comment by Libor Kramolis [ 08/Apr/15 ]

@puntogil I'm sorry I have no idea what fedoraproject is.

And may you prepare full reproducible test case? Currently I don't see where exactly do you have problem with new JAXB plugin. You can use https://gist.github.com/ to prepare test app. Thanks.





[JERSEY-2830] Memory leak when of response.readEntity when using JAX-RS Client API Created: 27/Mar/15  Updated: 09/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.17
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: nogyara Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7
OracleJDK 1.7.0 u67
Tomcat 7.0.47
Jersey 2.17/HK2 2.4.0 b10


Tags: memory-leak

 Description   

This is basically the same issue as described in JERSEY-2463 which I cannot reopen so I've created a new issue.

It's easy to reproduce: working with the same Client instance for multiple REST API calls implemented using code like this:

PrtgRestClient.java
	PrtgGroup getRootGroup() {
		Builder builder = baseTarget()
				.register(new ContentTypeClientResponseFilter(MediaType.APPLICATION_XML_TYPE))
				.path("table.xml")
				.queryParam("content", "sensortree")
				.queryParam("id", rootGroupId)
				.queryParam("output", "xml")
				.request(MediaType.APPLICATION_XML_TYPE);
//		String response = builder.get(String.class);
//		PrtgResponse prtgResponse = parseEntity(response, PrtgResponse.class);
		PrtgResponse prtgResponse = builder.get(PrtgResponse.class);

		List<PrtgGroup> groups = assertState("There must be exactly one root group", prtgResponse.getTree().getGroups(), hasSize(1));
		return groups.get(0);
	}

this creates a new instance of PerThreadContext for each and every invocation of this method (all invocations come from the same thread). Because we call REST API often, we soon end up with OutOfMemoryError - and analysis of the memory dump shows that 1.8 GB of memory is retained for more than 4000 instances of PerThreadContext (and objects retained by them of course).

When parsing is done manually, like in the commented out part of the sample code, no superfluous instances of PerThreadContext get created.

Like I mentioned, this looks pretty serious to me for it can cause massive memory leaking in production.

This is the stacktrace:

Daemon Thread [http-bio-8080-exec-5] (Suspended (entry into method <init> in PerThreadContext))	
	owns: Object  (id=18580)	
	owns: Object  (id=18581)	
	owns: SocketWrapper<E>  (id=18582)	
	PerThreadContext.<init>() line: 62	
	NativeConstructorAccessorImpl.newInstance0(Constructor, Object[]) line: not available [native method]	
	NativeConstructorAccessorImpl.newInstance(Object[]) line: 57	
	DelegatingConstructorAccessorImpl.newInstance(Object[]) line: 45	
	Constructor<T>.newInstance(Object...) line: 526	
	ReflectionHelper.makeMe(Constructor<?>, Object[], boolean) line: 1129	
	ClazzCreator<T>.createMe(Map<SystemInjecteeImpl,Object>) line: 274	
	ClazzCreator<T>.create(ServiceHandle<?>, SystemDescriptor<?>) line: 368	
	SystemDescriptor<T>.create(ServiceHandle<?>) line: 471	
	SingletonContext$1.compute(ContextualInput<Object>) line: 82	
	SingletonContext$1.compute(Object) line: 70	
	Cache$OriginThreadAwareFuture$1.call() line: 97	
	FutureTask<V>.run() line: 262	
	Cache$OriginThreadAwareFuture.run() line: 154	
	Cache<K,V>.compute(K) line: 199	
	SingletonContext.findOrCreate(ActiveDescriptor<T>, ServiceHandle<?>) line: 121	
	Utilities.createService(ActiveDescriptor<T>, Injectee, ServiceLocatorImpl, ServiceHandle<T>, Class<?>) line: 2064	
	ServiceHandleImpl<T>.getService(ServiceHandle<T>) line: 105	
	ServiceHandleImpl<T>.getService() line: 87	
	ServiceLocatorImpl._resolveContext(Class<Annotation>) line: 2047	
	ServiceLocatorImpl.access$000(ServiceLocatorImpl, Class) line: 120	
	ServiceLocatorImpl$2.compute(Class<Annotation>) line: 186	
	ServiceLocatorImpl$2.compute(Object) line: 182	
	Cache$OriginThreadAwareFuture$1.call() line: 97	
	FutureTask<V>.run() line: 262	
	Cache$OriginThreadAwareFuture.run() line: 154	
	Cache<K,V>.compute(K) line: 199	
	ServiceLocatorImpl.resolveContext(Class<Annotation>) line: 2066	
	Utilities.createService(ActiveDescriptor<T>, Injectee, ServiceLocatorImpl, ServiceHandle<T>, Class<?>) line: 2042	
	ServiceHandleImpl<T>.getService(ServiceHandle<T>) line: 105	
	ServiceHandleImpl<T>.getService() line: 87	
	ContextInjectionResolver$2.provide() line: 126	
	XmlRootElementJaxbProvider$App(XmlRootElementJaxbProvider).readFrom(Class<Object>, MediaType, Unmarshaller, InputStream) line: 138	
	XmlRootElementJaxbProvider$App(AbstractRootElementJaxbProvider).readFrom(Class<Object>, Type, Annotation[], MediaType, MultivaluedMap<String,String>, InputStream) line: 123	
	ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorContext, MessageBodyReader, EntityInputStream) line: 266	
	ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorContext) line: 236	
	ReaderInterceptorExecutor.proceed() line: 156	
	MessageBodyFactory.readFrom(Class<?>, Type, Annotation[], MediaType, MultivaluedMap<String,String>, PropertiesDelegate, InputStream, Iterable<ReaderInterceptor>, boolean) line: 1085	
	ClientResponse(InboundMessageContext).readEntity(Class<T>, Type, Annotation[], PropertiesDelegate) line: 853	
	ClientResponse(InboundMessageContext).readEntity(Class<T>, PropertiesDelegate) line: 785	
	ClientResponse.readEntity(Class<T>) line: 326	
	JerseyInvocation.translate(ClientResponse, RequestScope, Class<T>) line: 790	
	JerseyInvocation.access$500(JerseyInvocation, ClientResponse, RequestScope, Class) line: 91	
	JerseyInvocation$2.call() line: 687	
	Errors.process(Callable<T>, boolean) line: 315	
	Errors.process(Producer<T>, boolean) line: 297	
	Errors.process(Producer<T>) line: 228	
	RequestScope.runInScope(Producer<T>) line: 444	
	JerseyInvocation.invoke(Class<T>) line: 683	
	JerseyInvocation$Builder.method(String, Class<T>) line: 411	
	JerseyInvocation$Builder.get(Class<T>) line: 307	
	PrtgRestClient.getRootGroup() line: 104	
	PrtgAdapter.getPodGroup(PodEntity) line: 55	
	PrtgModule.retrievePodGroup(PodEntity) line: 43	
	PrtgModule.deleteEmptyDevices(MessageCollector, PodEntity) line: 54	
	PrtgModule.deleteUselessObjects(MessageCollector, PodEntity) line: 48	
	PrtgModule.synchronize(SyncerModule$Context, MessageCollector) line: 36	
	SyncerFormView$1.buttonClick(Button$ClickEvent) line: 115	
	...


 Comments   
Comment by Michal Gajdos [ 01/Apr/15 ]

I think this is already fixed in master and should be in 2.18. Can you, please, confirm either on 2.18-SNAPSHOT or wait until 2.18 is released and confirm then? In the meantime, please, refer to this [1] article when you can find what to avoid when using Jersey Client.

[1] https://blogs.oracle.com/japod/entry/how_to_use_jersey_client

Comment by nogyara [ 09/Apr/15 ]

Hi Michal,
if the behaviour from the article you linked here is going to stick for a while, it should be definitely documented. I just re-checked the latest Jersey 2.17 docs and there's no warning about this at all, I'd even say that the config inheritance described in the docs for both the Client and WebTarget (https://jersey.java.net/documentation/latest/client.html#d0e4405) promotes this config without reuse.

I'd prefer to test it on the final version 2.18, any guess when it's going to be out? According to the roadmap, it should be any day by now, right?





[JERSEY-2829] javax.ws.rs.core.Response#readEntity sometimes returns an empty string, if hasEntity() is called first Created: 26/Mar/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: eiden Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

OSX Yosemite, 1.8.0_31



 Description   

javax.ws.rs.core.Response#readEntity(String.class) sometimes returns an empty string if hasEntity() is called prior to readEntity.

This test case fails:

import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static javax.ws.rs.client.ClientBuilder.newClient;
import static org.fest.assertions.api.Assertions.assertThat;

public class ReadEntityTestCase {

    static final String RESPONSE_VALUE = "value";

    WebTarget target;

    @Before
    public void setUp() throws Exception {
        Client client = newClient()
                    .register(new ClientRequestFilter() {
                        @Override
                        public void filter(ClientRequestContext requestContext) throws IOException {
                            ByteArrayInputStream entity = new ByteArrayInputStream(RESPONSE_VALUE.getBytes(StandardCharsets.UTF_8));
                            requestContext.abortWith(Response.ok(entity).build());
                        }
                    });

        target = client.target("http://127.0.0.1:-1");
    }

    @Test
    public void hasEntityAndReadEntity() throws Exception {
        Response response = target.request().get();
        response.bufferEntity();

        for (int i = 0; i < 10; i++) {
            response.hasEntity();
            String value = response.readEntity(String.class);

            assertThat(value).isEqualTo(RESPONSE_VALUE);
        }
    }
}

If I comment out response.hasEntity();, the test passes.



 Comments   
Comment by Libor Kramolis [ 08/Apr/15 ]

@eiden Thanks for the report. How often is sometimes? Does it mean it sometimes passes also with calling response.hasEntity()?





[JERSEY-2828] "Jersey bean validation" does not validate @PathParam on sub resource location Created: 20/Mar/15  Updated: 16/Apr/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Maxonchik Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Thare is no validation on sub resource location.

For example:

@Path("{resourceId}/action")
public ActionResource actionController(@PathParam("resourceId") @PathId @Pattern(regexp = "\\d{1,10}") String resourceId) {
        ....
}

parameter "resourceId" will not be validated



 Comments   
Comment by Maxonchik [ 16/Apr/15 ]

Validation can be enabled by @ValidateOnExecution, but it could be enabled by default





[JERSEY-2827] Filter priority - negative numbers Created: 20/Mar/15  Updated: 21/Apr/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: walec51 Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The LoggingFilter has priority set to @Priority(Integer.MIN_VALUE)
However we noticed that it is actually executed after our own filter which had @Priority(100).
When we extended the LoggingFilter and gave it @Priority(0) the it started to execute before the filter with @Priority(100).

So there is either a problem with the ordering mechanism or the LoggingFilter should have @Priority(0).



 Comments   
Comment by Michal Gajdos [ 23/Mar/15 ]

Hi,

where is this happening (client/server)? Which version of Jersey do you use?

thanks,
Michal

Comment by Libor Kramolis [ 08/Apr/15 ]

@walec51 May you complete the report please.

Comment by abhirockzz [ 21/Apr/15 ]

I confirmed that the issue occurs on the server side with Jersey 2.10.4 (GlassFish 4.1.0). Seems as if negative Priority values are not being taken into account. I do not see anything in the JAX-RS specification as well w.r.t usage of negative values in @Priority. All that's stated is that the server side filters will be invoked in ascending order of @Priority





[JERSEY-2826] Jersey EntityFilteringFeature doesn't work correctly with abstract classes Created: 20/Mar/15  Updated: 08/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.17
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: satyavrat_prabhune Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7, JDK 1.7



 Description   

I want to use Jersey's EntityFilteringFeature with my abstract super class. When EntityFilteringFeature is NOT registered, I get correct representation of concrete child class, but the moment I register EntityFilteringFeature, child class field is not marshalled. Appears to be a Jersey bug.

I am using MOXy provider.

Please see all details at http://stackoverflow.com/questions/29140367/jersey-entityfilteringfeature-doesnt-work-correctly-with-abstract-classes






[JERSEY-2825] MOXyJsonProvider cannot unmarshall JSON arrays into custom collection types Created: 16/Mar/15  Updated: 16/Mar/15

Status: Open
Project: jersey
Component/s: media
Affects Version/s: 2.18
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Note: This is a problem in MOXy 2.6. It's filed against Jersey just to track the progress and the issue should be closed when new MOXy is integrated into Jersey.

Consider you have this JSON:

[{"jaxbBean":{"value":"one"}},{"jaxbBean":{"value":"two"}},{"jaxbBean":{"value":"three"}}]

Resource Method like:

@POST
@Path("custom")
public MyArrayList<JaxbBean> postCustom(final MyArrayList<JaxbBean> l) {
    return l;
}

Where MyArrayList looks like:

public class MyArrayList<T> extends ArrayList<T> {

    public MyArrayList() {
    }

    public MyArrayList(final Collection<T> a) {
        super(a);
    }

}

The JSON is unmarshalled as list of lists (MyArrayList of MyArrayLists) but JaxbBeans are not in unmarshalled object.






[JERSEY-2824] ObjectGraphImpl throwing NullPointerException when role entity has an abstract method implementation returning a custom object Created: 15/Mar/15  Updated: 24/Mar/15  Resolved: 24/Mar/15

Status: Resolved
Project: jersey
Component/s: extensions, security
Affects Version/s: 2.16
Fix Version/s: 2.18

Type: Bug Priority: Major
Reporter: rehan.shaukat Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Mac OS X 10.10.2 (14C1510)
Java 1.7.0_60



 Description   

I am trying the new feature in *Jersey 2.16* that supports *role-based entity filtering via Jackson*.

`NullPointerException` is thrown:

    java.lang.NullPointerException
	at org.glassfish.jersey.message.filtering.ObjectGraphImpl.getSubgraphs(ObjectGraphImpl.java:109)
	at org.glassfish.jersey.jackson.internal.JacksonObjectProvider.createSubfilters(JacksonObjectProvider.java:89)
	at org.glassfish.jersey.jackson.internal.JacksonObjectProvider.transform(JacksonObjectProvider.java:74)
	at org.glassfish.jersey.jackson.internal.JacksonObjectProvider.transform(JacksonObjectProvider.java:67)
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.createFilteringObject(AbstractObjectProvider.java:138)
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:100)
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:83)
	at org.glassfish.jersey.jackson.internal.FilteringJacksonJaxbJsonProvider.writeTo(FilteringJacksonJaxbJsonProvider.java:130)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.spi.ContentEncoder.aroundWriteTo(ContentEncoder.java:138)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.spi.ContentEncoder.aroundWriteTo(ContentEncoder.java:138)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1118)
	at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:662)
	at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:418)
	at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:408)
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:306)
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
	at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
	at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)

if I use a Jackson entity inherited from an abstract class, having an abstract method that returs another object of some custom class.

`JacksonFeature` and `SecurityEntityFilteringFeature` is registered and resource method looks like:

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @RolesAllowed(ACTUAL_ROLE)
    public User getTestData() {
      return new User("name", "address");
    }

where User is defined as:

    public class User extends SuperUser {
      
      private String name;
      private String address;
      
      public User(String name, String address){
        this.name = name;
        this.address = address;
      }
    
      public String getName() {
        return name;
      }
      
      public String getAddress() {
        return address;
      }
    
      @Override
      public MoreData getMoreData() {
        return null;
      }
    }
    
    abstract class SuperUser {
        public abstract MoreData getMoreData();
    }
    
    class MoreData {
    }

Everything works fine If `getMoreData()` returns a non-custom objection for instance `String`.



 Comments   
Comment by rehan.shaukat [ 15/Mar/15 ]

don't see any edit option to make formatting better

Comment by Michal Gajdos [ 18/Mar/15 ]

Moving to backlog for now (plan to look into it very soon).





[JERSEY-2823] Jersey does not handle PUT with Content-Type="" Created: 12/Mar/15  Updated: 19/Mar/15  Resolved: 17/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: timuralp Assignee: Jakub Podlesak
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Linux



 Description   

If a client submits a PUT request with Content-Type set to "" (empty string), Jersey returns error 400.

I could not find anything in the HTTP specification prohibiting a client from sending such requests (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html), but maybe I did not read it carefully. If this behavior is permitted, then Jersey does not process these requests at all – it is impossible to register any handler for it.

If such requests are prohibited, please point me to the documentation and mark this as invalid (I'll look into fixing the client).



 Comments   
Comment by Jakub Podlesak [ 17/Mar/15 ]

http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7

Here is a quote from part 14.17 of the very same doc you have referred originally:

The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.

Content-Type = "Content-Type" ":" media-type
Media types are defined in section 3.7. An example of the field is

Content-Type: text/html; charset=ISO-8859-4

Comment by timuralp [ 18/Mar/15 ]

At the same time, if one looks at the media types, the following stands out: "Use of non-registered media types is discouraged."

An empty string could be called an "unregistered" media type, which is not explicitly prohibited, but only "discouraged". Could you point to where it is explicitly required to be set?

Comment by Jakub Podlesak [ 18/Mar/15 ]

What about this one:

media-type = type "/" subtype *( ";" parameter )
type = token
subtype = token

How does it match your "emptie"? Where is the slash character there? Any more ideas?

Comment by timuralp [ 19/Mar/15 ]

This came up as the python-swiftclient submits such requests (the command line tool the openstack project ships). I verified that such requests do succeed against Rackspace CloudFiles (a swift provider) and docker-swift (docker container with swift). I filed a bug against the openstack project about this.

Anyway, thanks for looking into this. I'm not sure what warranted the response above, however.





[JERSEY-2822] Impossible to send 204 (No-Content) with Content-Length and Content-Type set Created: 12/Mar/15  Updated: 18/Mar/15  Resolved: 18/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: timuralp Assignee: Jakub Podlesak
Resolution: Works as designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Linux



 Description   

I am attempting to implement an OpenStack Swift server. While implementing the API for the Containers (http://developer.openstack.org/api-ref-objectstorage-v1.html) I found that it is impossible to implement HEAD according to that specification with Jersey. Specifically, when handling a HEAD request for an object, I cannot send back a No-Content response with Content-Length and Content-Type set to the object's size and type. When I explicitly set the headers, they are stripped off.

What is the reason that headers that are set explicitly by calling <ResponseBuilder>.header() removed in subsequent response processing?



 Comments   
Comment by Michael Osipov [ 13/Mar/15 ]

This is partially by design in Jersey. Read: http://stackoverflow.com/a/24574405/696632

Comment by Jakub Podlesak [ 18/Mar/15 ]

Please see the stack-overflow discussion linked above for possible solution (container response filter).





[JERSEY-2821] Inconsistent getParameters and toString in AcceptableMediaType Created: 12/Mar/15  Updated: 23/Mar/15  Resolved: 23/Mar/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Thomas_Schulz Assignee: Jakub Podlesak
Resolution: Works as designed Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When an org.glassfish.jersey.message.internal.AcceptableMediaType is created via the following constructor:

public AcceptableMediaType(String type, String subtype) {             
    super(type, subtype); // no need to add default quality parameter.
    q = Quality.DEFAULT;                                              
}

, the toString-Method will return something like this:

{application/hal+json, q=1000}

, whereas getParameters (which is not overridden), whill return an empty array.
This inconsistency causes problems even in code in the same package, because the method stripQualityParams in org.glassfish.jersey.message.internal.MediaTypes will return the original AcceptableMediaType intance instead of creating a new MediaType instance without quality parameters.

It should be sufficient to change the aforementioned constructor to look like this:

public AcceptableMediaType(String type, String subtype) {             
    super(type, subtype, Quality.enhanceWithQualityParameter(parameters, Quality.QUALITY_PARAMETER_NAME, Quality.DEFAULT));
    q = Quality.DEFAULT;                                              
}

Disclaimer: I did not test that; I just reverted back to Jersey 2.15.

As a side note: I don't understand why q would be an int when according to RFC 7231 the quality value is supposed to be "a real number in the range 0 through 1". Accordingly I would expect Quality.MAXIMUM (and therefore Quality.DEFAULT) to have the value 1.0 instead of 1000.



 Comments   
Comment by Jakub Podlesak [ 23/Mar/15 ]

Thomas, could you please elaborate a bit? Why should MediaTypes.stripQualityParams create any new instance?

You are reporting a bug against internal Jersey classes without providing a reproducible test that would show
Jersey breaks any valid use case.

On the "why 1000" side note: Jersey uses this only internally.

Comment by Jakub Podlesak [ 23/Mar/15 ]

I am resolving this as "works as designed". Please see my comments above for some more details.

Fee free to re-open based on a concrete test case proving the internal Jersey code wrong.





[JERSEY-2820] Cannot inject HttpServletRequest in ContainerRequestFilter via @Context when running unit test extends JerseyTest in Jersey 2.0 Jetty Test Framework Container Created: 11/Mar/15  Updated: 19/Mar/15

Status: Open
Project: jersey
Component/s: test-framework
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: bglmmz Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

WINDOWS 7 64bit
JDK 7
jersey 2.16
spring 3.2.3
aspectj 1.8.0



 Description   

This issue is like https://java.net/jira/browse/JERSEY-2462,
the different is that it happens in Jersey UnitTest.

public class RemoteFilter implements ContainerRequestFilter {
    //auto inject HttpServletRequest
    @Context
    private HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext ctx) throws IOException {
        //request is null when running unit test extends JersyTest
        String remoteAddr = request.getRemoteAddr();
    }
}


 Comments   
Comment by Adam Lindenthal [ 11/Mar/15 ]

Hi Bglmmz,

could you please specify what container you are using and how are you configuring it?
I'm sure you know that, but you have to really be on a servlet environment in order to have Servlet related objects injected and JerseyTest uses GrizzlyHttpContainer (non-servlet) as its default.
Would you be able to provide the full runable reproducing testcase?

Thank you,
Adam

Comment by bglmmz [ 12/Mar/15 ]

<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>$

{jersey.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}

</version>
<scope>test</scope>
</dependency>

Comment by bglmmz [ 12/Mar/15 ]

the same issue if use jetty..
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<version>$

{jersey.version}

</version>
</dependency

Comment by Jakub Podlesak [ 19/Mar/15 ]

Grizzly HTP container is not based on Servlet, so it does not make any sense to ask the HttpServletRequest injected there.

Regarding the Jetty container, this feature is indeed missing.

As a workaround, you should be able to use the external test container (https://jersey.java.net/documentation/latest/test-framework.html#d0e17242)
to test your use case.





[JERSEY-2819] ServletContainer hangs on startup - infinite loop Created: 10/Mar/15  Updated: 11/Mar/15

Status: Open
Project: jersey
Component/s: core, osgi
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: vdjurovic Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Jetty 9.2.9.v20150224 running inside Apache Felix 4.4.2 OSGI container


Attachments: Zip Archive jersey-startup-freeze.zip    

 Description   

I'm trying to deploy simple web app to Jetty runnin inside OSGI container. What I am experiencing in that ServletContainer hangs on startup and never loads.
My web.xml:

 <servlet>
        <servlet-name>Jersey Web 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>com.vektorsoft.demux.web.resource</param-value>
        </init-param>
        
        <load-on-startup>10</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webresources/*</url-pattern>
    </servlet-mapping>

I managed to isolate infinite loop happenning in org.glassfish.jersey.server.ResourceConfig, lines 887-905. The reason is that _org.glassfish.server.internal.scanning.BundleSchemeResourceFinderFactory.next() method does not advance iteration, but always returns the same item. Advance happens only in open() method in that class.

So, when you specify package which contains subpacakges as jersey.config.server.provider.packages property, infinite loop will happen. The reason is tha package name is never accepted in ResourceConfig:890, so open() is never called in _BundleSchemeResourceFInderFactory and iteration does not advance, returning the same object over and voer again.

If you specify package that does not contain subpackages as jersey.config.server.provider.packages, everything works fine.



 Comments   
Comment by Adam Lindenthal [ 11/Mar/15 ]

Hi Vdjurovic,

thanks for reporting and for investigation you've made.

Could you please make it easier for us to reproduce by providing a minimal test case (the configuration you've provided + e.g. one resource) and most importantly some steps to do? We do not run jetty inside osgi on our tests. Is this achievable within maven using some plugins (pax exam, etc)? It would be also useful for creating some integration test after its fixed.

It would be very helpful if you could write down some steps like "start the felix shell", "write [whatever command] to load [such and such] bundle", etc.

Many thanks,
Adam

Comment by Adam Lindenthal [ 11/Mar/15 ]

In the meantime, I will move this issue to backlog for further planning.

Comment by vdjurovic [ 11/Mar/15 ]

Hi, Adam

I've just started working on this project yesterday (and hit this bump immediatelly ), so I can not really provide streamlined test case. I have created Maven project with 3 modules:

  • server - Jetty server running inside Apace Felix
  • simple-bundle - OSGI bundle containing JAX-RS resources
  • jersey-startup-freeze-war - web application which starts ServletContainer

I can't attach files, so here is the download link:http://vektorsoft.com/files/jersey-startup-freeze.zip

How to run:

  1. extract the contents and change to jersey-startup-freeze dir
  2. run mvn install
  3. cd to server dir
  4. run
    java -Djetty.home=jettyhome/ -jar bin/felix.jar
  5. web app should start few seconds after server startup and freeze immediatelly. It also causes entire server to freeze
  6. in web.xml, if you change jersey.config.server.provider.packages value to package without subpackages, app starts normally

To run server in debug mode, use this command:

ava -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=<port_number> -Djetty.home=jettyhome/ -jar bin/felix.jar

Then attach debugger. If you set breakpoint to the line I've specified in bug descritpion, you can see infinite loop is created.

I'm not sure about running integration tests, Pax Exam is probably good choice. I don't have much free time right now, but I can try to set something up later when I'm not too busy.
Let me know if you need any more info from me.

Comment by Adam Lindenthal [ 11/Mar/15 ]

Thanks a lot, I guess that will be very helpful for reproducing. I've attached your zip here for the one of us who will be working on it.

Regards,
Adam





[JERSEY-2818] RolesAllowedDynamicFeature can return 401 or 403 errors. Created: 10/Mar/15  Updated: 15/Apr/15  Resolved: 19/Mar/15

Status: Resolved
Project: jersey
Component/s: core, security
Affects Version/s: 2.16
Fix Version/s: 2.18

Type: Improvement Priority: Major
Reporter: krotscheck Assignee: Michal Gajdos
Resolution: Fixed Votes: 4
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Currently, the RolesAllowedRequestFilter will always return HTTP 403 Forbidden. This is accurate in all cases where the security context is aware of the principal (securityContext.getUserPrincipal() is not null), however it is not strictly accurate in the case where a user has not been authenticated. In that case, returning HTTP 401 Unauthorized is more accurate, as the user has not provided the correct credentials.

The following code should suffice, if inserted before the role check loop.

if(requestContext.getSecurityContext().getUserPrincipal() == null && rolesAllowed.length > 0)

{ throw new NotAuthorizedException(); }

 Comments   
Comment by Adam Lindenthal [ 11/Mar/15 ]

Hi krotscheck,

thanks for reporting the improvement suggestion.
I will put it to backlog, so that someone can look at it in one of the future sprints.

Regards,
Adam

Comment by brunosimioni [ 18/Mar/15 ]

Guys,

Same problem over here. Since my API with RolesAllowedDynamicFeature is returning 403 instead of 401, Actually, I'm stucked in the same step and I'm currently integrating with others systems with this API. Returning then with forbidden 403 to a non-authenticated user just makes no sense.

Would you guys priorize this issue, or do you have a release date, or even can I make the fix and make a pull request under github repositories?

Best!

Comment by brunosimioni [ 19/Mar/15 ]

Guys,

I've forked the Jersey's github repository, patched up with krotscheck's fix and made a pull request to merge with master branch. Hope you guys accept it as soon as possible, since there is a scheduled build on April.

Please check this out: https://github.com/jersey/jersey/pull/150

Comment by Michal Gajdos [ 19/Mar/15 ]

I'll deliver fix for this internally - it'd be faster.

Comment by brunosimioni [ 19/Mar/15 ]

Thanks Michal!

Would it be available at April 8th?

I'll sign out the OCA too, for future collaborations.

Thank you very much.

Comment by Michal Gajdos [ 19/Mar/15 ]

It'll be in 2.18 (April 8th is approximate but 2.18 should be out that week).

Comment by Michal Gajdos [ 19/Mar/15 ]

Merged into master branch.

Comment by brunosimioni [ 19/Mar/15 ]

Michal, I've just saw you merge. Thank you for that!

Just a question: shouldn't NotAuthorizedException preceeds the ForbiddenException? Authorization should be evaluted before Permission rights, do you agree? Because to check wether the user can or cannot access the resource, it must be known.

In my patch (thanks to krotscheck) I've checked Authorization before DenyAll condition, but in your implementation, you did the inverse.

Best

Comment by andrewzimmer [ 15/Apr/15 ]

Glad to hear that this is going to be taken care of!





[JERSEY-2817] ByteBufferInputStream has bad casts for byte reads Created: 06/Mar/15  Updated: 06/Mar/15  Resolved: 06/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Marek Potociar Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates JERSEY-2498 ByteBufferInputStream violates InputS... Reopened

 Description   

ByteBufferInputStream has bad casts for byte reads - allowing a byte of '255' to be cast to '-1' as an int - which would indicate EOF on a read. The mask will push this back to the unsigned value.

A pull request #147 exists to fix the issue.






[JERSEY-2816] Error closing message content input stream. Created: 06/Mar/15  Updated: 23/Mar/15  Resolved: 23/Mar/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.5.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: wuzesheng Assignee: Unassigned
Resolution: Incomplete Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   
javax.ws.rs.ProcessingException: Error closing message content input stream.
	at org.glassfish.jersey.message.internal.EntityInputStream.close(EntityInputStream.java:159)
	at sun.nio.cs.StreamDecoder.implClose(StreamDecoder.java:358)
	at sun.nio.cs.StreamDecoder.close(StreamDecoder.java:173)
	at java.io.InputStreamReader.close(InputStreamReader.java:182)
	at org.eclipse.persistence.internal.libraries.antlr.runtime.ANTLRReaderStream.load(ANTLRReaderStream.java:92)
	at org.eclipse.persistence.internal.libraries.antlr.runtime.ANTLRInputStream.<init>(ANTLRInputStream.java:68)
	at org.eclipse.persistence.internal.libraries.antlr.runtime.ANTLRInputStream.<init>(ANTLRInputStream.java:52)
	at org.eclipse.persistence.internal.libraries.antlr.runtime.ANTLRInputStream.<init>(ANTLRInputStream.java:48)
	at org.eclipse.persistence.internal.libraries.antlr.runtime.ANTLRInputStream.<init>(ANTLRInputStream.java:40)
	at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:105)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:972)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:425)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:375)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:705)
	at org.eclipse.persistence.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:655)
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:301)
	at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.readFrom(MOXyJsonProvider.java:580)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:239)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:211)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:785)
	at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:267)
	at org.glassfish.jersey.client.InboundJaxrsResponse$1.call(InboundJaxrsResponse.java:111)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:397)
	at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:108)
	at com.xxxxx.GalaxyFDSClient.listObjects(GalaxyFDSClient.java:334)
	at com.xxxxx.TestFDSJavaSdk.deleteOneBucket(TestFDSJavaSdk.java:172)
	at com.xxxxx.TestFDSJavaSdk.testListBuckets(TestFDSJavaSdk.java:401)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
Caused by: java.io.IOException: Stream closed.
	at java.net.PlainSocketImpl.available(PlainSocketImpl.java:452)
	at java.net.SocketInputStream.available(SocketInputStream.java:217)
	at java.io.BufferedInputStream.available(BufferedInputStream.java:381)
	at sun.net.www.MeteredStream.available(MeteredStream.java:152)
	at sun.net.www.http.KeepAliveStream.close(KeepAliveStream.java:72)
	at java.io.FilterInputStream.close(FilterInputStream.java:155)
	at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.close(HttpURLConnection.java:2739)
	at org.glassfish.jersey.client.HttpUrlConnector$1.close(HttpUrlConnector.java:151)
	at org.glassfish.jersey.message.internal.EntityInputStream.close(EntityInputStream.java:157)
	... 41 more


 Comments   
Comment by Adam Lindenthal [ 06/Mar/15 ]

Hi wuzesheng,

could you please be a bit more specific on circumstances when this occurs? Is it always repeatable/reproducible? Ideally I would ask you to extract some minimal reproducing test case (e.g. one resource, custom providers if relevant + client code that shows the issue).

Also, which version are you using?

Regards,
Adam

Comment by wuzesheng [ 06/Mar/15 ]

Hi Adam,

Thanks for your replying.
I'm using Jersey 2.5.1, this case was occurred occasionally in my environment, sometime for GET, sometime for DELETE, etc.
I haven't used any custom providers.

Comment by Adam Lindenthal [ 06/Mar/15 ]

Thanks, I've filled in the "Affected versions" field.
Honestly, I am not sure how to solve this, unless there are some reasonable steps to reproduce.
Would you be able to provide a test case, that at lease "sometimes" shows this issue, along with the instructions how to reproduce? I don't mind sending a request 20 times before the error occurs...

Thanks,
Adam

Comment by wuzesheng [ 06/Mar/15 ]

OK, I'll try to construct a test case and will post it here later.

Comment by Adam Lindenthal [ 06/Mar/15 ]

Thanks, that will be very helpful.

Comment by wuzesheng [ 11/Mar/15 ]

Sorry for later response.
I tried to construct such a case, but it's not that easy.
I can offer one more message, perhaps related:
When I run the jersey application on openstack virtual machine, this exception occurs occasionally, but when I run the same application on a standalone machine, it never occurs.
Does this help?

Comment by Adam Lindenthal [ 11/Mar/15 ]

Honestly, I would love to say "yes", but it does not . But thanks for taking your time to investigate anyway.
We have to narrow it down somehow. For the start, have you tried some more recent Jersey version or is it not an option?
Are you somehow configuring the container and connector that you are using, or do you stick with defaults? Any special server side or client side configuration?

Comment by wuzesheng [ 12/Mar/15 ]

We have to narrow it down somehow. For the start, have you tried some more recent Jersey version or is it not an option?

OK, I will have a try.

Are you somehow configuring the container and connector that you are using, or do you stick with defaults? Any special server side or client side configuration?

I configured the 'jersey-grizzly-connector' connector, and the container is default.

Comment by Jakub Podlesak [ 23/Mar/15 ]

Even if the reproducible test case would fail only in say 1 out of 20 cases it would help us to diagnose the issue.
I am going to resolve this as invalid, but please ask for re-opening once you have the reproducer ready.
Thanks for understanding.

Comment by Jakub Podlesak [ 23/Mar/15 ]

Please see above for details.
Once a test case is provided, we are going to re-open this.





[JERSEY-2815] Add support for Optional from Java 8 into Jersey Created: 04/Mar/15  Updated: 04/Mar/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.16
Fix Version/s: backlog

Type: New Feature Priority: Major
Reporter: Michal Gajdos Assignee: Michal Gajdos
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

We're currently able to support some of the types from Java 8 in Jersey (extension module). Create infrastructure for this extension module and add support for Optional (entity, param).






[JERSEY-2814] Imporve JDK container to take custom SSLContext Created: 03/Mar/15  Updated: 05/Mar/15  Resolved: 05/Mar/15

Status: Resolved
Project: jersey
Component/s: containers
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Improvement Priority: Major
Reporter: Adam Lindenthal Assignee: Adam Lindenthal
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Originally reported internally by Luk Ho.

The JDK Container currently does not allow user to set custom SSLContext, like Grizzly2 and Simple severs do.
E.g. GrizzlyHttpServerFactory.createHttpServer(..., SSLEngineConfigurator)
Please improve JDK Container so that all the containers supported by Jersey provides the same functionality.



 Comments   
Comment by Adam Lindenthal [ 05/Mar/15 ]

Fixed in 2.17.

JdkHttpServerFactory was enhanced with some new overloaded createHttpServer methods that accept SSLContext or HttpsConfigurator.





[JERSEY-2813] The RxObservableInvoker swallows errors such as 404 NotFound Created: 03/Mar/15  Updated: 09/Mar/15  Resolved: 09/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: grro Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The RxObservableInvoker (jersey-rx-client-rxjava-2.16) swallows errors such as 404 NotFound. See example below

RxClient<RxObservableInvoker> restClient = Rx.newClient(RxObservableInvoker.class);       

restClient.target("http://localhost:8089/DoesNotExitAndReturnsA404Error")
          .request()                 
          .rx()
          .get(byte[].class)
          .onErrorReturn(error -> new byte[] { 12, 34, 45, 65 })
          .forEach(data -> System.out.println("data size " + data.length));
	     
 > data size 0

In contrast the RxCompletionStageInvoker (jersey-rx-client-java8-2.16 ) will not ignore the error

RxClient<RxCompletionStageInvoker> restClientCompletable = Rx.newClient(RxCompletionStageInvoker.class);

restClientCompletable.target("http://localhost:8089/DoesNotExitAndReturnsA404Error")
                     .request()                 
                     .rx()
                     .get(byte[].class)                              
                     .exceptionally(error -> new byte[] { 12, 34, 45, 65 })
                     .whenComplete((data, error) -> System.out.println("data size " + data.length));
        
>  data size 4


 Comments   
Comment by grro [ 04/Mar/15 ]

the corresponding HTTP response of the example is

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Wed, 04 Mar 2015 04:15:43 GMT




[JERSEY-2812] Thread not released when Jersey configured as a filter Created: 03/Mar/15  Updated: 01/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: fpoliquin Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: 1221, containers
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Zip Archive jersey2812-master.zip    

 Description   

Using the following code:

@GET
@Path("/wait")
public void waitForRessource(@Suspended final AsyncResponse asyncResponse) {
    ...
}

The following configuration works as expected:

    <servlet>
        <servlet-name>jersey</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>xxx</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </servlet>

But if I configure Jersey using the following configuration:

    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>xxx</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.servlet.filter.forwardOn404</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

The thread executing the request is never returned to the container. The thread is stuck with this stack:

Daemon Thread [http-bio-60000-exec-10] (Suspended)
owns: Object (id=9746)
owns: SocketWrapper (id=9731)
Unsafe.park(boolean, long) line: not available [native method]
LockSupport.park(Object) line: not available
AbstractFuture$Sync(AbstractQueuedSynchronizer).parkAndCheckInterrupt() line: not available
AbstractFuture$Sync(AbstractQueuedSynchronizer).doAcquireSharedInterruptibly(int) line: not available
AbstractFuture$Sync(AbstractQueuedSynchronizer).acquireSharedInterruptibly(int) line: not available
AbstractFuture$Sync.get() line: 292
SettableFuture(AbstractFuture).get() line: 116
ResponseWriter.getResponseContext() line: 273
ResponseWriter.getResponseStatus() line: 268
WebComponent$6.get() line: 404
WebComponent$6.get() line: 401
Values$LazyValueImpl.get() line: 340
ServletContainer.doFilter(HttpServletRequest, HttpServletResponse, FilterChain, String, String, String) line: 534
ServletContainer.doFilter(HttpServletRequest, HttpServletResponse, FilterChain) line: 482
ServletContainer.doFilter(ServletRequest, ServletResponse, FilterChain) line: 419
ApplicationFilterChain.internalDoFilter(ServletRequest, ServletResponse) line: 241
ApplicationFilterChain.doFilter(ServletRequest, ServletResponse) line: 208
FiltreContexteApplicationWeb.doFilter(ServletRequest, ServletResponse, FilterChain) line: 54
ApplicationFilterChain.internalDoFilter(ServletRequest, ServletResponse) line: 241
ApplicationFilterChain.doFilter(ServletRequest, ServletResponse) line: 208
RestRecorderFilter.doFilter(ServletRequest, ServletResponse, FilterChain) line: 83
ApplicationFilterChain.internalDoFilter(ServletRequest, ServletResponse) line: 241
ApplicationFilterChain.doFilter(ServletRequest, ServletResponse) line: 208
StandardWrapperValve.invoke(Request, Response) line: 220
StandardContextValve.invoke(Request, Response) line: 122
StandardHostValve.invoke(Request, Response) line: 170
ErrorReportValve.invoke(Request, Response) line: 103
AccessLogValve.invoke(Request, Response) line: 950
StandardEngineValve.invoke(Request, Response) line: 116
CoyoteAdapter.service(Request, Response) line: 421
Http11Processor(AbstractHttp11Processor).process(SocketWrapper<S>) line: 1070
Http11Protocol$Http11ConnectionHandler(AbstractProtocol$AbstractConnectionHandler).process(SocketWrapper<S>, SocketStatus) line: 611
JIoEndpoint$SocketProcessor.run() line: 316
ThreadPoolExecutor(ThreadPoolExecutor).runWorker(ThreadPoolExecutor$Worker) line: not available
ThreadPoolExecutor$Worker.run() line: not available
TaskThread$WrappingRunnable.run() line: 61
TaskThread(Thread).run() line: not available

This behavior makes the @Suspended annotation basically useless as the whole point of using it is to release the thread.

I'm using Tomcat 7.0.56 with the native Windows binaries.



 Comments   
Comment by Adam Lindenthal [ 03/Mar/15 ]

Hi fpoliquin,

thanks for reporting this issue.
Just to rule out other influences, have you tried to reproduce this on some other container (Jetty, Glassfish, etc)?

The thing is, on the first quick look into the code, the destroy() method in the ServletContainer comes from both servlet and filter classes and should be invoked in both cases.

Could you share a complete minimal example (ideally maven based servlet app with a test narrowed down as much as possible).

Many thanks,
Adam

Comment by fpoliquin [ 03/Mar/15 ]

I did a test case but I don't have the rights to upload the file in JIRA. Is there another place where I can put it?

Comment by Adam Lindenthal [ 03/Mar/15 ]

Hi, that's great.

Unfortunately, we cannot assign you the permission in JIRA, so we usually use other ways to do that. If you have a github account, please upload it there and paste a link here, if not, feel free to send me a zip with soruces via email. In both cases, I will attach it here for you, if you don't mind.

Regards,
Adam

Comment by fpoliquin [ 04/Mar/15 ]

I uploaded my test case to this URL: https://github.com/fpoliquin/jersey2812

Basically, there are 4 URLs:
1. /jersey2812/test/wait This uses the filter configuration and triggers an AsyncResponse
2. /jersey2812/test/broadcast This is used to free all waiting connections
3. /jersey2812/servlet/test/wait Same as above but with a servlet configuration
4. /jersey2812/servlet/test/broadcast Same as above but with a servlet configuration

If you look in the console, you will see that the first URL never releases the thread whereas the third one does it correctly.

Thanks.

Comment by Adam Lindenthal [ 04/Mar/15 ]

Great, thanks for the test case, I have just attached it here.

Comment by Adam Lindenthal [ 05/Mar/15 ]

Hi fpoliquin,

I am moving the issue to backlog, so that we can plan the work on it into one of the future sprints.

Regards,
Adam





[JERSEY-2811] Minor grammatical issue on home page Created: 02/Mar/15  Updated: 02/Mar/15  Resolved: 02/Mar/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Trivial
Reporter: mcandre Assignee: Jakub Podlesak
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

"Jersey provides it’s own API" should be

"Jersey provides its own API"






[JERSEY-2810] InMemory JerseyTest ignore contextPath parameter Created: 02/Mar/15  Updated: 06/Mar/15

Status: Open
Project: jersey
Component/s: test-framework
Affects Version/s: 1.18.1
Fix Version/s: 1.x-backlog

Type: Bug Priority: Major
Reporter: nfalco79 Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to JERSEY-2809 ClientConfig is ignored by InMemoryTe... Open

 Description   

The context path configured in the WebAppDescriptor.Builder() is ignored by test framework.
With a configured path "test" I expect that for a resource @Path("resources") annotated at class level, requests that matches resource methods start with monospaced

{schema}

://

{host}

:

{port}

/test/resources/...monospaced



 Comments   
Comment by nfalco79 [ 02/Mar/15 ]

:\ issue can not be edited.
The URLs expected are in form:
http://<host>:<port>/test/resources/...

Follow a JUnit

ContextPathTest.java
public class ContextPathTest extends JerseyTest {

	@Path("api/resources")
	public static class ContextPathResource {
		@POST
		@Consumes(MediaType.APPLICATION_JSON)
		@Path("")
		public Response create(Resource resource) {
			return Response.created(null).build();
		}
	}

	@XmlRootElement
	public static class Resource {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	@Override
	protected AppDescriptor configure() {
		return new WebAppDescriptor.Builder(this.getClass().getPackage().getName())
				.contextPath("test")
				.build();
	}

	@Test
	public void context_path() {
		Resource res = new Resource();
		res.setName("my resource");

		URI uri = UriBuilder.fromUri(getBaseURI()).path("test").path(ContextPathResource.class, "create").build();

		ClientResponse response = client()
				.resource(uri)
				.post(ClientResponse.class, res);

		Assert.assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
	}
}
Comment by Michal Gajdos [ 02/Mar/15 ]

I guess the expected URL should be rather `http://<host>:<port>/test/api/resources/...` but I see your point. I'll check whether the problem is in 2.x as well and if this is the case then the problem would be fixed there (and hopefully migrated into 1.x).

Comment by nfalco79 [ 02/Mar/15 ]

The expected URL refers to the issue context description.
The JUnit was writing after the issue opened and an "api" in the root resource path was introduced.
I'm sorry for the mismatch.

Comment by nfalco79 [ 03/Mar/15 ]

I think the context path should be part of JerseyTest.getBaseURI(). I would expect the same in the ContextRequest.getBaseUri() received in my ContainerRequestFilter test implementation as happen in a real call.

ContextPathTest.java
public class ContextPathTest extends JerseyTest {

	@Path("api/resources")
	public static class ContextPathResource {
		@GET
		@Consumes(MediaType.APPLICATION_JSON)
		@Path("")
		public Response get() {
			return Response.ok().build();
		}
	}

	public static class FilterFactory implements ResourceFilterFactory {
		class InternalFilter implements ResourceFilter, ContainerRequestFilter {

			@Override
			public ContainerRequestFilter getRequestFilter() {
				return this;
			}

			@Override
			public ContainerResponseFilter getResponseFilter() {
				return null;
			}

			@Override
			public ContainerRequest filter(ContainerRequest request) {
				Assert.assertEquals("/test", request.getBaseUri().getPath());
				return request;
			}

		}

		@Override
		public List<com.sun.jersey.spi.container.ResourceFilter> create(AbstractMethod am) {
			return Collections.<ResourceFilter> singletonList(new InternalFilter());
		}

	}

	@Override
	protected AppDescriptor configure() {
		return new WebAppDescriptor.Builder(ContextPathResource.class.getPackage().getName())
			.contextPath("test")
			.initParam("com.sun.jersey.spi.container.ResourceFilters", FilterFactory.class.getName())
			.build();
	}

	@Test
	public void context_path_resource_filter() {
		URI uri = UriBuilder.fromUri(getBaseURI())/*.path("test")*/.path(ContextPathResource.class).build();

		ClientResponse response = client()
				.resource(uri)
				.type(MediaType.APPLICATION_JSON_TYPE)
				.get(ClientResponse.class);

		Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
	}
}
Comment by Adam Lindenthal [ 05/Mar/15 ]

Hi nfalco,

moving this issue to backlog, so that we can plan the work on it for one of the future sprints).

Regards,
Adam





[JERSEY-2809] ClientConfig is ignored by InMemoryTestContainerFactory Created: 02/Mar/15  Updated: 06/Mar/15

Status: Open
Project: jersey
Component/s: test-framework
Affects Version/s: 1.18.1
Fix Version/s: 1.x-backlog

Type: Bug Priority: Major
Reporter: nfalco79 Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to JERSEY-2810 InMemory JerseyTest ignore contextPat... Open

 Description   

Using InMemory jersey test framework the ClientConfig passed in configure method to the

WebAppDescriptor.Builder().clientConfig(cc)

is not used to configure the client that

JerseyTest.client()

returns.
I'm not be able to configure POJO feature so an exception was thrown by client.

com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java class com.example.MyBean, and Java type class com.example.MyBean, and MIME media type application/json was not found


 Comments   
Comment by Adam Lindenthal [ 06/Mar/15 ]

Hi, thanks for reporting.
I will put this to backlog,right next to the other issue you created
I linked them together, even though technically it is a different problem, but in the same code, so I guess those two could be fixed at once.

Regards,
Adam





[JERSEY-2808] Nested objected not marshaled when enabled EntityFilteringFeature Created: 27/Feb/15  Updated: 10/Mar/15

Status: Reopened
Project: jersey
Component/s: extensions, media
Affects Version/s: 2.10, 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: rkorn Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Glassfish 4.1, Jersey 2.10.4 (and 2.16.0)


Attachments: Zip Archive 2808-entity-filtering.zip     Zip Archive jerseyEntityFilteringNestingIssue-master.zip    

 Description   

I guest, I've hit a bug with my question on StackOverflow - http://stackoverflow.com/questions/28762909/marshall-nested-objects-with-jersey-using-entityfilter-feature

I have deep nested objects in my domain model (> Level 2) and after enabling EntityFilteringFeature the nested objects dont get marshaled in my json reponse (no matter if using Jackson or Moxy).
Extending the examples at https://github.com/jersey/jersey/tree/master/examples/entity-filtering to contain some deep nested objects should show the issue.



 Comments   
Comment by Adam Lindenthal [ 09/Mar/15 ]

Hi rkorn,

I tried to adjust the entity filtering example as you suggested, but do not see any unexpected behaviour.
Everything seems to be correctly marshalled and sent to the output as it should be.

Please find the attached file which contains the changed and added files to the mentioned entity filtering example and try the /users and /users?detailed=true URIs.

I will close the issue as invalid for now. If you can adjust the example, so that it reproduces the issue, please feel free to ask for reopening. In that case a standalone minimal reproducer test case would be very appreciated.

Regards,
Adam

Comment by PJC23 [ 10/Mar/15 ]

Hello I am actually experiencing this same issue with my domain model. I have edited the example to show the issue, as it is it has entity filtering disabled and will nest objects 4 levels deep. Once you uncomment the feature and turn it on you will lose the last child and the json will only be marshaled for 3 of the 4 levels. It does not appear that I have rights to add an attachment to this issue, if you give me rights I will attach the file.

Comment by Adam Lindenthal [ 10/Mar/15 ]

Hi, thanks for providing an additional info.
Unfortunately I cannot assign you the upload permission, that's a global java.net jira set-up out of our scope.
Thera are basically two ways - send it to me via email or put on github and paste a link.

Thanks,
Adam

Comment by PJC23 [ 10/Mar/15 ]

Here is the link to the modified example on GitHub, https://github.com/pjcahill/jerseyEntityFilteringNestingIssue

Comment by Adam Lindenthal [ 10/Mar/15 ]

Thanks, attached as jerseyEntityFilteringNestingIssue-master.zip. I will delete my originally attached file, so that it does not confuse anybody.
Reopening the issue and moving to backlog, so that work on it can be planned into some of the future sprints.

Regards,
Adam





[JERSEY-2807] Glassfish / Jersey throws NPE on startup of versioned app Created: 26/Feb/15  Updated: 27/Feb/15  Resolved: 27/Feb/15

Status: Resolved
Project: jersey
Component/s: containers
Affects Version/s: 2.10
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: lprimak Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

GlassFish


Issue Links:
Duplicate
duplicates JERSEY-2626 Glassfish / Jersey throws NPE on star... Open
Tags: version

 Description   

Any GlassFish versioned applications fail on startup.

Here is the original (and seems-to-have forgotten) JIRA issue

https://java.net/jira/browse/JERSEY-2626



 Comments   
Comment by Adam Lindenthal [ 27/Feb/15 ]

Hi Iprimak,

the other issue you opened is still in backlog. Backlog does not mean the issue is closed and won't be revisited, basically every issue ends up there for some time. It is a pool from where we plan the future work based on various priorities.
As far as I understand, this is a 100% duplicate of the other issue.

If you want to remind or ask status, please use the original one.
This one is going to be closed now.

Regards,
Adam





[JERSEY-2806] Jackson serialization exception is sent in response Created: 26/Feb/15  Updated: 02/Mar/15  Resolved: 02/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: jstrom Assignee: Michal Gajdos
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I have a WriterInterceptor which wraps all my JSON responses in a "base response container". During development of this feature I had an issue with Jackson throwing a JsonMappingException. For some reason, this was written to the output stream.

Feb 26, 2015 9:39:20 AM org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating InMemoryTestContainer configured at the base URI /api/
Feb 26, 2015 9:39:20 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Sending client request on thread main
1 > GET /api/test/jsonGenericList

Feb 26, 2015 9:39:20 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * Client response received on thread main
2 < 400
2 < Content-Length: 208
2 < Content-Type: text/plain
Incompatible types: declared root type ([collection type; class java.util.List, contains [simple type, class com.example.jersey.test.api.TestResource$Pojo]]) vs com.example.jersey.server.api.ApiResponseRoot

Similar response was observed in regular Jersey container.

The actual exception was due to my resource method returning a value which used generics, and my interceptor did not call ctx.setGenericType(), which caused the above exception. Note that this is not what this issue is about.

The issue is rather that the error goes out to the client, and with status 400 instead of 500. In this case, it doesn't tell too much, but in other cases the information leakage may be worse. IMO a 500 with empty response, and the exception logged, would be more appropriate.

This particular error is thrown in com.fasterxml.jackson.databind.SerializerProvider.java. While googling the error, I noticed similar problems in older Jersey versions: JERSEY-2325. However, here it seems to be a stack trace and not sent as response?

I do not have a complete test case, but here are the important parts:

Response interceptor
@Priority(JerseyPriorities.POST_ENTITY_CODER)
public class ApiResponseInterceptor implements WriterInterceptor {
	@Override
	public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {

		MediaType mt = ctx.getMediaType();
		if(mt.equals(MediaType.APPLICATION_JSON_TYPE)) {
			Object entity = ctx.getEntity();
			ApiResponseRoot root = new ApiResponseRoot(entity);
			ctx.setEntity(root);
			// uncomment this removes the "exception"
			//ctx.setGenericType(ApiResponseRoot.class);
		}
		ctx.proceed();
	}
}
Simplified response wrapper
public final class ApiResponseRoot {
	@JsonInclude(value = JsonInclude.Include.NON_NULL)
	public final Object result;
	public ApiResponseRoot(Object result) {
		this.result = result;
	}
}
Resource which returns a Generics-type
@Path("test")
public class TestResource {
	public static class Pojo {
		public long id = 1;
		public String name = "Test";
	}

	@GET
	@Path("jsonGenericList")
	@Produces("application/json")
	public List<Pojo> jsonGenericList(){
		return Arrays.asList(new Pojo(), new Pojo());
	}
}


 Comments   
Comment by jstrom [ 26/Feb/15 ]

The JacksonFeature installs these:

            // add the default Jackson exception mappers
            context.register(JsonParseExceptionMapper.class);
            context.register(JsonMappingExceptionMapper.class);

Those are the ones responsible for the rendered exception.

Based on their javadocs, I would say they are more made for handling JSON data coming on the request-side, rather than response:

Implementation of ExceptionMapper to send down a "400 Bad Request" in the event unparsable JSON is received.

It makes sense when incoming JSON cannot be mapped, but when outgoing JSON fails to render, I would say it's 500 Internal Server Error, rather than 400 Bad request.

Comment by Michal Gajdos [ 02/Mar/15 ]

Interesting problem and I agree it should be 500. However I don't think this is a problem in Jersey (or any other JAX-RS implementation for that matter). I think this should be fixed in Jackson (so all JAX-RS implementations can profit from that). And the fix in Jackson would require to update the JsonMappingException so that the mapper can definitely decide whether the response should be 400 or 500. Now even if we decided to not register that handler and write our own for JsonMappingException we couldn't do it because of the fact that the exception is not specific enough about the response we should throw.

Comment by Michal Gajdos [ 02/Mar/15 ]

I am going to close this issue (won't fix) but feel free to comment (I'll watch it) or reopen it if you still think it's a problem in Jersey.

Comment by Michal Gajdos [ 02/Mar/15 ]

There is a workaround. If you don't want those mappers don't register JacksonFeature from Jersey but register JacksonJaxbJsonProvider from Jackson directly.





[JERSEY-2805] Allow JerseyTest to create client with non-default ClientBuilder Created: 26/Feb/15  Updated: 18/Mar/15  Resolved: 18/Mar/15

Status: Resolved
Project: jersey
Component/s: test-framework
Affects Version/s: None
Fix Version/s: 2.18

Type: Improvement Priority: Major
Reporter: raybirk Assignee: Jakub Podlesak
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Currently, private Client getClient(ClientConfig) always use the default ClientBuilder to create new client. Although we get some flexibility by passing in a clientConfig, not everything can be done through it. For example, it is easier to use HTTPS by using a ClientBuilder with its SslContext customized. Therefore, it would be great to have a way to specify a ClientBuilder to use.



 Comments   
Comment by Adam Lindenthal [ 05/Mar/15 ]

Hi Raybirk,

so if I understand it correctly, all you basically need is the getClient(ClientConfig) method to be proctected, so that you can extend JerseyTest, make your own test base using your customized ClientBuilder?

But could you please describe the use case a bit more? Do you need to create new clients from your custom builder?
Couldn't you just create one configured client and use multiple {{WebTarget}}s of it?

Regards,
Adam

Comment by raybirk [ 05/Mar/15 ]

Hi Adam,

Yes, making getClient(ClientConfig) protected would work. My use case is to test against a server with HTTPS with external container wrapper. I would do this to get the client:

client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(hostnameVerifier).build();

I think we cannot change WebTarget to use HTTPS but I may be wrong.

Thanks,
RayBirk

Comment by Adam Lindenthal [ 06/Mar/15 ]

Hi Ray,
thanks for clarification.
Sure, you are right, that you cannot define ssl context on a WebTarget instance. But if you have the client defined as in your previous comment, does something prevent you from calling client.target() repeatedly (for more requests)? If you have configured the ClientBuilder, you should get the Client and all the targets configured correctly for https. Or am I missing some part of your use case that I didn't consider?
Sorry for asking so much, but I just want to be sure there is a real need that would justify changing the access level to methods that have been private for quite a while.

Regards,
Adam

Comment by raybirk [ 06/Mar/15 ]

Hi Adam,

It seems to be fine to call client.target() repeatedly, as long as the SSL context is still valid.

Can you elaborate on configuring ClientBuilder? A simple example would be appreciated.

Thanks,
RayBirk

Comment by Jakub Podlesak [ 17/Mar/15 ]

Agreed. Both setter and getter should be available for overriding. Unfortunately, I do not see any reasonable workaround for your use-case at the moment.

Comment by raybirk [ 18/Mar/15 ]

That's okay. I hope some others would benefit from the change.

Comment by Jakub Podlesak [ 18/Mar/15 ]

Fixed in the master branch. Should be available in 2.18 snapshot soonish.





[JERSEY-2804] Deadlock in Apache HTTP client for basic non-preemptive authentication Created: 25/Feb/15  Updated: 24/Mar/15

Status: Open
Project: jersey
Component/s: connectors, core
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: mario.casola Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Linux ubuntu 13.10, tomcat 7.0.57, jdk 1.7.0_71 64 bit


Attachments: Zip Archive jersey-non-preemptive-auth.zip    

 Description   

I wanna share my experience about an issue that I encountered. The scenario is the following:

1. jersey client
2. http client connection manager
3. apache connection provider
4. basic non-preemptive authentication

the problem was that in some cases the connection was not released like expected, like the log below shows

2015-02-25 19:26:06.488 DEBUG 13230 --- [nio-8181-exec-9] h.i.c.PoolingHttpClientConnectionManager : Connection released: [id: 0][route: {}->http://localhost:8080][total kept alive: 1; route allocated: 1 of 10; total allocated: 1 of 10]
  • Example that works in both cases, successful http code or not
rootTarget.queryParam("sort", sort + "," + dir)
	.queryParam("size" + Integer.MAX_VALUE)
	.request(MediaType.APPLICATION_JSON_TYPE).get(String.class);
  • Example that works only if the request is unsuccessful
return rootTarget
	.request(MediaType.WILDCARD_TYPE)
	.post(Entity.entity(myobject, MediaType.APPLICATION_JSON_TYPE),
			MyCustomClass.class);
  • Example that doesn't work at all
Response r = null;
try {
	r = idTarget.request(MediaType.WILDCARD_TYPE)
			.put(Entity.entity(myobject, MediaType.APPLICATION_JSON_TYPE));
	if (r.getStatusInfo().getStatusCode() != Status.NO_CONTENT
			.getStatusCode()) {
		throw new InternalServerErrorException(r.getStatusInfo()
				.getReasonPhrase());
	}
} finally {
	if (r != null) {
		try {
			r.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

This last example works only if I consume the response body like string. Response.close() doesn't work.

Instead If I change the authentication to preemptive mode everything works fine.

Best regards
Mario Casola



 Comments   
Comment by Adam Lindenthal [ 11/Mar/15 ]

Hi Mario,

could you please share the code where you configure the client? Or, ideally provide a minimal reproducer testcase, e.g. buildable and runnable by maven?

Thanks a lot,
Adam

Comment by mario.casola [ 11/Mar/15 ]

Hi Adam,

at the following link you can download a maven project to test the issue

https://www.dropbox.com/s/dhgr4t5tt0j4g6q/jersey-non-preemptive-auth.zip?dl=0

Max connection per route 5

[WORKING]

$ mvn -DnonPreemptive=false -DconsumeString=true -Dexception=true test
$ mvn -DnonPreemptive=false -DconsumeString=false -Dexception=true test

2015-03-12 00:02:06.890 DEBUG 8504 --- [           main] h.i.c.PoolingHttpClientConnectionManager : Connection released: [id: 5][route: {}->http://localhost:8080][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]

$ mvn -DnonPreemptive=false -DconsumeString=false -Dexception=false test
$ mvn -DnonPreemptive=false -DconsumeString=true -Dexception=false test

2015-03-12 00:03:05.015 DEBUG 8582 --- [           main] o.a.http.impl.execchain.MainClientExec   : Connection can be kept alive indefinitely
2015-03-12 00:03:05.016 DEBUG 8582 --- [           main] h.i.c.PoolingHttpClientConnectionManager : Connection [id: 0][route: {}->http://localhost:8080] can be kept alive indefinitely
2015-03-12 00:03:05.017 DEBUG 8582 --- [           main] h.i.c.PoolingHttpClientConnectionManager : Connection released: [id: 0][route: {}->http://localhost:8080][total kept alive: 1; route allocated: 1 of 5; total allocated: 1 of 10]

[NOT WORKING]

$ mvn -DnonPreemptive=true -DconsumeString=true -Dexception=true test
$ mvn -DnonPreemptive=true -DconsumeString=false -Dexception=true test
$ mvn -DnonPreemptive=true -DconsumeString=true -Dexception=false test
$ mvn -DnonPreemptive=true -DconsumeString=false -Dexception=false test

blocked

2015-03-11 23:42:39.717 DEBUG 7710 --- [           main] h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {}->http://localhost:8080][total kept alive: 0; route allocated: 5 of 5; total allocated: 5 of 10]

At the end doesn't seems to be a question between consuming String or a custom Object. Another aspect is if you remove the response body on http return code that is not SUCCESSFUL. In that case even with non preemptive authentication it works.

I hope this helps

regards
Mario

Comment by Adam Lindenthal [ 11/Mar/15 ]

Thanks, Mario.
I've attached your example to the issue. We will look at it and decide if someone knows what's wrong or if we plan some work on for future sprints.

Adam

Comment by Jakub Podlesak [ 23/Mar/15 ]

There does not seem to be an issue with client.close(). Try to place the following to the beginning of your test method:

            Executors.newFixedThreadPool(1).submit(new Runnable(){

                @Override
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    restClient.close();
                }
            })

In the original test case, the restClient.close() was never invoked!

Comment by Jakub Podlesak [ 23/Mar/15 ]
	at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
	at org.apache.http.pool.PoolEntryFuture.await(PoolEntryFuture.java:133)
	at org.apache.http.pool.AbstractConnPool.getPoolEntryBlocking(AbstractConnPool.java:282)
	at org.apache.http.pool.AbstractConnPool.access$000(AbstractConnPool.java:64)
	at org.apache.http.pool.AbstractConnPool$2.getPoolEntry(AbstractConnPool.java:177)
	at org.apache.http.pool.AbstractConnPool$2.getPoolEntry(AbstractConnPool.java:170)
	at org.apache.http.pool.PoolEntryFuture.get(PoolEntryFuture.java:102)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:244)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:231)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:173)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
	at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:455)
	at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:246)
	at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:667)
	at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:664)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
	at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:664)
	at org.glassfish.jersey.client.authentication.HttpAuthenticationFilter.repeatRequest(HttpAuthenticationFilter.java:334)
	at org.glassfish.jersey.client.authentication.BasicAuthenticator.filterResponseAndAuthenticate(BasicAuthenticator.java:125)
	at org.glassfish.jersey.client.authentication.HttpAuthenticationFilter.filter(HttpAuthenticationFilter.java:250)
	at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:134)
	at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:123)
	at org.glassfish.jersey.process.internal.Stages.process(Stages.java:171)
	at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:251)
	at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:683)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
	at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:679)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:408)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:308)
	at jersey.test.JerseyClientTest.test(JerseyClientTest.java:96)
Comment by Jakub Podlesak [ 23/Mar/15 ]

Updated bug title to describe the real issue.
Added stack trace that captures where the deadlock happens.

Moved to backlog.

Comment by mario.casola [ 23/Mar/15 ]

Hi Jakub,

good to know that you found the real issue. I didn't call the close method on restClient (javax.ws.rs.client.Client) object because in a real webapp I never call that method. On webapp shutdown spring call the close() method for me.
The method consumeTarget.request(MediaType.APPLICATION_JSON_TYPE).get(cls) should read the entity and call the method close on Response object.

thanks
Mario

Comment by Jakub Podlesak [ 24/Mar/15 ]

Understood, it was not the client but the response which you wanted to close. Anyway, the deadlock prevents any close attempt,
even if it is placed in a finally block. We need to address the deadlock first.





[JERSEY-2803] InternalServerErrorException when using SecurityEntityFilteringFeature with JacksonFeature filtering an object with a DateTime field Created: 24/Feb/15  Updated: 25/Feb/15  Resolved: 25/Feb/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: matthewhubble Assignee: Michal Gajdos
Resolution: Duplicate Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Running tests on Mac OS X with IntelliJ IDEA Ultimate 14


Issue Links:
Duplicate
duplicates JERSEY-2784 Selectable Entity Filtering doesn't w... Open

 Description   

If you open the "entity-filtering-jersey" example project in the Jersey repository and run the tests, everything passes. However, if you add a DateTime field to the RestrictedEntity class, the Jackson tests in RestrictedResourceTest all fail (the Moxy ones still pass). It seems there is an issue serialising objects using Jackson that have DateTime fields when the SecurityEntityFilteringFeature is registered. The SecurityEntityFilteringFeature for Jackson was added for 2.16, but appears to be broken in this case.

The tests fail with this exception:
javax.ws.rs.InternalServerErrorException: HTTP 500 Request failed.

Applying this diff to the Jersey repository in GitHub (https://github.com/jersey/jersey) on the master branch commit 685713e21831d4842c0d78e8868f1ddbaad6fef9 causes the tests to fail:

diff --git a/examples/entity-filtering-security/pom.xml b/examples/entity-filtering-security/pom.xml
index ebda6cf..c55179f 100644
--- a/examples/entity-filtering-security/pom.xml
+++ b/examples/entity-filtering-security/pom.xml
@@ -47,7 +47,7 @@
     <parent>
         <groupId>org.glassfish.jersey.examples</groupId>
         <artifactId>project</artifactId>
-        <version>2.17-SNAPSHOT</version>
+        <version>2.16</version>
     </parent>
 
     <artifactId>entity-filtering-security</artifactId>
@@ -84,6 +84,11 @@
             <type>pom</type>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>joda-time</groupId>
+            <artifactId>joda-time</artifactId>
+            <version>2.7</version>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/examples/entity-filtering-security/src/main/java/org/glassfish/jersey/examples/entityfiltering/security/domain/RestrictedEntity.java b/examples/entity-filtering-security/src/main/java/org/glassfish/jersey/examples/entityfiltering/security/domain/RestrictedEntity.java
index 448bc43..1766eaf 100644
--- a/examples/entity-filtering-security/src/main/java/org/glassfish/jersey/examples/entityfiltering/security/domain/RestrictedEntity.java
+++ b/examples/entity-filtering-security/src/main/java/org/glassfish/jersey/examples/entityfiltering/security/domain/RestrictedEntity.java
@@ -40,6 +40,8 @@
 
 package org.glassfish.jersey.examples.entityfiltering.security.domain;
 
+import org.joda.time.DateTime;
+
 import javax.annotation.security.DenyAll;
 import javax.annotation.security.PermitAll;
 import javax.annotation.security.RolesAllowed;
@@ -53,6 +55,8 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement
 public class RestrictedEntity {
 
+    private DateTime fooBar;
+
     private String simpleField;
 
     private String denyAll;

Commenting out the DateTime field in RestrictedEntity will cause the tests to pass again. I'm not sure if other objects cause the issue.



 Comments   
Comment by Michal Gajdos [ 25/Feb/15 ]

This is the same issue as JERSEY-2784. Hence closing as duplicate. I should be able to fix it in Jersey 2.17.





[JERSEY-2801] Bug in org.glassfish.jersey.internal.util.ReflectionHelper Created: 21/Feb/15  Updated: 23/Feb/15  Resolved: 23/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: Anthony Ve Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

It seems there is a bug in the method getValueOfStringMethodPA. The current code is:

final Method m = c.getDeclaredMethod("valueOf", String.class);
if (!Modifier.isStatic(m.getModifiers()) && m.getReturnType() == c) {
return null;
}
return m;

but I think it should be:

final Method m = c.getDeclaredMethod("valueOf", String.class);
if (Modifier.isStatic(m.getModifiers()) && m.getReturnType() == c) {
return m;
} else {
return null;
}

because with the current code, a method "static AnyType valueOf(String value)" would be returned, even though its return type is invalid.



 Comments   
Comment by Anthony Ve [ 21/Feb/15 ]

Just for the record, it's about lines 776-780 in https://java.net/projects/jersey/sources/code/content/core-common/src/main/java/org/glassfish/jersey/internal/util/ReflectionHelper.java





[JERSEY-2800] Memory Leak when using @BeanParam within HK2 Created: 19/Feb/15  Updated: 25/Feb/15  Resolved: 25/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: nicholas.hagen Assignee: Jakub Podlesak
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Blocks
is blocked by HK2-245 BuiltActiveDescriptor should override... Closed

 Description   

There are a few similar tickets opened for this, but my investigation led me down a different path, so not sure if they are related or not. We use @BeanParam via field injection:

@Path("/test")
public class TestResource {
    @BeanParam
    protected PagingInfo pagingInfo

    ...

    public static class PagingInfo {
        @QueryParam("limit")
        private Integer limit;
		
        @QueryParam("page")
        private Integer page;
    }
}

It appears as though this instance is getting added to the "ServiceLocatorImpl.allDescriptors" field within HK2 such that after a few hours it has over 250K items (most of which are the paging info descriptors) and eventually OOM.

Digging through the code, it appears that within BeanParamValueFactoryProvider (https://github.com/jersey/jersey/blob/master/core-server/src/main/java/org/glassfish/jersey/server/internal/inject/BeanParamValueFactoryProvider.java#L112) it attempts to lookup the service for the particular BeanParam object class. That eventually calls "ServiceLocatorImpl.internalGetDescriptor" which attempts to compute the key within the "idgCache" using an "IndexedFilter". That eventually calls "ServiceLocatorImpl.getDescriptors" using that "IndexedFilter". Because it is using the "IndexedFilter" it attempts to grab the descriptor via the "descriptorsByAdvertisedContract" map using the name of the BeanParam object class as the key (line 296 of ServiceLocatorImpl). The class name is not within that map and so it returns null all the way back out to the BeanParam factory. As a result, the BeanParam factory adds the class into the service locator via https://github.com/jersey/jersey/blob/master/core-server/src/main/java/org/glassfish/jersey/server/internal/inject/BeanParamValueFactoryProvider.java#L98. The problem there is that the descriptor that gets created only ends up with a single advertised contract which is the scope per the "in(RequestScoped.class)" portion. This occurs within "ServiceLocatorImpl.addConfigurationInternal" method via its call to "getAllContracts".

What appears needs to happen is that the class name should also be set as a contract along with the scope doing one of the following:

// cal to(key) to add the type as a contract
BuilderHelper.activeLink(key).to(key).in(RequestScoped.class).build();
// or just call: descriptor.addContractType(key);

Per the JavaDocs for the activeLink, "The implementation class given will NOT automatically be added to the set of contracts of the

{@link ActiveDescriptor}

".

When I did that above in a local build it seemed to find the references properly and avoid re-adding to the map over and over thus stopping the memory leak. However, I'm not sure that is the expected fix or if there is some incompatibility between HK2 and Jersey. Looking at some of the other open BeanParam/Memory Leak tickets, there was some investigation into issues between the two.



 Comments   
Comment by Jakub Podlesak [ 24/Feb/15 ]

The above suggested fix does not seem to be sufficient. I had to add hashCode and equals method implementation to HK2's BuiltActiveDescriptor in order to get rid of the memory leak.

Going to file a bug report against HK2, so that John could address this.

Comment by Jakub Podlesak [ 24/Feb/15 ]

Hmmm, after a chat with John and some more debugging, it turns out Jersey is the only one to fix. Already submitted an internal review request.

Comment by Jakub Podlesak [ 25/Feb/15 ]

Fixed in the master branch.





[JERSEY-2799] Temporary files created via FileProvider are never deleted Created: 19/Feb/15  Updated: 19/Feb/15  Resolved: 19/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Michal Gajdos
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Temporary files created in FileProvider (or in multipart module) are never deleted (or deleted only at JVM shutdown).



 Comments   
Comment by Michal Gajdos [ 19/Feb/15 ]

Users should delete the file manually when they're given a File handle.





[JERSEY-2798] Document performance penality introduced by DataSource Provider Created: 18/Feb/15  Updated: 18/Feb/15

Status: Open
Project: jersey
Component/s: docs, performance
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Task Priority: Major
Reporter: Michael Osipov Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Document that the DataSource implementation used by Jersey is backed by a byte array. That might introduce a huge performance/memory penality when huge data is processed.

In my case, a client can upstream large files (hundreds of megabytes), I requested Jersey to provide a DataSource. Memory exploded. I resorted to an inputStream with a custom InputStreamDataSource in the backend. That sovled the issue.






[JERSEY-2797] Jersey(2.10.4) Entity provider selection algorithm gives less priority to custom providers(MessageBodyWriter) making it not to be invoked Created: 18/Feb/15  Updated: 17/Mar/15

Status: Open
Project: jersey
Component/s: core, media
Affects Version/s: 2.10
Fix Version/s: None

Type: Bug Priority: Major
Reporter: shaswat Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Glassfish 4.1



 Description   

We have a custom MessageBodyWriter in our application for serializing DTO objects to XML in output stream

We have a custom MessageBodyWriter in our application that produces data of Media type application/xml.As we know Jersey 2.x has an algorithm(https://jersey.java.net/documentation/latest/message-body-workers.html#mbw.writer.selection.algorithm) that chooses a suitable MBR from a list of internal and custom MessageBodyWriters to persist entity into output buffer.The algorithm sorts MBR is based upon Object type distance and media type distance.So our Custom MBR is not getting invoked as we saw in the Jersey common code (MessageBodyFactory.getMessageBodyWriter())that our Custom Writer is at the below in the list and some other provider whose isWriteable() method returns true getting invoked.Further based on media type sorting our writers gets priority as we have mentioned media type as "application/xml" ,but in terms of Object type distance the priority gets lower as the DTO objects to be persist has long distance from Object super class .Eventually our Custom writer sits below in the list of writer providers and other JAXB providers like (specifically XmlRootElementJaxbProvider) gets priority and as its isWriteable() returns true so this provider (XmlRootElementJaxbProvider) gets called

The question is how can we force Jersey to invoke custom MessageBodyWriters ??Should we try adding a custom media type(like application/vnd.xml) to force it to call our Custom MessageBodyWriters ??



 Comments   
Comment by Michal Gajdos [ 18/Feb/15 ]

How do you register the provider into your application?

Comment by shaswat [ 18/Feb/15 ]

We have decorated our custom MessageBodyWriter with @Provider annotation.
@Provider
@Produces("application/xml")
public class RestDataSourceMessageBodyWriter implements MessageBodyWriter<Object> {

Comment by Michal Gajdos [ 20/Feb/15 ]

Ok, so you're using package scanning to register your provider. In this case Jersey doesn't recognizes your provider as a custom provider and treats it like our providers. Try to add @Priority(1) annotation on top of your provider.

Comment by shaswat [ 23/Feb/15 ]

I added @Priority(1) annotation on top of my MBW .The issue still exist.

@Priority(1)
@Provider
@Produces("application/xml")
public class RestDataSourceMessageBodyWriter implements MessageBodyWriter<Object> {

Comment by shaswat [ 23/Feb/15 ]

I guess we can use Priorities annotation for Interceptors /filters not for MessageBodyWriters .

Comment by shaswat [ 23/Feb/15 ]

Well My custom MBR looks like below
@Provider
@Produces("application/xml")
public class RestDataSourceMessageBodyWriter implements MessageBodyWriter {

if I make my custom MBR more specific like

@Provider
@Produces("application/xml")
public class RestDataSourceMessageBodyWriter implements MessageBodyWriter<UserInfoDTO> {

(Here "UserInfoDTO" is the first DTO object which gets searlized to xml by entity provider) then it works .But we cannot write custom MBR for thousands of DTOs and it has to be any ways.What do you suggest here?

Comment by Adam Lindenthal [ 05/Mar/15 ]

Hi shaswat,

well, if you cannot make your DTOs to extend an abstract class or implement an interface, you might want to try to set the legacy ordering property.

Comment by shaswat [ 06/Mar/15 ]

Hi Adam,

I already did that .I added below method in my root application class(class that extends javax.ws.rs.core.Application ),but interestingly ,the issue remains

@Override
public Map<String,Object> getProperties()

{ Map<String,Object> resources = new java.util.HashMap<>(); resources.put(LEGACY_WORKERS_ORDERING, true); return resources; }
Comment by Adam Lindenthal [ 06/Mar/15 ]

Interesting,
would you mind providing a full (as minimalistic as possible) reproducer test case? Not necessarily a unit test per se, just a tiny app with one resource and the custom provider registered (ideally maven based) that shows the problem isolated from other influences. You can either put it on github and link it here or send a zip to me via email, I will attach it here (unfortunately you don't have the permission to attach files in JIRA directly). If it saves you some time, you can use one of our archetypes to generate the skeleton of the app.
We need to either confirm, that there is a bug in the provider (writer) selection algorithm (or some related code) or check if there is something wrong with the way you are using it and make it clear (e.g. update the docs).

BTW, does your problem still persist if you register all your resources and providers manually (not the entire package)?

Thanks,
Adam

Comment by shaswat [ 06/Mar/15 ]

Please share your mail id or I'll put the code on git hub and share the link here.Well I did analyze a lot ,debugged the Jersey core package's MessageBodyFactory getMessageBodyWriter () method .I believe there is an issue with sorting of MBRs(MessageBodyWriter) on Object type distance grounds.Just to confirm that I created a sample app and my DTOs didn't extend or implemented any class or interfaces .I was able to call the writeTo() method of my custom MBR.Then I made my DTOs to extend couple of classes and I was able to reproduce the issue .The distance from your DTO class from java.lang.Object matters I guess here if you write---
public class RestDataSourceMessageBodyWriter implements MessageBodyWriter<Object> { "angle brackets java.lang.Object" "

Comment by shaswat [ 06/Mar/15 ]

We decorated our MBR with @Provider .That's what we do to register our custom provider .How do I register them manually?

Comment by shaswat [ 06/Mar/15 ]

oops sorry to mentioned that I did try registering them manually like below and the issue remained.

@Override
public Set<Class<?>> getClasses()

{ Set<Class<?>> resources = new java.util.HashSet<>(); resources.add(com.jenzabar.ngp.smartgwt.jaxrs.RestDataSourceMessageBodyWriter.class); return resources; }
Comment by Adam Lindenthal [ 06/Mar/15 ]

Yes, that's what I was asking.
The email is my firstname.lastname at oracle.com.

Thanks, after I receive it, I'll attach it here, so that whoever will work on this issue has the access to the reproducer.

Regards,
Adam

Comment by Jakub Podlesak [ 17/Mar/15 ]

Any update on the use case? Anybody?





[JERSEY-2796] Calling getClasses() on ResourceConfig breaks example in some cases Created: 17/Feb/15  Updated: 18/Feb/15  Resolved: 18/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: jstrom Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Jersey 2.16, Java 1.7.0_51



 Description   

During a debugging session I added a call to rc.getClasses(), in combination with manually registering a filter. Suddenly, all my requests started giving 404 errors.

The example below demonstrates this on the simple-service example, based on Jersey 2.16:

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example \
-DarchetypeVersion=2.16

Apply patch which demonstrates problem:

  • If I remove either getClasses or register, it works fine.
  • If I call getClasses after register, it works fine.
--- a/src/main/java/com/example/Main.java
+++ b/src/main/java/com/example/Main.java
@@ -4,6 +4,9 @@ import org.glassfish.grizzly.http.server.HttpServer;
 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
 import org.glassfish.jersey.server.ResourceConfig;

+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+
 import java.io.IOException;
 import java.net.URI;

@@ -23,6 +26,9 @@ public class Main {
         // create a resource config that scans for JAX-RS resources and providers
         // in com.example package
         final ResourceConfig rc = new ResourceConfig().packages("com.example");
+
+        System.out.println("Loaded with classes "+ rc.getClasses());
+        rc.register(SimpleFilter.class);

         // create and start a new instance of grizzly http server
         // exposing the Jersey application at BASE_URI
@@ -41,5 +47,12 @@ public class Main {
         System.in.read();
         server.stop();
     }
+
+    public static class SimpleFilter implements ContainerRequestFilter {
+        @Override
+        public void filter(ContainerRequestContext crc) throws IOException {
+            System.out.println("in filter");
+        }
+    }
 }

Results:

Running com.example.MyResourceTest
Loaded with classes [class com.example.MyResource]
Feb 17, 2015 6:00:26 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:8080]
Feb 17, 2015 6:00:26 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Feb 17, 2015 6:00:26 PM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:8080]
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.425 sec <<< FAILURE!

Results :

Tests in error:
  testGetIt(com.example.MyResourceTest): HTTP 404 Not Found





[JERSEY-2795] CopyOnWriteHashMap is not thread safe Created: 17/Feb/15  Updated: 20/Apr/15  Resolved: 20/Apr/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 1.19
Fix Version/s: 1.20

Type: Bug Priority: Major
Reporter: djasonpenney Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: pull-request
Remaining Estimate: 1 day
Time Spent: Not Specified
Original Estimate: 1 day


 Description   

Under load, I have noticed the Netflix Zuul router occasionally generates the following message:

Unable to execute RestClient request for URI:http://<omitted>
Caused by: java.lang.NullPointerException
at com.sun.jersey.client.impl.CopyOnWriteHashMap.entrySet(CopyOnWriteHashMap.java:155)
...
at com.netflix.niws.client.http.RestClient.execute(RestClient.java:89)
at com.netflix.client.AbstractLoadBalancerAwareClient.executeOnSingleServer(AbstractLoadBalancerAwareClient.java:116)

Investigation shows that com.sun.jersey.client.impl.CopyOnWriteHashMap.java is not at all thread safe. In the face of concurrent updating, certain readers will retrieve a "null" underlying view object. Second, concurrent updates may be lost.

I recommend rewrite of this class to require a volatile read for concurrent reading as well as full synchronization to protect concurrent writes.



 Comments   
Comment by Michal Gajdos [ 17/Feb/15 ]

Pull Request: https://github.com/jersey/jersey-1.x/pull/15

Comment by Michal Gajdos [ 20/Apr/15 ]

Thank you Jason for fixing the issue.





[JERSEY-2794] Aborted multipart upload leaves non-empty MIME*.tmp tempfile behind Created: 17/Feb/15  Updated: 16/Mar/15  Resolved: 16/Mar/15

Status: Resolved
Project: jersey
Component/s: media
Affects Version/s: 2.16
Fix Version/s: 2.18

Type: Bug Priority: Major
Reporter: mikaelstaldal Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

jetty-9.2.5.v20141112

java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) Server VM (build 25.20-b23, mixed mode)

Linux 3.13.0-45-generic



 Description   

I have a resource method like this:

  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @POST
  public Response upload(@Context UriInfo uriInfo.
             @FormDataParam("text") String foo,
             @FormDataParam("file") InputStream file) {
      // do stuff
  }

This usually works, but if someone upload a large file and the upload is aborted midway, a non-empty temporary file named /tmp/MIME5392929676998476902.tmp (the number varies) is left behind until the JVM is shut down. This is a resource leak which can lead to out of disk space. In this case, my resource method is never invoked (which is fine) and I see this Exception caught by my general ExceptionMapper (which is not OK):

org.eclipse.jetty.io.EofException: Early EOF
        at org.eclipse.jetty.server.HttpInput$3.noContent(HttpInput.java:486) ~[jetty-server-9.2.5.v20141112.jar:9.2.5.v20141112]
        at org.eclipse.jetty.server.HttpInput.read(HttpInput.java:124) ~[jetty-server-9.2.5.v20141112.jar:9.2.5.v20141112]
        at org.glassfish.jersey.message.internal.EntityInputStream.read(EntityInputStream.java:101) ~[jersey-common-2.16.jar:?] 
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream.read(ReaderInterceptorExecutor.java:301) ~[jersey-common-2.16.jar:?]
        at org.jvnet.mimepull.MIMEParser.fillBuf(MIMEParser.java:440) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEParser.readBody(MIMEParser.java:216) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEParser.access$600(MIMEParser.java:68) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:165) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:132) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEMessage.makeProgress(MIMEMessage.java:198) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEMessage.parseAll(MIMEMessage.java:181) ~[mimepull-1.9.3.jar:1.9.3]
        at org.jvnet.mimepull.MIMEMessage.getAttachments(MIMEMessage.java:106) ~[mimepull-1.9.3.jar:1.9.3]
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:226) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:91) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:180) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:92) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:259) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.spi.ContentEncoder.aroundReadFrom(ContentEncoder.java:127) ~[jersey-common-2.16.jar:?] 
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:74) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1075) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:785) ~[jersey-common-2.16.jar:?]
        at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:233) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider.getEntity(FormDataParamValueFactoryProvider.java:376) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider.access$000(FormDataParamValueFactoryProvider.java:87) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:203) ~[jersey-media-multipart-2.16.jar:?]
        at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:125) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:158) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) ~[jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303) [jersey-server-2.16.jar:?]
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.internal.Errors.process(Errors.java:315) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.internal.Errors.process(Errors.java:297) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.internal.Errors.process(Errors.java:267) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) [jersey-common-2.16.jar:?]
        at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286) [jersey-server-2.16.jar:?]
        at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072) [jersey-server-2.16.jar:?]
        at org.gh.jersey.servlet.WebComponent.service(WebComponent.java:399) [jersey-container-servlet-core-2.16.jar:?]
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) [jersey-container-servlet-core-2.16.jar:?]
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) [jersey-container-servlet-core-2.16.jar:?]
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) [jersey-container-servlet-core-2.16.jar:?]
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:800) [jetty-servlet-9.2.5.v20141112.jar:9.2.5.v20141112]
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) [jetty-servlet-9.2.5.v20141112.jar:9.2.5.v20141112]


 Comments   
Comment by Michal Gajdos [ 18/Feb/15 ]

Thanks for filing this. I am currently looking at one multipart issue (JERSEY-2663) – I'll try to solve this issue with it as well. Moving to backlog for now.





[JERSEY-2793] EntityFiltering with Jackson doesn't work for subclasses Created: 16/Feb/15  Updated: 19/Feb/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: anna_zhdan Assignee: Unassigned
Resolution: Unresolved Votes: 2
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I've tried using entity filtering feature. Here is my resource class


@Path("users")
@Produces("application/json")
public class Users {

    @GET
    public Entity getUser() {
        return new User("1", "anna", "anna@example.com");
    }

}

In this case entity filtering doesn't work – whatever I pass as "select" parameter, I get only implicit "type" field for my entity
(

{"type":"jetbrains.gap.app.User"}

)
If I change method return type to User everything works fine for me.



 Comments   
Comment by Michal Gajdos [ 18/Feb/15 ]

Moving to backlog for now but I'll try to target the fix for the next version.

Comment by anna_zhdan [ 19/Feb/15 ]

Michal, we've found a warkaround for this in case of returning a single entity:

return Response.ok(new GenericEntity<Entity>(result, entityType))

as I actually have entityType in runtime for this method.
But I have a problem about fixing a case with returning a list of entities (I also know entityType for list elements in runtime). Maybe you know how to deal with this case?





[JERSEY-2792] NPE in JerseyTest.tearDown Created: 15/Feb/15  Updated: 15/Feb/15  Resolved: 15/Feb/15

Status: Resolved
Project: jersey
Component/s: test-framework
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

https://github.com/jersey/jersey/pull/140

To handle cases when tearDown throws an exception and makes exception from setup/test methods swallowed/overwritten.

Really helps with debugging setup problems. In my case corresponding setUp did not complete correctly and old test container was null.






[JERSEY-2791] Add support for micro-benchmarks in Jersey (JMH based) Created: 15/Feb/15  Updated: 18/Feb/15  Resolved: 18/Feb/15

Status: Resolved
Project: jersey
Component/s: test-framework
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Task Priority: Major
Reporter: Michal Gajdos Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

We currently don't have means to measure performance of local changes easily. This task is aimed to add support for basic, JMH based, benchmark tests to Jersey.

DEMO:

  • Create an example of such a benchmark.





[JERSEY-2790] jaxrs-ri transitively pulls in sources jars, wastes space and increases startup time Created: 14/Feb/15  Updated: 17/Feb/15  Resolved: 17/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: minfrin Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When an attempt is made to depend on jaxrs-ri as below, various sources jars are included transitively.

Due to a bug in maven, it is impossible to filter out these sources files.

<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.16</version>
</dependency>

mvn dependency:tree reveals the sources jars included transitively:

[INFO] +- org.glassfish.jersey.bundles:jaxrs-ri:jar:2.16:compile
[INFO] | +- javax.ws.rs:javax.ws.rs-api:jar:sources:2.0.1:compile
[INFO] | +- org.glassfish.jersey.core:jersey-common:jar:sources:2.16:compile
[INFO] | +- org.glassfish.jersey.media:jersey-media-jaxb:jar:sources:2.16:compile
[INFO] | +- org.glassfish.jersey.core:jersey-client:jar:sources:2.16:compile
[INFO] | +- org.glassfish.jersey.core:jersey-server:jar:sources:2.16:compile
[INFO] | +- org.glassfish.jersey.containers:jersey-container-servlet-core:jar:sources:2.16:compile
[INFO] | - org.glassfish.jersey.containers:jersey-container-servlet:jar:sources:2.16:compile

To fix this, remove the stray dependency on the sources jars.



 Comments   
Comment by Michal Gajdos [ 17/Feb/15 ]

Nice catch. Fixed in master.





[JERSEY-2789] Astral Unicode characters included in uri parts are not properly encoded Created: 13/Feb/15  Updated: 18/Feb/15  Resolved: 18/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.5
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: lcsanchez08 Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Cloners
clones JERSEY-2293 Astral Unicode characters included in... Resolved

 Description   

The URL encoding algorithm incorrectly iterates over code units (chars) instead of code points (ints). This means that characters in the Basic Multilingual Plane are encoded just fine (http://codepoints.net/basic_multilingual_plane), but characters in the Astral Plane are always incorrectly encoded as %3F%3F.



 Comments   
Comment by Michal Gajdos [ 13/Feb/15 ]

Jersey 2.x clone of JERSEY-2293.





[JERSEY-2788] Stuck in loop in ResourceConfig.scanClasses Created: 12/Feb/15  Updated: 18/Feb/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.15, 2.16
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: jstrom Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: osgi, scanning
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Jersey 2.15, and 2bc1fcb
Apache Karaf 3.0.3



 Description   

Hi,
I'm new with Jersey and I'm trying to run a jersey/grizzley based server in the Apache Karaf OSGI container.

In short, I have a resource directory with static files (well, only one so far) in the JAR. When ResourceConfig scans, it gets stuck in an infinite loop on this directory.

In long:

I have a pretty basic project, which fails to load. The relevant code is more or less from the tutorials:

log.info("Hello, starting!");
final ResourceConfig rc = new ResourceConfig().packages("testproject");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);

I use basic iPOJO component to get something runnable.
In addition, i have a directory with static files under "testproject/www".

During component activation, I get stuck inside createHttpServer forever:

Name: [iPOJO] pool-1-thread-1
State: RUNNABLE
Total blocked: 9  Total waited: 3

Stack trace: 
org.glassfish.jersey.server.ResourceConfig.scanClasses(ResourceConfig.java:905)
org.glassfish.jersey.server.ResourceConfig._getClasses(ResourceConfig.java:849)
org.glassfish.jersey.server.ResourceConfig.getClasses(ResourceConfig.java:755)
org.glassfish.jersey.server.ResourceConfig$RuntimeConfig.<init>(ResourceConfig.java:1184)
org.glassfish.jersey.server.ResourceConfig$RuntimeConfig.<init>(ResourceConfig.java:1157)
org.glassfish.jersey.server.ResourceConfig.createRuntimeConfig(ResourceConfig.java:1153)
org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:322)
org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:289)
org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.<init>(GrizzlyHttpContainer.java:331)
org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory.createHttpServer(GrizzlyHttpServerFactory.java:119)
asd.Main.startServer(Main.java:55)
asd.Main.__M_start(Main.java:89)
asd.Main.start(Main.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.apache.felix.ipojo.util.Callback.call(Callback.java:237)
org.apache.felix.ipojo.util.Callback.call(Callback.java:193)
org.apache.felix.ipojo.handlers.lifecycle.callback.LifecycleCallback.call(LifecycleCallback.java:86)
org.apache.felix.ipojo.handlers.lifecycle.callback.LifecycleCallbackHandler.__M_stateChanged(LifecycleCallbackHandler.java:162)
org.apache.felix.ipojo.handlers.lifecycle.callback.LifecycleCallbackHandler.stateChanged(LifecycleCallbackHandler.java)
org.apache.felix.ipojo.InstanceManager.setState(InstanceManager.java:560)
org.apache.felix.ipojo.InstanceManager.start(InstanceManager.java:440)
org.apache.felix.ipojo.ComponentFactory.createInstance(ComponentFactory.java:179)
org.apache.felix.ipojo.IPojoFactory.createComponentInstance(IPojoFactory.java:319)
   - locked org.apache.felix.ipojo.ComponentFactory@46737f42
org.apache.felix.ipojo.IPojoFactory.createComponentInstance(IPojoFactory.java:240)
org.apache.felix.ipojo.extender.internal.linker.ManagedType$InstanceSupport$1.call(ManagedType.java:312)
org.apache.felix.ipojo.extender.internal.linker.ManagedType$InstanceSupport$1.call(ManagedType.java:306)
org.apache.felix.ipojo.extender.internal.queue.JobInfoCallable.call(JobInfoCallable.java:114)
java.util.concurrent.FutureTask.run(FutureTask.java:262)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:745)

This was on jersey 2.15. I tried master, same issue. Modified the code a bit to see what's going on (patch against master):

index edc3c24..bd52cbd 100644
--- a/core-server/src/main/java/org/glassfish/jersey/server/ResourceConfig.java
+++ b/core-server/src/main/java/org/glassfish/jersey/server/ResourceConfig.java
@@ -887,6 +887,7 @@ public class ResourceConfig extends Application implements Configurable<Resource
             while (resourceFinder.hasNext()) {
                 final String next = resourceFinder.next();
                 if (afl.accept(next)) {
+                                                LOGGER.log(Level.INFO, "Loading resource "+next+" from finder "+rfs.getClass()+" -> " + rfs);
                     final InputStream in = resourceFinder.open();
                     try {
                         afl.process(next, in);
@@ -894,12 +895,14 @@ public class ResourceConfig extends Application implements Configurable<Resource
                         LOGGER.log(Level.WARNING, LocalizationMessages.RESOURCE_CONFIG_UNABLE_TO_PROCESS(next));
                     } finally {
                         try {
+                                                LOGGER.log(Level.INFO, "Closing instream for "+next);
                             in.close();
                         } catch (final IOException ex) {
                             LOGGER.log(Level.FINER, "Error closing resource stream.", ex);
                         }
                     }
-                }
+                }else
+                                                LOGGER.log(Level.INFO, "Not loading resource "+next+" from finder "+rfs.getClass()+" -> " + rfs);
             }
         }

This gives me the following output:

2015-02-12 14:42:15,170 | INFO  |  pool-1-thread-1 | Main                             | 146 - testproject - 1.0.0.SNAPSHOT | Hello, starting!
2015-02-12 14:42:15,170 | INFO  |  pool-1-thread-1 | ResourceConfig                   | 269 - org.glassfish.jersey.core.jersey-server - 2.16.0.SNAPSHOT | Not loading resource /asd/www/ from finder class java.util.HashSet -> [org.glassfish.jersey.server.internal.scanning.PackageNamesScanner@23b9b99d]
2015-02-12 14:42:15,170 | INFO  |  pool-1-thread-1 | ResourceConfig                   | 269 - org.glassfish.jersey.core.jersey-server - 2.16.0.SNAPSHOT | Not loading resource /asd/www/ from finder class java.util.HashSet -> [org.glassfish.jersey.server.internal.scanning.PackageNamesScanner@23b9b99d]
2015-02-12 14:42:15,171 | INFO  |  pool-1-thread-1 | ResourceConfig                   | 269 - org.glassfish.jersey.core.jersey-server - 2.16.0.SNAPSHOT | Not loading resource /asd/www/ from finder class java.util.HashSet -> [org.glassfish.jersey.server.internal.scanning.PackageNamesScanner@23b9b99d]

And on it goes.. forever, until JVM is killed. So, for some reason the ResourceFinder keeps giving me that directory over and over.

If i remove the www directory from my package, everything starts up perfectly fine.

As a side note, to anyone else trying to get OSGI/Jersey working: I kept getting the following exception:

java.lang.IllegalStateException: No generator was provided and there is no default generator registered
	at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.internalCreate(ServiceLocatorFactoryImpl.java:266)
	at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.create(ServiceLocatorFactoryImpl.java:230)
	at org.glassfish.jersey.internal.inject.Injections._createLocator(Injections.java:138)
	at org.glassfish.jersey.internal.inject.Injections.createLocator(Injections.java:123)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:308)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:289)
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.<init>(GrizzlyHttpContainer.java:331)
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory.createHttpServer(GrizzlyHttpServerFactory.java:119)

until I ensured that org.glassfish.hk2.locator was installed. In my maven-bundle-plugin instructions I added "<_include>src/main/resources/bundle.osgi</_include>", which contains "Require-Bundle: org.glassfish.hk2.locator".
Is there any better way to do this? Require-bundle seems non-recommended..



 Comments   
Comment by jstrom [ 12/Feb/15 ]

Oops, log output above says "Not loading resource /asd/www/"... I missed to rewrite that part in the issue text (in the rest of the text I changed "asd" to "testproject", to avoid confusion about "asd". that fired back!)

Comment by jstrom [ 12/Feb/15 ]

After some additional testing, it seems that it fails if the scanned prefix contains any HTML files.
Some tested scenarios:

Fails:
new ResourceConfig().packages("testproject")
/testproject/Main.class
/testproject/index.html

Fails:
new ResourceConfig().packages("testproject")
/testproject/Main.class
/testproject/index.html

Fails:
new ResourceConfig().packages("testproject")
/testproject/Main.class
/testproject/www/index.html

Works:
new ResourceConfig().packages("testproject.src")
/testproject/src/Main.class
/testproject/www/index.html

Works:
new ResourceConfig().packages("testproject")
/testproject/Main.class
/www/index.html

So.. Basically it seems I can not have any .html files in the path which is scanned?
It's easy to avoid though, just keep code in "com.example.project" and HTML resources in "www" (in a particular JAR). Keeping resources under com.example.project.www would fail though (but not sure if that is common practice or not).

For the record, this did not occur when running in standalone mode (with static main() as from the tutorials).

Comment by jstrom [ 18/Feb/15 ]

I've done some more debugging, and verified this is also a problem on 2.16 (and 2.17-SNAPSHOT @ b2424a3). I've noticed that it may hang on plain directories as well, even if they have class files in them.
The actual hang boils down to this:

  1. scanClasses calls hasNext() on the ResourceFinder, in this case a BundleSchemeResourceFinder.
  2. BundleSchemeResourceFinder.hasNext will return true if an internal boolean "accessed" is false.
  3. If the AnnotationAcceptingListener does accept the resource, it calls open() on the resourceFinder, else it continues with another round of hasNext().
  4. in BundleSchemeResourceFinder, if open() is called, accessed is set to true.
  5. Since open() is never called, accessed will always be false and we are stuck in a loop.

In my case, there are a bunch of BundleSchemeResourceFinder instances added to the resource stack. These are added from ResourceConfig.init(), which eventually delegates to osgiRegistry.getPackageResources to find any resources in my bundle.
In OsgiRegistry.getPackageResources (with some extra logging added), the call to findEntries (with recurse=false) results in this:

Looking for package asd in asd [154]
  found entry /asd/BasicApiResource.class => asd.BasicApiResource at bundle://154.0:0/asd/BasicApiResource.class
  found entry /asd/Main.class => asd.Main at bundle://154.0:0/asd/Main.class
.. some more classes...
  found entry /asd/TestExceptionMapper.class => asd.TestExceptionMapper at bundle://154.0:0/asd/TestExceptionMapper.class
  found entry /asd/x/ => asd. at bundle://154.0:0/asd/x/

The /asd/x directory has a few other resources, but since findEntries is non-recursive, it only returns the directory.

A working workaround is to make sure that any directory which is scanned, does not have any subdirectories. For example, ensure all resources are located in asd.resources and have nothing but .class files there.

Comment by jstrom [ 18/Feb/15 ]

(Oh, and a side note to any future google references to "No generator was provided and there is no default generator registered", it seems to be very important that the org.glassfish.hk2.osgi-resource-locator bundle is loaded before anything else (more likely, before org.glassfish.hk2.locator). Ensure this happens by setting the start-level of this bundle to a lower value than the rest. In Karaf/Felix, it can be done with bundle:start-level org.glassfish.hk2.osgi-resource-locator 70.)

Comment by jstrom [ 18/Feb/15 ]

Another gotcha with regards to OSGI scanning: On container startup, it will not always find my resources (getPackageResources's call to bundleContext.getBundles() returns no bundles).
Workaround: ensures start-level for the application is higher jersey bundles.

Comment by Michal Gajdos [ 18/Feb/15 ]

Thank you for a very detailed description and analysis, moving to backlog for now (we should be able to look into this soon).





[JERSEY-2787] Incorrect wadl generated when entity parameter is annotated with unknown annotation Created: 11/Feb/15  Updated: 01/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.13, 2.14, 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: elw00d Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: 1221, wadl
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Tested on Windows, Linux. Jersey is executed in standalone mode.



 Description   

Assume that we have a REST method like this:

@POST
public String putSomeEntity(Entity entity) {
   // bla bla bla
}

If execute this and go to application.wadl we should find something like this:

<method id="putSomeEntity" name="POST">
<request>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="entity" mediaType="application/json"/>
</request>
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="entity" mediaType="application/json"/>
</response>
</method>

Let we add some unknown annotation TestAnn to this parameter:

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface SomeAnnotation {
}
@POST
public String putSomeEntity(@SomeAnnotation  Entity entity) {
   // bla bla bla
}

Generated wadl will be changed to something like this:

<method id="putSomeEntity" name="POST">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="entity" mediaType="application/json"/>
</response>
</method>

Now we have no <request/> section. If we will try to generate rest client code using this wadl, we'll get methods without parameters.

Source of this behaviour is unknown annotations processing code. In 2.15 it is org.glassfish.jersey.server.model.Parameter class, method create():

for (Annotation annotation : annotations) {
            if (ANNOTATION_HELPER_MAP.containsKey(annotation.annotationType())) {
                ParamAnnotationHelper helper = ANNOTATION_HELPER_MAP.get(annotation.annotationType());
                paramAnnotation = annotation;
                paramSource = helper.getSource();
                paramName = helper.getValueOf(annotation);
            } else if (Encoded.class == annotation.annotationType()) {
                paramEncoded = true;
            } else if (DefaultValue.class == annotation.annotationType()) {
                paramDefault = ((DefaultValue) annotation).value();
            } else {
                // Take latest unknown annotation, but don't override known annotation
                if ((paramAnnotation == null) || (paramSource == Source.UNKNOWN)) {
                    paramAnnotation = annotation;
                    paramSource = Source.UNKNOWN;
                    paramName = getValue(annotation);
                }
            }
        }

        if (paramAnnotation == null) {
            paramSource = Parameter.Source.ENTITY;
        }

When there are unknown annotation and no more annotations, this code makes parameter UNKNOWN instead of ENTITY. To quick fix this I added line to loop body:

if (annotation instanceof SomeAnnotation) continue;

Hope this can be fixed more elegantly and without any compatibility issues.



 Comments   
Comment by Michal Gajdos [ 18/Feb/15 ]

Thanks for filing the issue and for investigation where the problem might be. Moving to backlog for now until someone picks it up.





[JERSEY-2786] Memory leak with shutdown hooks, caused by configuration inheritance Created: 11/Feb/15  Updated: 18/Mar/15  Resolved: 18/Mar/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.15
Fix Version/s: 2.18

Type: Bug Priority: Critical
Reporter: ogheorghies+java@gmail.com Assignee: Jakub Podlesak
Resolution: Fixed Votes: 1
Labels: memory-leak
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to JERSEY-2688 Memory leak with the shutdown hooks q... Resolved

 Description   

The following code causes OutOfMemoryError. An actual invocation.invoke() call is neither required, nor it eliminates the problem.

OOM Repro
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://example.com");

        while (true) {
            WebTarget target2 = target.property("foo", "bar");
            Builder req = target2.request();
            Invocation invocation = req.buildGet();
        }

Root cause:

  • Each Jersey ClientConfig has a copy-on-write State, and each State instance creates one lazily-initialized ClientRuntime.
  • Whenever target.property() is called, a new State copy is created.
  • The JerseyInvocation created by buildGet() uses this new State instance, and accesses its lazily-initialized ClientRuntime.
  • Upon its initialization, ClientRuntime is registered as a shutdown hook with the JerseyClient.

Therefore, each iteration results in one ClientRuntime instance being added to the list of shutdown hooks in JerseyClient. The ClientRuntime instance is never removed from this list.

This issue is probably the root cause of https://java.net/jira/browse/JERSEY-2688 , which was catalogued as a "connectors" issue that has to do with ApacheConnector.



 Comments   
Comment by prattm [ 16/Mar/15 ]

We have run into this memory leak in 2.13 using a slightly different path:

Client client = ClientBuilder.newClient()
               .property(ClientProperties.CONNECT_TIMEOUT, getConnectTimeout())
               .property(ClientProperties.READ_TIMEOUT,    getReadTimeout())
               .register(CustomJacksonContextResolver.class);

WebTarget target = client.target("http://host:port/resources");
target.register(LoggingFilter(...));
target.path("path");
target.request().get(SomeDto.class);

As the originator points out, all forms of property() and register() inside ClientConfig cause the State to be copied. This leads to unbounded memory growth in our apps, requiring daily bounces of our services. Removing the LoggingFilter on all of our requests alleviates the leak.

Comment by Jakub Podlesak [ 17/Mar/15 ]

To workaround this and also to achieve a better performance, you could do the following:
Build the client with a well configured ClientConfig already:

  Client client = ClientBuilder.newClient(new ClientConfig().register(new LoggingFilter(...)).register(...).property(...));

Reuse the above client for all appropriate targets (that share the same configuration).
If needed, explicitly create another client with different configuration for targets that need to be configured differently (e.g. when no logging filter is required).

Comment by Jakub Podlesak [ 18/Mar/15 ]

This has been fixed in the master branch.

However, whenever possible, please follow the suggestion above to avoid redundant client runtime instances creation.





[JERSEY-2785] Use StAX instead of SAX for JAXB Created: 11/Feb/15  Updated: 19/Feb/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.16
Fix Version/s: backlog

Type: Improvement Priority: Major
Reporter: evnp Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Is it possible to change SAXSource to StAX XMLInputFactory in org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider?

JAXB RI use woodstox StAX implementation if possible because it has great perfomance advantages, so adding woodstox jar to classpath will increase XML marshalling and unmarshalling speed.



 Comments   
Comment by Michal Gajdos [ 18/Feb/15 ]

Can you, please, elaborate more? I mean can you point us to some performance overview of these two approaches?

Comment by evnp [ 19/Feb/15 ]

See http://stackoverflow.com/questions/11773649/java-xml-parser-performance-sun-java-streaming-xml-parser-sjsxp-vs-woodsto/11782775#11782775 for example. For my private xml data this is true: woodstox is faster than default stax implementation and aalto is bit faster than woodstox.





[JERSEY-2784] Selectable Entity Filtering doesn't work with JodaTime Fields Created: 10/Feb/15  Updated: 25/Feb/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: difranr Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK 1.8, Cargo with Tomcat 8


Issue Links:
Duplicate
is duplicated by JERSEY-2803 InternalServerErrorException when usi... Resolved

 Description   

We have model objects that have JodaTime Instants in them and when I enabled SelectableEntityFilteringFeature, the content fails to render. I debugged it and it seems to fail specifically on the ZONE field which is of type DateTimeZone. This type is abstract and contains only static fields, therefore the method ObjectGraphImpl.getFields(final String parent) fails because the enclosed graph object is NULL.



 Comments   
Comment by difranr [ 11/Feb/15 ]

I want to further clarify, what is occurring. We have a domain object that looks like:

Bar.java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Thing {
  private String id;
  private Instant createdDate;
}

And then an enclosing response object that looks like:

Bar.java
@XmlRootElement
public class ThingCollectionResponse {
    private Integer total;

    private List<Thing> entries = new ArrayList<>();

    public ThingCollectionResponse() {
    }

    public ThingCollectionResponse(List<Thing> entries) {
        setEntries(entries);
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public List<Thing> getEntries() {
        return entries;
    }

    public void setEntries(List<Thing> entries) {
        this.entries = entries;
        total = this.entries.size();
    }
}

When I access my response which returns just a Thing object it works fine and it filters just fine. It just when I return a collection via the ThingCollectionResponse that it fails to render at all, because it hits the NPE in ObjectGraphImpl.getFields().

Comment by Michal Gajdos [ 18/Feb/15 ]

Oh, I see. I guess we should introduce a way how to exclude classes (e.g. JodaTime classes) from being processed by EntityFiltering processors. Thank you for reporting this!

Comment by difranr [ 18/Feb/15 ]

@Michal It would be NICE to filter on these fields, but the code needs to recognize not to recurse into fields that are abstract/static, etc. I believe that this issue is related:

https://java.net/jira/browse/JERSEY-781

I was trying to come up with a fix, but got bogged down try to upgrade to 2.16.





[JERSEY-2783] Priority comparator fails when dealing with edge case values Integer.MIN_VALUE and Integer.MAX_VALUE Created: 10/Feb/15  Updated: 10/Feb/15  Resolved: 10/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.15
Fix Version/s: 2.16

Type: Bug Priority: Major
Reporter: Jakub Podlesak Assignee: Jakub Podlesak
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

This was already fixed with the following commit:
SHA: 63e9eaa385e1600c6ff9613c5e0b6f2343420096
Author: Jakub Podlesak <jakub.podlesak@oracle.com>
Date: Mon Jan 26 2015 20:05:54 GMT+0100 (CET)
Subject: Fixed nasty RankedComparator bug (pointed out my Mira) where edge case values caused comparator malfunction
Parent: de2c2f9e58646375c65093195108ad0c9629522d






[JERSEY-2782] MOXy-based JSON unmarshaller returns null "root" Object value when an unmapped JSON property name is returned Created: 09/Feb/15  Updated: 18/Feb/15  Resolved: 18/Feb/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.15
Fix Version/s: None

Type: Bug Priority: Major
Reporter: dallasvaughan Assignee: Michal Gajdos
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Zip Archive json-moxy.zip    

 Description   

If there are any properties in a JSON-based response which are not mapped to a Java property of an @XmlRootElement-annotated class given as the return type of a POST request, the return object value is null (even if there are properties which are mapped correctly).

For comparison, when using the Jackson feature, and an unmapped JSON property is encountered during client response processing, it throws the following exception:

javax.ws.rs.ProcessingException: Error reading entity from input stream.
~
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "fieldC" (class com.SomeClass), not marked as ignorable (2 known properties: "fieldA", "fieldB"])

The MOXy feature, on the other hand, provides no information about what the problem is making it difficult to debug (unless you already know about this issue).



 Comments   
Comment by Michal Gajdos [ 10/Feb/15 ]

Can you provide a reproducible test-case? I am not sure I correctly understand your problem. Thanks.

Comment by dallasvaughan [ 11/Feb/15 ]

Say you want to connect to a REST-based service that returns a JSON response, such as:

{"fieldA" : "value1", "fieldB" : "value2" }

and so you create a Java class to map to this response type using MOXy:

SomeClass.java

@XmlRootElement
public class SomeClass {
   String fieldA;
   String fieldB;

   //fieldA and fieldB getters and setters
}

After receiving the response from the service, it will be successfully unmarshalled to the mapped object:

   WebTarget target = ClientBuilder.newClient().target("http://someservice.com/someresource");
   SomeClass response = target.request().get(SomeClass.class);
   //response is not null and is populated with fieldA="value1" and fieldB="value2"

However, if the service adds a field ("fieldC") to the JSON response that is not mapped in the class as a property, the response will not be unmarshalled successfully and the entire object will be set to null:

{"fieldA" : "value1", "fieldB" : "value2", "fieldC" : "value3" }

Now, when running the same code above...

   WebTarget target = ClientBuilder.newClient().target("http://someservice.com/someresource");
   SomeClass response = target.request().get(SomeClass.class);
   //response is null

Given the same conditions above, when using Jackson as the provider, it throws the error I referenced (UnrecognizedPropertyException). I would expect MOXy to handle it similarly, but it fails silently. Perhaps this is an issue with MOXy itself, but perhaps there is a way to handle this condition by Jersey more effectively .

Comment by Michal Gajdos [ 15/Feb/15 ]

I've slightly updated our json-moxy example, see attached. Unfortunately, I still cannot reproduce it. Can you look at the example and tell me what I did wrong when reproducing the issue? The sample uses MOXy 2.5 and Jersey 2.15. Take a look at JsonResource.createSimpleBean and JsonResourceTest.testGet.

Comment by dallasvaughan [ 17/Feb/15 ]

Thanks for creating this example, Michal. I think I've found the issue: If an "extra" field is in the last position and its value is null, it will return a null result. If the extra field is not null or it is not the last field, it will silently ignore this field and populate the bean with as many field/values as it can.

To verify this, switch the position of "fieldC" in the JsonResource class to be the last field, and set its value to null. This will give the result I described (though I wrongly assumed the issue arose from the extra field and not the fact that this field was null - sorry about that! :-/).

JsonResource.java
    @GET
    @Produces("application/json")
    public String createSimpleBean() {
        // return new TestBean("a", 1, 1L);
        return "{\"fieldA\" : \"a\" , \"foo\" : \"bar\" , \"fieldB\" : \"b\", \"fieldC\" : null}";
        // return "<testBean><a>a</a><b>1</b><c>1</c><foo>bar</foo></testBean>";
    }
Comment by Iaroslav Savytskyi [ 18/Feb/15 ]

This is MOXy issue. I've filled the bug against eclipselink 2.6 : https://bugs.eclipse.org/bugs/show_bug.cgi?id=460253

Comment by Michal Gajdos [ 18/Feb/15 ]

Unfortunately we cannot do anything in Jersey with this. As Iaroslav mentioned it's a problem in MOXy. I'll watch progress on the underlying issue and when it's fixed we can update MOXy in Jersey.





[JERSEY-2781] Locale-dependent test fails in org.glassfish.jersey.message.internal.QualityTest.testEnhanceWithQualityParameter Created: 09/Feb/15  Updated: 10/Feb/15  Resolved: 10/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.16
Fix Version/s: 2.16

Type: Bug Priority: Minor
Reporter: limomartin Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:
$ mvn --version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T18:29:23+01:00)
Maven home: /usr/local/Cellar/maven/3.2.5/libexec
Java version: 1.8.0_31, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre
Default locale: de_DE, platform encoding: UTF-8
OS name: "mac os x", version: "10.10.2", arch: "x86_64", family: "mac"


 Description   
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE! - in org.glassfish.jersey.message.internal.QualityTest
testEnhanceWithQualityParameter(org.glassfish.jersey.message.internal.QualityTest)  Time elapsed: 0.011 sec  <<< FAILURE!
java.lang.AssertionError: 
Expected: <{q=0.2}>
     but: was <{q=0,2}>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:865)
	at org.junit.Assert.assertThat(Assert.java:832)
	at org.glassfish.jersey.message.internal.QualityTest.testEnhanceWithQualityParameter(QualityTest.java:68)

Possible hotfix (besides locale agnostic test):

$ diff pom.xml.old pom.xml
153c153
<                     <argLine>${surefire.security.argline}</argLine>
---
>                     <argLine>${surefire.security.argline} -Duser.language=en -Duser.region=US</argLine>


 Comments   
Comment by Michal Gajdos [ 10/Feb/15 ]

Nice catch, thanks.





[JERSEY-2780] Provide option to opt out from MEDIA_TYPE_MAPPINGS Created: 09/Feb/15  Updated: 18/Feb/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.11
Fix Version/s: icebox

Type: Improvement Priority: Major
Reporter: Michael Osipov Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I have configured MEDIA_TYPE_MAPPINGS for my Jersey apps. Unfortunately, this causes some trouble with a generic upload service in my app.

@PUT
@Path("files/{filename}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response uploadFile(
    @PathParam("filename") @NotNull @Size(max = 240) String filename, DataSource dataSource)

If someone uploads .../files/file.xml the extension is chopped of.

There should be some opt-out to this. Otherwise one has to disable this feature. This is what I did.

Here is the SO question for this.






[JERSEY-2779] ServerSent Events not working when LoggingFilter is enabled with printEntity Created: 09/Feb/15  Updated: 13/Apr/15

Status: Open
Project: jersey
Component/s: core, media
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: quixote_arg Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: 1221, sse
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

tomcat 7.0.53



 Description   

Some time ago I added a LoggingFilter to my application, like this on the "extends ResourceConfig" class:

register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true));

After some time I noticed that the server sent events stopped working.

I reproduced it with the sample from https://jersey.java.net/documentation/latest/sse.html (adding Thread.sleep(1000) to make it more asynchronous); when the LoggingFilter was enabled (with printEntity set to true) then it will wait the whole 30 seconds and output the entire response at once (instead of one per second, 30 times)

If I comment out the LoggingFilter registration or change it to:

register(LoggingFilter.class);

then the chunks arrive once per second, as expected.

Another side effect of the this bug is that when I close the client connection, no exception is thrown on the server, hence the server keeps sending events to the client, even if the connection was closed a long time ago.



 Comments   
Comment by quixote_arg [ 09/Feb/15 ]

I think that the problem is on LoggingFilter.filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) which tries to log the entire entity which the server responded, which in the case of SSE may never finish

LoggingFilter.java
        if (printEntity && responseContext.hasEntity()) {
            OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
            responseContext.setEntityStream(stream);
            requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
            // not calling log(b) here - it will be called by the interceptor
        } else {
            log(b);
        }




[JERSEY-2778] ClassNotFoundException: EntityFilteringFeature Created: 08/Feb/15  Updated: 10/Feb/15  Resolved: 10/Feb/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.15
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: dutoitns@gmail.com Assignee: Unassigned
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 8



 Description   

I pulled Moxy onto my classpath. Now I'm suddenly getting a ClassNotFoundException as follows:

SEVERE: StandardWrapper.Throwable
java.lang.NoClassDefFoundError: org/glassfish/jersey/message/filtering/EntityFilteringFeature
at org.glassfish.jersey.moxy.json.MoxyJsonFeature.entityFilteringEnabled(MoxyJsonFeature.java:100)
at org.glassfish.jersey.moxy.json.MoxyJsonFeature.configure(MoxyJsonFeature.java:89)
at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:709)
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:639)
at org.glassfish.jersey.server.ResourceConfig.configureMetaProviders(ResourceConfig.java:809)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:392)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:167)
at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:327)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:324)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.message.filtering.EntityFilteringFeature
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 30 more

The libraries I downloaded (jars within Jersey's jaxrs-ri-2.15.zip, and Moxy: jersey-media-moxy-2.15.jar) doesn't contain that class?



 Comments   
Comment by dutoitns@gmail.com [ 08/Feb/15 ]

Not sure about the details, but there is another issue open for Jersey 2.15 that also has to do with the EntityFilteringFeature
https://java.net/jira/browse/JERSEY-2777

Comment by Michal Gajdos [ 10/Feb/15 ]

You need to put also jersey-entity-filtering.jar (see [1]) on your class-path. Jersey media MOXy module depends on it.

[1] http://search.maven.org/#artifactdetails%7Corg.glassfish.jersey.ext%7Cjersey-entity-filtering%7C2.15%7Cjar

Comment by Michal Gajdos [ 10/Feb/15 ]

Closing as invalid. Feel free to reopen (or comment) if you think this is still an issue.





[JERSEY-2777] EntityFilteringFeature traps with NullPointerException when used with lazy JPA Parent/Child relation under EclipseLink Created: 07/Feb/15  Updated: 18/Feb/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Sascha_Baumeister Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: entity-filtering
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Ubuntu Gnome Linux 14.10
OpenJDK 1.8
mysql-connector 5.1.34 (connector-j)
eclipse-link 2.5.2
jersey 2.15
jersey-container-jdk-http 2.15
jersey-media-moxy 2.15
jersey-entity-filtering 2.15



 Comments   
Comment by Sascha_Baumeister [ 07/Feb/15 ]

I created a test model project with two JPA entities forming a parent/child relationship, with the parent side annotated using @ManyToOne(fetch = FetchType.LAZY, optional = false).

When running a test service that retrieves the child, it works as long as I leave out either the Jersey Entity Filtering feature, or EclipseLink's Dynamic Weaving feature (enabled by adding the VM-Argument "-javaagent:<libpath>/eclipselink.jar", preventing the fallback to EAGER relationship fetching).

However, once I enable both Entity Filtering and Dynamic Weaving the former traps with a NullPointerException, generating the following stack trace:
java.lang.NullPointerException
at org.glassfish.jersey.message.filtering.ObjectGraphImpl.getFields(ObjectGraphImpl.java:94)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.createSubgraphs(MoxyObjectProvider.java:128)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.createSubgraphs(MoxyObjectProvider.java:139)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.createSubgraphs(MoxyObjectProvider.java:115)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.createObjectGraph(MoxyObjectProvider.java:91)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.transform(MoxyObjectProvider.java:78)
at org.glassfish.jersey.moxy.internal.MoxyObjectProvider.transform(MoxyObjectProvider.java:63)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.createFilteringObject(AbstractObjectProvider.java:135)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:97)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:80)
at org.glassfish.jersey.moxy.json.internal.FilteringMoxyJsonProvider.preWriteTo(FilteringMoxyJsonProvider.java:80)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:858)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:85)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:662)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:418)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:408)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:306)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:316)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1073)
at org.glassfish.jersey.jdkhttp.JdkHttpHandlerContainer.handle(JdkHttpHandlerContainer.java:175)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:82)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:675)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

I'd like to add my test application consisting of two source+binary JARs, including a mysql schema creation script to this topic, but don't know how to ...

Comment by Sascha_Baumeister [ 07/Feb/15 ]

As there seems to be no way to add the JARs as binaries, I decided to add the relevant sources so you can recreate the problem:

==========================
bug-model-jar:
==========================

package de.bug.model;
import javax.persistence.*;
import javax.xml.bind.annotation.*;
@XmlType
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@Entity
@Table(schema = "bug", name = "Child")
public class Child {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private final long identity;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "parentReference", nullable = false, updatable = false)
private final Parent parent;

@Column(nullable = true, updatable = true, length = 63)
private volatile String name;

protected Child ()

{ this.identity = 0; this.parent = null; }

public Child(String name, Parent parent)

{ this.identity = 0; this.parent = parent; this.name = name; }

@XmlElement
public long getIdentity ()

{ return this.identity; }

@XmlElement
public String getName() { return this.name; }

@XmlElement
public Parent getParent () { return this.parent; }
}



package de.bug.model;
import java.util.*;
import javax.persistence.*;
import javax.xml.bind.annotation.*;
@XmlType
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@Entity
@Table(schema = "bug", name = "Parent")
public class Parent {

@XmlElement
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private final long identity;

@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private final Set<Child> children;

@XmlElement
@Column(nullable = true, updatable = true, length = 63)
private volatile String name;

protected Parent () { this.identity = 0; this.children = new HashSet<>(); }

public Parent (final String name) { this.identity = 0; this.children = new HashSet<>(); this.name = name; }

@XmlElement
public long getIdentity () { return this.identity; }

@XmlElement
public String getName()

{ return this.name; }

public Set<Child> getChildren ()

{ return this.children; }

}

File /META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="bug" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<!-- non-jta-data-source>JNDI-name in Java EE</non-jta-data-source -->

<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>

<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
</persistence-unit>
</persistence>

File /META-INF/bug-mysql.sql
SET CHARACTER SET utf8;
DROP DATABASE IF EXISTS bug;
CREATE DATABASE bug CHARACTER SET utf8;
CREATE TABLE bug.Parent (
identity BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(63) NULL,
PRIMARY KEY (identity)
) ENGINE=InnoDB;
CREATE TABLE bug.Child (
identity BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(63) NULL,
parentReference BIGINT NOT NULL,
PRIMARY KEY (identity),
FOREIGN KEY (parentReference) REFERENCES bug.Parent (identity) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

==========================
bug-rest-jar:
==========================
package de.bug.rest;
import java.io.*;
import java.net.URI;
import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.message.filtering.EntityFilteringFeature;
import org.glassfish.jersey.moxy.json.MoxyJsonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import com.sun.net.httpserver.HttpServer;
public class ApplicationContainer {

static public void main (final String[] args) throws IOException {
final URI serviceURI = URI.create("http://localhost:8001/services");

final ResourceConfig configuration = new ResourceConfig();
configuration.packages("de.bug.rest");
configuration.register(MoxyJsonFeature.class);
configuration.register(EntityFilteringFeature.class);

final HttpServer server = JdkHttpServerFactory.createHttpServer(serviceURI, configuration);
try

{ System.out.format("HTTP server running on service address %s, enter \"quit\" to stop.\n", serviceURI); final BufferedReader charSource = new BufferedReader(new InputStreamReader(System.in)); while (!"quit".equals(charSource.readLine())); }

finally

{ server.stop(0); }

}
}

package de.bug.rest;
import java.util.logging.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class DetailedExceptionMapper implements ExceptionMapper<Throwable> {
public Response toResponse (final Throwable exception) {
final Response response = exception instanceof WebApplicationException
? ((WebApplicationException) exception).getResponse()
: Response.status(Status.INTERNAL_SERVER_ERROR).build();
if (response.getStatus() >= 400) {
for (Throwable throwable = exception; throwable != null; throwable = throwable.getCause())

{ Logger.getGlobal().log(Level.WARNING, throwable.getMessage(), throwable); }

}
return response;
}
}

package de.bug.rest;
import javax.persistence.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import de.bug.model.*;

@Path("bugs")
public class Service {

@GET
@Produces(

{ MediaType.APPLICATION_JSON }

)
public Child test () {
final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("bug");
try {
final EntityManager entityManager = entityManagerFactory.createEntityManager();
try

{ entityManager.getTransaction().begin(); Parent parent = new Parent("foo"); entityManager.persist(parent); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); Child child = new Child("bar", parent); entityManager.persist(child); entityManager.getTransaction().commit(); entityManager.clear(); entityManager.getTransaction().begin(); child = entityManager.find(Child.class, child.getIdentity()); parent = child.getParent(); entityManager.getTransaction().commit(); return child; }

finally

{ entityManager.close(); }

} finally

{ entityManagerFactory.close(); }

}
}

Comment by Michal Gajdos [ 18/Feb/15 ]

Thank you for the test-case. Moving to backlog for now.





[JERSEY-2776] Regression -Multipart/form-data POST having a quoted boundary parameter in the Content-Type header fails. Created: 07/Feb/15  Updated: 24/Feb/15  Resolved: 24/Feb/15

Status: Resolved
Project: jersey
Component/s: media
Affects Version/s: 2.15
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: jontejj Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: 0 minutes
Time Spent: Not Specified
Original Estimate: 0 minutes

Attachments: HTML File does_not_work_but_is_valid    
Issue Links:
Cloners
clones JERSEY-1420 CLONE -Multipart/form-data POST havin... Resolved
Tags: boundary, jersey, multipart, pull-request, quoted

 Description   

Jersey returns HTTP status 400 when POST-ing a multipart/form-data having a quoted boundary parameter in the Content-Type header:
Content-Type: multipart/form-data;boundary="MrmiiyyJEqRYcIJyun5tMVIz70NuQ_nfD"
and use MrmiiyyJEqRYcIJyun5tMVIz70NuQ_nfD (without quotes) to separate the parts.

Use com.sun.jersey.spi.spring.container.servlet.SpringServlet.
Exception is thrown in jersey class com.sun.jersey.multipart.impl.MultiPartReaderClientSide, method readMultiPart. (org.jvnet.mimepull.MIMEParsingException: Missing start boundary).

RFC2046 states that quoted boundary values are permitted (http://www.ietf.org/rfc/rfc2046.txt):
"
WARNING TO IMPLEMENTORS: The grammar for parameters on the Content-
type field is such that it is often necessary to enclose the boundary
parameter values in quotes on the Content-type line. This is not
always necessary, but never hurts. Implementors should be sure to
study the grammar carefully in order to avoid producing invalid
Content-type fields. Thus, a typical "multipart" Content-Type header
field might look like this:
Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p

But the following is not valid:
Content-Type: multipart/mixed; boundary=gc0pJq0M:08jU534c0p
(because of the colon) and must instead be represented as
Content-Type: multipart/mixed; boundary="gc0pJq0M:08jU534c0p"
".



 Comments   
Comment by jontejj [ 07/Feb/15 ]

This affects version 2.15 (I don't have rights to edit fields).
My suggested fix is to:

mediaType = unquoteMediaTypeParameters(mediaType, "boundary");

protected static MediaType unquoteMediaTypeParameters(final MediaType mediaType, final String... parameters) {
if (parameters == null || parameters.length == 0)

{ return mediaType; }

final HashMap<String, String> unquotedParams = new HashMap<String, String>(mediaType.getParameters());

for (final String parameterName : parameters) {
String parameterValue = mediaType.getParameters().get(parameterName);

if (parameterValue.startsWith("\""))

{ parameterValue = parameterValue.substring(1, parameterValue.length() - 1); unquotedParams.put(parameterName, parameterValue); }

}

return new MediaType(mediaType.getType(), mediaType.getSubtype(), unquotedParams);
}

Like MultiPartReaderClientSide looks like in com.sun.jersey.contribs/jersey-multipart/1.15. I'll send a PR to github.

Comment by jontejj [ 09/Feb/15 ]

Pull request: https://github.com/jersey/jersey/pull/143





[JERSEY-2775] Server-Sent Events - write to broken connection does not throw exception Created: 06/Feb/15  Updated: 18/Feb/15

Status: Open
Project: jersey
Component/s: media
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: ricb Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: sse
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Tomcat 7.0.53, RHEL 6.


Tags: sse

 Description   

We are using Server-Sent Events to allow our client application to listen to events raised by our Jersey server. This works great.

We have a requirement for our server to have an accurate list of currently-connected SSE callers (instances of our client application). To this end, our server sends a tiny message to each client (via eventOutput.write) once every five seconds. If our client is shut down while SSE-connected, or if the remote computer is powered off while SSE-connected, our server's eventOutput.write call correctly throws the ClientAbortException/SocketException exception shown below. That's perfect: we catch the exception, and mark that client as no longer connected.

The problem: there are two cases where calling eventOutput.write to a no-longer-connected computer does NOT throw an exception: 1) if the Ethernet cable of the remote computer is disconnected while the client is SSE-connected, and 2) if the network adapter in the remote computer is turned off (e.g., by an administrator) while the client is SSE-connected. In these two cases, eventOutput.write does not throw an exception. We can call eventOutput.write to the remote computer every five seconds for hours and no exception is thrown. This makes it impossible to detect that the remote computer is no longer connected.

To sum up, there are four cases:

1) Client software is shut down: eventOutput.write() correctly throws an exception.
2) Computer running client software is powered down: eventOutput.write() correctly throws an exception.
3) Etherhet cable is disconnected from computer running client software: eventOutput.write does not detect broken connection.
4) Network adapter on computer running client software is turned off: eventOutput.write does not detect broken connection.

Here is the (good/useful) exception we get in cases where eventOutput.write DOES throw the exception we want:

org.apache.catalina.connector.ClientAbortException: null
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:371) ~[catalina.jar:7.0.53]
    at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:333) ~[catalina.jar:7.0.53]
    at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:101) ~[catalina.jar:7.0.53]
    at org.glassfish.jersey.servlet.internal.ResponseWriter$NonCloseableOutputStreamWrapper.flush(ResponseWriter.java:303) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.message.internal.CommittingOutputStream.flush(CommittingOutputStream.java:292) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.server.ChunkedOutput$1.call(ChunkedOutput.java:240) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.server.ChunkedOutput$1.call(ChunkedOutput.java:190) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:242) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:347) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.server.ChunkedOutput.flushQueue(ChunkedOutput.java:190) ~[jaxrs-ri-2.13.jar:2.13.]
    at org.glassfish.jersey.server.ChunkedOutput.write(ChunkedOutput.java:180) ~[jaxrs-ri-2.13.jar:2.13.]
    at com.appserver.webservice.AgentSsePollingManager$ConnectionChecker.run(AgentSsePollingManager.java:174) ~[AgentSsePollingManager$ConnectionChecker.class:na]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_71]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) [na:1.7.0_71]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) [na:1.7.0_71]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.7.0_71]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_71]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_71]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_71]
Caused by: java.net.SocketException: Broken pipe
    at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.7.0_71]
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113) ~[na:1.7.0_71]
    at java.net.SocketOutputStream.write(SocketOutputStream.java:159) ~[na:1.7.0_71]
    at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215) ~[tomcat-coyote.jar:7.0.53]
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480) ~[tomcat-coyote.jar:7.0.53]
    at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:119) ~[tomcat-coyote.jar:7.0.53]
    at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:799) ~[tomcat-coyote.jar:7.0.53]
    at org.apache.coyote.Response.action(Response.java:174) ~[tomcat-coyote.jar:7.0.53]
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:366) ~[catalina.jar:7.0.53]
    ... 19 common frames omitted





[JERSEY-2773] Annotated CDI beans not detected while injecting into Jersey resource Created: 03/Feb/15  Updated: 10/Feb/15  Resolved: 10/Feb/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.13
Fix Version/s: None

Type: Bug Priority: Major
Reporter: xwibao Assignee: Unassigned
Resolution: Works as designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Oracle JDK 1.8.0_31
GlassFish v4.1 b13 nightly 12-15-2014



 Description   

If we create an annotated CDI bean (ex., @RequestScoped), and try to inject it into a resource class, this will fail:

Only injection into resource classes fails; injection into servlets or EJBs works OK. Removing bean-discovery-mode, or setting it to "all", or using CDI 1.0 descriptor (xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd") makes injection work.

Please see this gist. It was created by some other guy, but it reproduces the bug perfectly.

Also tested in WildFly 8.2 (works OK).



 Comments   
Comment by Jakub Podlesak [ 10/Feb/15 ]

The GenericResource from the test case app would be injected all right if it was turned into a contextual CDI bean (i.e. by attaching @RequestScoped annotation to it). Current config is a bit vague, as based on selected discovery mode the GenericResource is either a dependent bean or CDI unmanaged component. In either case, it is not clear how Jersey should treat it.

To make it short: clearly specify scope of the GenericResource bean, and Jersey will handle it and inject just right.

Resolving as "Works as designed". Please feel free to re-open if you think otherwise.





[JERSEY-2772] Tomcat memory leak on undeploy Created: 03/Feb/15  Updated: 03/Apr/15

Status: Reopened
Project: jersey
Component/s: None
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: kilian.koller Assignee: Adam Lindenthal
Resolution: Unresolved Votes: 1
Labels: hk2, memory-leak
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Tomcat 8.0.18


Issue Links:
Duplicate
duplicates HK2-247 Tomcat memory leak on undeploy Closed

 Description   

On undeploy, I get the following errors. Any idea?

03-Feb-2015 08:48:14.362 SEVERE [http-nio-8080-exec-62] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jboss.netty.util.CharsetUtil$2] (value [org.jboss.netty.util.CharsetUtil$2@ecfacab]) and a value of type [java.util.IdentityHashMap] (value [{UTF-8=sun.nio.cs.UTF_8$Decoder@3b8a17a9}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
03-Feb-2015 08:48:14.362 SEVERE [http-nio-8080-exec-62] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jboss.netty.util.CharsetUtil$2] (value [org.jboss.netty.util.CharsetUtil$2@ecfacab]) and a value of type [java.util.IdentityHashMap] (value [{UTF-8=sun.nio.cs.UTF_8$Decoder@515aa672}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
03-Feb-2015 08:48:14.362 SEVERE [http-nio-8080-exec-62] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jboss.netty.util.CharsetUtil$2] (value [org.jboss.netty.util.CharsetUtil$2@ecfacab]) and a value of type [java.util.IdentityHashMap] (value [{UTF-8=sun.nio.cs.UTF_8$Decoder@26d65908}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
03-Feb-2015 08:48:14.362 SEVERE [http-nio-8080-exec-62] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [com.codahale.metrics.ThreadLocalRandom$1] (value [com.codahale.metrics.ThreadLocalRandom$1@558f138d]) and a value of type [com.codahale.metrics.ThreadLocalRandom] (value [com.codahale.metrics.ThreadLocalRandom@3ed371ca]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
03-Feb-2015 08:48:14.362 SEVERE [http-nio-8080-exec-62] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jboss.netty.util.CharsetUtil$2] (value [org.jboss.netty.util.CharsetUtil$2@ecfacab]) and a value of type [java.util.IdentityHashMap] (value [{UTF-8=sun.nio.cs.UTF_8$Decoder@3abe2954}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
03-Feb-2015 08:48:14.882 INFO [http-nio-8080-exec-62] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/v1]


 Comments   
Comment by kilian.koller [ 03/Feb/15 ]

Sorry, wrong errors pasted. See these:

03-Feb-2015 09:12:30.472 SEVERE [http-nio-8080-exec-75] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$3] (value [org.jvnet.hk2.internal.Utilities$3@3705b919]) and a value of type [java.util.WeakHashMap] (value [{public org.glassfish.jersey.message.internal.XmlJaxbElementProvider$General(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@590e679e, public org.glassfish.jersey.server.internal.inject.BeanParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@68aa64d0, private javax.ws.rs.container.ResourceContext org.glassfish.jersey.server.model.internal.VoidVoidDispatcherProvider.resourceContext=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@646fa434, private javax.inject.Provider org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.request=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@7e3814d1, private org.glassfish.jersey.server.model.internal.ResourceMethodDispatcherFactory org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder.dispatcherProviderFactory=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5420ae1f, public org.glassfish.jersey.server.internal.inject.HeaderParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6f97dcaf, private org.glassfish.jersey.process.internal.RequestScope org.glassfish.jersey.server.ServerRuntime$Builder.requestScope=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@76c08b6d, public org.glassfish.jersey.message.internal.SourceProvider$SourceWriter(org.glassfish.hk2.api.Factory,org.glassfish.hk2.api.Factory)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@486097f8, public org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider$General(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@19e188bd, public org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider$App(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@48c25d8a, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider.serviceLocator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3aab2c1c, protected javax.ws.rs.ext.Providers com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider._providers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@76b8b3e6, private javax.inject.Provider org.glassfish.jersey.internal.JaxrsProviders.workers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@630979ec, public org.glassfish.jersey.server.internal.RuntimeExecutorsBinder$BackgroundSchedulerFactory(org.glassfish.jersey.spi.RuntimeThreadProvider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@397d560a, public org.glassfish.jersey.server.internal.inject.FormParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5a5556f5, private javax.inject.Provider org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory.request=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@69c1e9da, org.glassfish.jersey.server.internal.JerseyResourceContext(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@412f3b17, public org.glassfish.jersey.server.internal.inject.AsyncResponseValueFactoryProvider(javax.inject.Provider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@1231f83e, public org.glassfish.jersey.server.internal.inject.ParamConverters$AggregatedProvider(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@62a3f673, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.internal.inject.ParamInjectionResolver.locator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@44a5cc4, public org.glassfish.jersey.message.internal.XmlCollectionJaxbProvider$General(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3c8538d9, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.internal.inject.BeanParamValueFactoryProvider.locator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2168d77f, private javax.ws.rs.core.Configuration org.glassfish.jersey.server.ServerRuntime$Builder.configuration=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5c85bd4f, private javax.inject.Provider org.glassfish.jersey.server.validation.internal.ValidationExceptionMapper.request=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@aff6667, public org.glassfish.jersey.message.internal.XmlJaxbElementProvider$App(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@1f29c411, private org.glassfish.jersey.server.spi.ExternalRequestScope org.glassfish.jersey.server.ServerRuntime$Builder.externalRequestScope=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@781d3ba4, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder.locator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@9038e2d, private org.glassfish.jersey.spi.ExceptionMappers org.glassfish.jersey.server.ServerRuntime$Builder.exceptionMappers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@78be0d34, public org.glassfish.jersey.message.internal.SourceProvider$DomSourceReader(org.glassfish.hk2.api.Factory)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@29e6577e, private javax.ws.rs.core.Configuration org.glassfish.jersey.server.validation.internal.ValidationExceptionMapper.config=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@383799fd, org.glassfish.jersey.server.model.internal.ResourceMethodDispatcherFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2dd01a30, private javax.inject.Provider org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.containerRequestProvider=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@250f6513, private javax.inject.Provider org.glassfish.jersey.message.internal.DocumentProvider.tf=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3ec99b6b, private javax.inject.Provider org.glassfish.jersey.message.internal.DocumentProvider.dbf=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3a35053e, public org.glassfish.jersey.message.internal.XmlRootObjectJaxbProvider$App(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@179989d2, public org.glassfish.jersey.message.internal.XmlRootObjectJaxbProvider$Text(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@49e051cf, public org.glassfish.jersey.server.internal.routing.RuntimeModelBuilder(org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder,org.glassfish.hk2.api.ServiceLocator,org.glassfish.jersey.message.MessageBodyWorkers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3b00895b, private org.glassfish.jersey.process.internal.RequestExecutorFactory org.glassfish.jersey.server.ServerRuntime$Builder.asyncExecutorFactory=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@290e77f0, public org.glassfish.jersey.server.internal.inject.WebTargetValueFactoryProvider(org.glassfish.hk2.api.ServiceLocator,javax.ws.rs.core.Configuration)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@7202ac1a, public org.glassfish.jersey.message.internal.SourceProvider$SaxSourceReader(javax.inject.Provider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3927e5bc, private java.util.concurrent.ScheduledExecutorService org.glassfish.jersey.server.ServerRuntime$Builder.backgroundScheduler=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6d2f992, org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5cb9af4f, public org.glassfish.jersey.message.internal.XmlCollectionJaxbProvider$App(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3bbcbabe, public org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorFactory(org.glassfish.jersey.server.internal.inject.ParamConverterFactory)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3db0b270, public org.glassfish.jersey.server.internal.inject.DelegatedInjectionValueFactoryProvider(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2cbfc23d, public org.glassfish.jersey.server.internal.inject.QueryParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3dedd332, public org.glassfish.jersey.internal.ExceptionMapperFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@635ae77b, public org.glassfish.jersey.server.internal.inject.MatrixParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5bc1fa52, public org.glassfish.jersey.message.internal.XmlCollectionJaxbProvider$Text(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@9bd653d, private javax.inject.Provider org.glassfish.jersey.internal.JaxrsProviders.mappers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5a1a537b, public org.glassfish.jersey.server.internal.inject.PathParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6ecf167c, public void org.glassfish.jersey.message.internal.AbstractJaxbProvider.setConfiguration(javax.ws.rs.core.Configuration)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3a08629d, public org.glassfish.jersey.message.internal.XmlJaxbElementProvider$Text(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@587e6c6c, public org.glassfish.jersey.message.internal.XmlRootObjectJaxbProvider$General(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@50f76d93, private javax.inject.Provider org.glassfish.jersey.internal.JaxrsProviders.resolvers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@469ded07, private org.jvnet.hk2.internal.DynamicConfigurationServiceImpl(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@3f7873c3, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.internal.inject.ContextInjectionResolver.serviceLocator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@14ce754c, private javax.inject.Provider org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.validatorProvider=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@7fbe19b3, org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(org.glassfish.hk2.api.ClassAnalyzer,org.glassfish.hk2.api.IterableProvider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@56e22696, org.glassfish.jersey.server.internal.inject.ParamConverterFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2a78a1e2, public org.glassfish.jersey.server.ContainerMessageBodyWorkersInitializer(javax.inject.Provider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@4d7bd5f4, public org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider$Text(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@42072e69, org.glassfish.jersey.server.internal.inject.EntityParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@5966629, public org.glassfish.jersey.server.internal.process.ServerManagedAsyncExecutorFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6a0ea0c8, private org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder.invocationHandlerProviderFactory=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@79491c08, public org.glassfish.jersey.server.internal.inject.CookieParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@246012e, public org.glassfish.jersey.server.internal.inject.JaxbStringReaderProvider$RootElementProvider(javax.inject.Provider,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@34578861, public org.glassfish.jersey.message.internal.MessageBodyFactory(org.glassfish.hk2.api.ServiceLocator,javax.ws.rs.core.Configuration)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2bc076c3, org.glassfish.jersey.server.internal.process.ReferencesInitializer(org.glassfish.hk2.api.ServiceLocator,javax.inject.Provider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@1a5886ef, private javax.ws.rs.core.Configuration org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder.globalConfig=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@2825bbfb, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.ServerRuntime$Builder.locator=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@20392a1e}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

03-Feb-2015 09:12:30.472 SEVERE [http-nio-8080-exec-75] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@86736b4]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

03-Feb-2015 09:12:30.472 SEVERE [http-nio-8080-exec-75] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@56d6a6a9]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Comment by Michal Gajdos [ 03/Feb/15 ]

Does this happen only on Tomcat? Does it happen all the time you undeploy an application?

Comment by kilian.koller [ 03/Feb/15 ]

Hi,
it happens on every reload and undeploy and also on Tomcat 7.0.57. After undeploy, I can only kill Tomcat, stop won't work...

I don't have another application server to test...

Regards

Comment by Michal Gajdos [ 10/Feb/15 ]

Thanks for clarification. Moving to backlog for now.

Comment by Adam Lindenthal [ 25/Feb/15 ]

Hi, this should be drastically improved already (from Jersey 2.16 / hk2 2.4.0-b07 and above), but still present. Tomcat still log a warning and I can still see some memory leaking in profiler with repeated redeploys. I am communicating with hk2 guys and try to resolve this.

Comment by kilian.koller [ 26/Feb/15 ]

Thanks, yes, it's getting better, down to 3 messages now:

— Version 2.15

26-Feb-2015 09:12:59.884 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.884 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.885 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$3] (value [org.jvnet.hk2.internal.Utilities$3@59a0850e]) and a value of type [java.util.WeakHashMap] (value [{private javax.validation.Configuration org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.validationConfig=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@43b11fc, protected javax.ws.rs.core.SecurityContext com.treefin.srv.rest.resource.AbstractService.sc=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@30fce9ca, public org.glassfish.jersey.internal.ContextResolverFactory(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6fc07101, protected javax.servlet.ServletContext com.treefin.srv.rest.resource.AbstractService.servletContext=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@32150102, private javax.ws.rs.container.ResourceContext org.glassfish.jersey.server.validation.internal.InjectingConstraintValidatorFactory.resourceContext=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@6efd424d, protected com.treefin.srv.beans.CassandraConnection com.treefin.srv.rest.resource.AbstractService.cc=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@399844e1, private javax.ws.rs.core.Configuration org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.jaxRsConfig=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@55bc62aa, private javax.ws.rs.container.ResourceContext org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.resourceContext=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@4f3b740e, private javax.validation.ValidatorFactory org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.factory=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@4b50b88e, private javax.ws.rs.ext.Providers org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.providers=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@30945249, private javax.validation.Configuration org.glassfish.jersey.server.validation.internal.ValidationBinder$DefaultValidatorFactoryProvider.config=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@60bdfc3, protected org.glassfish.jersey.server.internal.process.ServerProcessingBinder$ContainerRequestFactory(javax.inject.Provider)=org.jvnet.hk2.internal.Utilities$SoftAnnotatedElementAnnotationInfo@12045008}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.885 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.apache.juli.OneLineFormatter$2] (value [org.apache.juli.OneLineFormatter$2@5cde0e0e]) and a value of type [org.apache.juli.DateFormatCache] (value [org.apache.juli.DateFormatCache@4eca19c6]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.885 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.apache.juli.OneLineFormatter$1] (value [org.apache.juli.OneLineFormatter$1@16e7221b]) and a value of type [org.apache.juli.OneLineFormatter$1$1] (value [{59=http-nio-8080-exec-9, 85=Cassandra Java Driver worker-0, 63=http-nio-8080-exec-11, 92=http-nio-8080-exec-17, 91=http-nio-8080-exec-16, 93=http-nio-8080-exec-18, 90=http-nio-8080-exec-15, 88=http-nio-8080-exec-13, 89=http-nio-8080-exec-14, 94=http-nio-8080-exec-19}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.885 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.886 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.886 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.886 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.886 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.887 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.887 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.887 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.887 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.887 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.888 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.888 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.888 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.FactoryCreator$1] (value [org.jvnet.hk2.internal.FactoryCreator$1@622acb2a]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:12:59.888 SEVERE [http-nio-8080-exec-11] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.Utilities$2] (value [org.jvnet.hk2.internal.Utilities$2@acab529]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

– Version 2.16

26-Feb-2015 09:15:31.913 SEVERE [http-nio-8080-exec-19] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.PerLocatorUtilities$1] (value [org.jvnet.hk2.internal.PerLocatorUtilities$1@64d714e]) and a value of type [java.util.WeakHashMap] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:15:31.913 SEVERE [http-nio-8080-exec-19] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.PerLocatorUtilities$2] (value [org.jvnet.hk2.internal.PerLocatorUtilities$2@68e71637]) and a value of type [java.util.WeakHashMap] (value [{private org.jvnet.hk2.internal.DynamicConfigurationServiceImpl(org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@7bb66949}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
26-Feb-2015 09:15:31.914 SEVERE [http-nio-8080-exec-19] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [v1] created a ThreadLocal with key of type [org.jvnet.hk2.internal.PerLocatorUtilities$2] (value [org.jvnet.hk2.internal.PerLocatorUtilities$2@35d0c8c6]) and a value of type [java.util.WeakHashMap] (value [{private javax.validation.Configuration org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.validationConfig=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@58fa0833, public org.glassfish.jersey.jaxb.internal.XmlRootObjectJaxbProvider$Text(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@87cebb5, public org.glassfish.jersey.server.internal.inject.BeanParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@40c837d2, private javax.ws.rs.container.ResourceContext org.glassfish.jersey.server.model.internal.VoidVoidDispatcherProvider.resourceContext=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@73ed51f5, private org.glassfish.jersey.server.model.internal.ResourceMethodDispatcherFactory org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder.dispatcherProviderFactory=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@7b5e642b, public org.glassfish.jersey.server.internal.inject.HeaderParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@149019b6, private org.glassfish.jersey.process.internal.RequestScope org.glassfish.jersey.server.ServerRuntime$Builder.requestScope=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@15e7ca51, public org.glassfish.jersey.jaxb.internal.XmlRootObjectJaxbProvider$App(org.glassfish.hk2.api.Factory,javax.ws.rs.ext.Providers)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@c1c53e1, public org.glassfish.jersey.message.internal.SourceProvider$SourceWriter(org.glassfish.hk2.api.Factory,org.glassfish.hk2.api.Factory)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@46b0175, private javax.ws.rs.container.ResourceContext org.glassfish.jersey.server.validation.internal.InjectingConstraintValidatorFactory.resourceContext=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@10a2e5e7, private org.glassfish.hk2.api.ServiceLocator org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider.serviceLocator=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@3b3c10e0, protected javax.ws.rs.ext.Providers com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider._providers=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@55d1cf3d, private javax.inject.Provider org.glassfish.jersey.internal.JaxrsProviders.workers=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@96d0c5b, public org.glassfish.jersey.server.internal.RuntimeExecutorsBinder$BackgroundSchedulerFactory(org.glassfish.jersey.spi.RuntimeThreadProvider)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@ee74d4c, private javax.ws.rs.core.Configuration org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.jaxRsConfig=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@5587f760, public org.glassfish.jersey.server.internal.inject.FormParamValueFactoryProvider(org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider,org.glassfish.hk2.api.ServiceLocator)=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@ef472ca, private javax.inject.Provider org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory.request=org.jvnet.hk2.internal.SoftAnnotatedElementAnnotationInfo@6f1ab89b, private javax.validation.ValidatorFactory org.glassfish.jersey.server.validation.internal.ValidationBinder$ConfiguredValidatorProvider.fa
Comment by Adam Lindenthal [ 27/Feb/15 ]

Hi, after some investigation, I delegated the issue to hk2.

Regards,
Adam

Comment by Adam Lindenthal [ 27/Feb/15 ]

Reopening until upgrading to the future fixed version of hk2.

Comment by bruno_cappoen [ 02/Apr/15 ]

Hi, i have the same issue. Do you have any new informations with hk2 ?

Thanks,

Bruno.

Comment by Adam Lindenthal [ 03/Apr/15 ]

Hi Bruno,

I assume you are using latest release, nut not latest snapshot.
The problem should resolve after you upgrade to Jersey 2.18, which is going to be released in around 1-2 weeks.
In the meantime, you can (at least for development) use the 2.18-SNAPSHOT version.

Regards,
Adam

Comment by bruno_cappoen [ 03/Apr/15 ]

Hi, yes you're right. It's not urgent. I will test the release 2.18.

Thanks.





[JERSEY-2771] Hard to customize freemarker configuration Created: 02/Feb/15  Updated: 23/Feb/15  Resolved: 23/Feb/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: 2.16
Fix Version/s: 2.17

Type: Improvement Priority: Minor
Reporter: jeffwilde Assignee: Michal Gajdos
Resolution: Fixed Votes: 0
Labels: mvc
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

While using the jersey-mvc-freemarker extension, I found it very difficult to customize the freemarker Configuration object that is instantiated within FreeMarkerViewProcess class.

It is possible to construct your own Configuration object and let HK2 resolve it, but some of the basic (and valuable within jersey) configuration is already tied-up within an anonymous Value<Configuration> class in the FreemarkerViewProcessor class. There's no way to reuse that Configuration setup code without duplicating it wholesale.

I propose that FreeMarkerViewProcessor should resolve a true factory instead of firectly requesting a freemarker Configuration object, that'll make it easier to override/extend the configuration mechanism. As a reference, this is how the mustache templating code currently works.



 Comments   
Comment by Michal Gajdos [ 03/Feb/15 ]

GitHub PR: https://github.com/jersey/jersey/pull/141





[JERSEY-2770] Cannot inject ContainerRequestContext in ContainerRequestfilter Created: 31/Jan/15  Updated: 02/Feb/15  Resolved: 02/Feb/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.14
Fix Version/s: None

Type: Bug Priority: Major
Reporter: phil-lift Assignee: Unassigned
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

oracle jdk 7_u71, tomcat 7.0.57, on Mac OSX yosemite



 Description   

Injection of field @Context ContainerRequestContext fails in ContainerRequestfilter fails on start up with : java.lang.IllegalStateException: Not inside a request scope.

It fails on startup of webapp, so I understand that must happen during initialization of the filter, and that during this phase it is are not in a request scope, so it is my impression that is should be injected as a proxy, as default initialization if there is any or default constructor won't access it.

It seems reasonable to inject *request* resources in a **request ** filter.

Tried: making the filter a @Singleton, using @Inject rather than @Context. Same issue.

Workaround for now :

@Inject
private ServiceLocator serviceLocator;
....
ContainerRequestContext containerRequestContext = serviceLocator.getService(ContainerRequestContext.class);

Complete stack

Jan 31, 2015 3:26:22 PM org.glassfish.jersey.internal.Errors logErrors
WARNING: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 3
java.lang.IllegalStateException: Not inside a request scope.
	at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:149)
	at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:156)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:116)
	at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:214)
	at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:237)
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.liftsession.rest.security.RestSecurityFilter errors were found
	at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:249)
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on com.liftsession.rest.security.RestSecurityFilter
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:389)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)


Jan 31, 2015 3:26:22 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
MultiException stack 1 of 3
java.lang.IllegalStateException: Not inside a request scope.
	at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:149)
	at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:156)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:116)
	at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:214)
	at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:237)
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.liftsession.rest.security.RestSecurityFilter errors were found
	at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:249)
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on com.liftsession.rest.security.RestSecurityFilter
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:389)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)

Jan 31, 2015 3:26:23 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /services threw load() exception
java.lang.IllegalStateException: Not inside a request scope.
	at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:149)
	at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:228)
	at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:156)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:116)
	at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:214)
	at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:237)
	at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360)
	at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
	at org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
	at org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
	at org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
	at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
	at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
	at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
	at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:674)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:450)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
	at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
	at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:315)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
	at javax.servlet.GenericServlet.init(GenericServlet.java:158)
	at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)


 Comments   
Comment by phil-lift [ 31/Jan/15 ]

I tried to get access to the ContainerRequestContext in a ContainerRequestfilter... as mentioned here

https://jersey.java.net/documentation/latest/security.html#d0e12010

16.1.1.2. Using Security Context in Container Request Filters

The SecurityContext can be directly retrieved from ContainerRequestContext via getSecurityContext() method. You can also replace the default SecurityContext in a request context with a custom one using the setSecurityContext(SecurityContext) method. If you set a custom SecurityContext instance in your ContainerRequestFilter, this security context instance will be used for injection into JAX-RS resource class fields.

If not using my workaround, how else am I supposed to gain access to ContainerRequestContext into a ContainerRequestFilter?

Maybe I am missing out on some core concepts.

Thanks

Comment by phil-lift [ 01/Feb/15 ]

I just realized the requestContext is the one and only param passed to the filter method....
Very stupid of me.

But still, anywhere else the ContainerRequestContext could be injected as proxy.

please close, and have a good laugh





[JERSEY-2769] LoggingFilter always truncates if message size is larger than 4096 Created: 30/Jan/15  Updated: 27/Mar/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: None
Fix Version/s: backlog

Type: Bug Priority: Minor
Reporter: akanto Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Related code in LoggingFilter.java:

```
private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) throws IOException {
if (!stream.markSupported())

{ stream = new BufferedInputStream(stream); }

stream.mark(maxEntitySize + 1);
final byte[] entity = new byte[maxEntitySize + 1];
final int entitySize = stream.read(entity);
b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
if (entitySize > maxEntitySize)

{ b.append("...more..."); }

b.append('\n');
stream.reset();
return stream;
}
```
The stream.read(entity) reads maximum of 8192 bytes in one go (entitySize will be maximum 4096) even if the entity array size is much more larger, therefore the logging output is truncated.



 Comments   
Comment by Michal Gajdos [ 02/Feb/15 ]

You can always set maxEntitySize (in constructor) to a number you find appropriate. I am not sure I follow your last sentence - can you be more specific what you mean by that?

Comment by akanto [ 02/Feb/15 ]

Please ignore the 8192 above it was a mistake, it is 4096.

The maxEntitySize was 10000 in my tests, but the stream.read(entity) was able to read maximum of 4096 bytes from stream, although the stream itself contained more data. To make it easier to understand I have created a screenshot about the debug where you can see that the entity array length is 10001, but only 4096 bytes has been read:

I have tested it with Jersey 2.11, 2.15 and also with latest 2.16-SNAPSHOT, with the same result.

Comment by Michal Gajdos [ 02/Feb/15 ]

Oh, I see. Thanks. This happens when chunked transfer encoding is used and the entity doesn't come at once but in separated chunks. Do you encounter this on server or client (there might be a workaround on client)?

Comment by akanto [ 02/Feb/15 ]

I am using Jersey as client and I cannot have any influence on server. Please let me know whether some workaround might be applied on client side in this case? It is just about logging the rest of the message processing is perfect and I have no issues with it.

Thanks.

Comment by eripe970 [ 27/Mar/15 ]

I have the same issue. Fixed it temporary by a local workaround.





[JERSEY-2768] declarative linking traverses up the class hierarchy when used with bean validation Created: 30/Jan/15  Updated: 02/Feb/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: trombka1 Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Using the declarative linking and bean validation features together causes problems because the former traverses up the class hierarchy.

Here is a sample test case:
https://github.com/trombka/jersey-declarative-linking-and-validation

The code fails with ConcurrentModificationException. It happens because
org.glassfish.jersey.linking.FieldProcessor traverses through the database driver's (datastax in this case) classes!

This is the place with the problem

FieldProcessor:152

// Recursively process all member fields
for (FieldDescriptor member : instanceDescriptor.getNonLinkFields())

{ processMember(entity, resource, member.getFieldValue(instance), processed, uriInfo,rmc); }

This code uses reflection. When the entity is a collection as well. And if the collection is a guava proxy it can go totally out of its scope just like in case of List<ValidationError>.

public static List<ValidationError> constraintViolationToValidationErrors(final ConstraintViolationException violation) {
return Lists.transform(Lists.newArrayList(violation.getConstraintViolations()),
new Function<ConstraintViolation<?>, ValidationError>() {

@Override
public ValidationError apply(final ConstraintViolation<?> violation)

{ return new ValidationError( violation.getMessage(), violation.getMessageTemplate(), getViolationPath(violation), getViolationInvalidValue(violation.getInvalidValue()) ); }

});
}



 Comments   
Comment by trombka1 [ 30/Jan/15 ]

Patch: https://github.com/jersey/jersey/pull/139





[JERSEY-2767] @Path regexp too greedy Created: 29/Jan/15  Updated: 03/Feb/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.13
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: xwibao Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Oracle JDK 1.8.0_31
GlassFish v4.1 b13 nightly 12-15-2014



 Description   

Imagine we have the following REST resource. We want the @GET method handle URLs like both "/1" and "/1/foo", so we use a regexp in @Path:

    @GET
    @Path("/{id}{name: (/\\w+)?}")
    public String get(@PathParam("id") Long id, @PathParam("name") String name) {
        LOG.log(Level.INFO, "GET {0} {1}", new Object[]{id, name});
        return "Foo";
    }

    @DELETE
    @Path("/{id}")
    public void delete(@PathParam("id") Long id) {
        LOG.log(Level.INFO, "DELETE {0}", id);
    }

The @GET method works, but @DELETE gets broken (405 Method Not Allowed). Seems like @GET mapping shadows that of @DELETE, and the request is being routed to @GET handler despite HTTP method annotation.



 Comments   
Comment by xwibao [ 29/Jan/15 ]

Also tested on TomEE (CXF) and WildFly (RESTEasy) - works OK.

I've noticed some other minor differences:

  • if the optional part is present (ex. "/1/foo"), the "name" param value is:
    • TomEE: foo
    • GF: /foo
    • WF: /foo
  • if absent:
    • TomEE: null
    • GF: empty string
    • WF: empty string

If needed, I can supply a working NetBeans project (though I don't see how to attach files here)

Comment by Michal Gajdos [ 03/Feb/15 ]

Thank you for filing the issue, moving to backlog for now.





[JERSEY-2766] Adding Guice integration example Created: 29/Jan/15  Updated: 11/Mar/15  Resolved: 11/Mar/15

Status: Resolved
Project: jersey
Component/s: examples
Affects Version/s: 2.15
Fix Version/s: backlog

Type: New Feature Priority: Trivial
Reporter: TheIndifferent Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

https://github.com/jersey/jersey/pull/133
Pull request contains minimal web application based on Guice-Servlet module, and serving Jersey endpoints directly, without any additional third-party libraries.



 Comments   
Comment by Adam Lindenthal [ 29/Jan/15 ]

Hi Stanislav,

thanks! I will put the issue to our backlog now, until the pull request is reviewed and merged.

Regards,
Adam

Comment by Adam Lindenthal [ 11/Mar/15 ]

As discussed with Stanislav on github, this is going to be closed until new pull request is created. Then a new issue will be created or this one reopened.





[JERSEY-2765] Add support for bean validation groups Created: 29/Jan/15  Updated: 03/Feb/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.15
Fix Version/s: backlog

Type: New Feature Priority: Major
Reporter: brendan.doyle@intl.verizon.com Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: bean-validation
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Currently Jersey does not support bean validation groups, (see here )

Can this feature be considered ?



 Comments   
Comment by Michal Gajdos [ 03/Feb/15 ]

Hi Brendan,

thank you for your suggestion. We'd certainly like to have support for Bean Validation groups - I'll try to estimate the effort and based on that we'll consider implementing it (but I guess it won't be available very soon). If you were willing to contribute such support let me know, we can try to do this together.

In the meantime - moving to backlog.

Michal





[JERSEY-2764] Entity Filtering - Add support for XML (MOXy) Created: 28/Jan/15  Updated: 28/Jan/15

Status: Open
Project: jersey
Component/s: media
Affects Version/s: 2.3.1, 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Michal Gajdos
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: entity-filtering, xml

 Description   

XML (MOXy)

  • Add support for Entity Filtering.
  • Create Auto-discoverable.





[JERSEY-2763] @PathParam with commas to List<MyObject> Created: 25/Jan/15  Updated: 01/Apr/15  Resolved: 01/Apr/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.15
Fix Version/s: 2.17

Type: Bug Priority: Minor
Reporter: guillaume.l Assignee: Michal Gajdos
Resolution: Fixed Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I am trying to understand how the injections work for the variables annotated @PathParameter.

Regarding the injections of parameters in a list, seperated by a coma, I read the extract() method in CollectionExtractor class and your associated test in ParamConverterInternalTest, which returs a List of List.

When we call a simple webservice with the same pattern as your test ( http://.../resource/1,2,3 ), we would like a list of Object with 1,2 and 3 :

@Path("/resource")
public class AppWS {

    @GET
    @Path("/{params}")
    public Response get(@PathParam("params") List<MyObject> params) {
        return Response.status(200).entity("output").build();
    }
}

and

public class MyObject {
    Integer value;
    public MyObject(Integer value) {
        this.value = value;
    }
}

We write a specific ParamConverterProvider which splits the parameter (1,2,3) and return a ParamConverter<List<MyObject>>.

In the webservice class, when the ParamConverter is typed with an object class and therefore returns an object with this same type.

My issue is when the ParamConverter is typed with a List of Object, I expect the same type to be returned, which is not the case.

ie The value of the variable is a List of List of MyObject whereas I would like a List of MyObject.



 Comments   
Comment by Michal Gajdos [ 03/Feb/15 ]

Confirmed that this is a bug. Moving to backlog for now.

In the meantime there is a workaround - inject Collection<MyObject> into your resource method instead of List<MyObject> and update param converter provider accordingly.

Comment by guillaume.l [ 03/Feb/15 ]

Ok thanks, I will try it. Also, my workaround, I've created an object MyObjectList which extends ArrayList<MyObject>.

Comment by saadmufti [ 23/Feb/15 ]

I have similar case for @QueryParam, hopefully the two are related.

I have a QueryParam that is declared as List<Integer> and I want to oevrride the built in support for List which would require passing i something like

param=val1&parm=val2&......&param=valn

This gets quite long and rpepetitive given the limits on URL length, so I wanted to support

param=val1,val2,val3.....,valn

To do this, I wrote up a ParamConverterProvider and registered it, which looks at the passed in rawType and genericType to getConverter and res[ponds with an appropriate ParamConverter if rawType == List.class and if genericType instanceof ParameterizedType && genericType.getActualTypeArguments.length == 1 and genericType.getActualTypeArguments[0] == Integer.class .

The problem is at runtime Jersey never calls my ParamConverterProvider to decide how to handle List<Integer> and persists with the built in behavior, so the current implementation does not allow overriding the built in behavior for List<T> unless you use one of the workarounds mentioned above, like declaring the parameter to be Collection<T> or sub-classing ArrayList<T> with your own type, both of which are not ideal.

So hopefully the fix is the same both for this and the originally reported issue.

Thanks.





[JERSEY-2762] Support Declarative Linking Annotations on Methods Created: 23/Jan/15  Updated: 03/Feb/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: None
Fix Version/s: backlog

Type: Improvement Priority: Major
Reporter: rpeterson Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: declarative-linking, pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Currently the @InjectLink and the @InjectLinks annotations have a @Target that is limited to types (Field & Type). In cases where the response object is an interface, and specifically an interface that is represented as a Proxy instance, the annotations can't be used since there are no field declarations on an interface.

This is a request to full support the annotations when they appear on the "getters" within the interface (assuming a corresponding setter is available).



 Comments   
Comment by rpeterson [ 23/Jan/15 ]

Pull Request has been created at https://github.com/jersey/jersey/pull/137





[JERSEY-2761] ResourceConfig packages() does not work on Websphere 7 Created: 23/Jan/15  Updated: 30/Jan/15  Resolved: 28/Jan/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.5
Fix Version/s: 2.12

Type: Bug Priority: Major
Reporter: engrun Assignee: Michal Gajdos
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates JERSEY-2336 Support for META-INF/services discove... Resolved

 Description   

To get Jersey to work on WAS7, we have to register each resource explicitly, as packages('my.package.goes.here') does not work. That is, when using the ResourceConfig class.

The development team has structured the code like this

  • module1
  • application
  • webapp
  • othermodule

The "application" module contains all resources classes and config, whereas the "webapp" module only contains files under src/main/webapp.
So the resourcesclasses are packaged inside a jar in the lib folder when wrapping up the war file

Everything works fine on Tomcat and maven-jetty plugin when using the packages() method, however, all resources fails in WAS7 with a 404 - Not found error.

So might be related to classloaders/package scanning?



 Comments   
Comment by Michal Gajdos [ 28/Jan/15 ]

Seems like this issue duplicated JERSEY-2336 which has been fixed in version 2.12.

Comment by Michal Gajdos [ 28/Jan/15 ]

Closing issue as duplicate. If you have problems with WAS and Jersey 2.12+ feel free to reopen the issue.

Comment by engrun [ 30/Jan/15 ]

Thanks for the info
WAS 7 does not support java7, and if I have understood it correctly, Jersey version 2.7 and upwards are not compatible with Java6.

We'll stick to register each resource explicitly until we upgrade our WAS instance





[JERSEY-2760] TimeZones in DateProvider (via HttpDateFormat) can get corrupted Created: 20/Jan/15  Updated: 26/Jan/15  Resolved: 26/Jan/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 1.18.1, 2.15
Fix Version/s: 2.16

Type: Bug Priority: Critical
Reporter: stoicflame Assignee: Libor Kramolis
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Summary

I've been tracking down a pretty nasty issue that I've isolated to the HttpDateFormat. It boils down to the fact that the readDate method calls SimpleDateFormat.parse, which can result in a change to the timezone of the date format. If that happens, then all subsequent calls to format on that date format don't use GMT, but instead use the last timezone that was {{parse}}d. According to the HTTP spec, GMT must be used.

Suggested Fix

I suggest that the fix be applied at HttpDateFormat line 135: instead of immediately returning the result of f.parse(date), make a call to f.setTimeZone(GMT). The fix should be applied to both Jersey 1 and Jersey 2.

Additional Details

The bug surfaced because we were using Jersey client to read upstream responses which had invalid Last-Modified headers that used a timezone that wasn't GMT. (In my case, it was CEST.) Since both the Jersey client and the Jersey server used DateProviders which ultimately used the same HttpDateFormat, all subsequent responses from my service on that thread changed my Last-Modified headers to use CEST.

Test Case

It's pretty easy to write a test case that reproduces the problem:

    DateProvider dp = new DateProvider();
    Date now = new Date();
    assertTrue(dp.toString(now).endsWith("GMT"));
    Date lastModified = dp.fromString("Thu, 11 Sep 2014 22:30:06 CEST");
    assertTrue(dp.toString(now).endsWith("GMT")); //FAIL!!! (Should succeed)
{java}

 Comments   
Comment by Libor Kramolis [ 21/Jan/15 ]

Thanks for the report. Unfortunately SimpleDateFormat already has GMT time zone set.

Comment by Libor Kramolis [ 21/Jan/15 ]

Calling SimpleDateFormat.parse(...) can change it's time zone. It is necessary set before any use of SDF or reset after parsing String.





[JERSEY-2759] CDI scope mapping issue with singleton resources Created: 19/Jan/15  Updated: 21/Jan/15  Resolved: 19/Jan/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: diorcety Assignee: Unassigned
Resolution: Works as designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The class com/sun/jersey/server/impl/cdi/CDIComponentProviderFactory.java may returns a object of type
com.sun.jersey.core.spi.component.ioc.IoCFullyManagedComponentProvider
with getScope return a mapping of CDI scope to jersey ones.
The issue is that this behaviour avoid to inject @RequestScoped field into a @Singleton(jersey on) class. This restriction may be valid with jersey injection but with cdi, the inject objects are proxy, and this behaviour is allowed



 Comments   
Comment by Jakub Podlesak [ 19/Jan/15 ]

Things work as designed here IIUC. But maybe
i do not understand the use case.

As you pointed out, injecting request scoped CDI beans into application scoped CDI beans works just fine. The aim of Jersey 1.x CDI support
is to fulfil JAX-RS requirement to allow CDI beans to work as JAX-RS
components.

Please feel free to re-open or ask this to be re-opened, given you provided
a reproducible test case. Thanks for understanding.

Comment by diorcety [ 19/Jan/15 ]

I didn't mean CDI bean in CDI bean .. here a short example

@javax.enterprise.context.RequestScoped
public MyService {
}

@ManagedBean
@com.sun.jersey.spi.resource.Singleton
public class MyResource {
@InjectParam
private MyService myService;
}
Comment by Jakub Podlesak [ 19/Jan/15 ]

Could you please elaborate? I need a bit more realistic use case. What do you want to achieve?
I do not see any other Jersey annotations than @Singleton and @InjectParam.

The @ManagedBean annotation on MyResource class is misleading. You wanted Jersey singleton, right?
Shall it be a JAX-RS resource class? Could you please explain?

Comment by diorcety [ 19/Jan/15 ]

If i take com.sun.jersey.samples.jersey_cdi.resources.JCDIBeanDependentSingletonResource and add one field

private @InjectParam FormBean pfb;

It will not work. Because as FormBean is a @RequestScoped bean the ResourceComponentProvider#getScope will return ComponentScope.PerRequest( see com/sun/jersey/server/impl/cdi/CDIComponentProviderFactory.java:179).
As the scope equals ComponentScope.PerRequest the injectable factory will return null (com/sun/jersey/server/impl/application/WebApplicationImpl.java:1004)
The injectable factory behaviour is good, the CDI ComponentProviderFactory seems correct too. But as CDI returns a proxy for RequestScope and SessionScope, these proxy can be handled as singleton bean and could be put in a singleton resource like JCDIBeanDependentSingletonResource
It's not a really a bug, but a serious restriction and that avoid to create singleton resource for this case

Comment by Jakub Podlesak [ 20/Jan/15 ]

For that you could utilise CDI @ApplicationScoped contextual bean and have the dynamic proxy injected via CDI directly using javax.inject.Inject. Would not that work for you?

Comment by diorcety [ 21/Jan/15 ]

Yes that should work. But with my way, shouldn't be working too?





[JERSEY-2758] Add support for nested generics to ConfigurableMoxyJsonProvider Created: 19/Jan/15  Updated: 28/Jan/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: None
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: lasselassi Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When using Moxy to generate JSON responses, types with nested generics (e.g. Collection<TypeA<TybeB>>) do not work, leading to an error being logged:

ERROR [main] MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.Collection<foo.TypeA<foo.TypeB>>. (at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:245))

This is a known Moxy issue with nested generics which has unfortunately been unresolved since July 2013: https://bugs.eclipse.org/bugs/show_bug.cgi?id=413809

I suspected issue JERSEY-2443 might be caused by the same problem.

We have successfully fixed this problem in production with a patched version of ConfigurableMoxyJsonProvider overwriting MOXyJsonProvider::getDomainClass, as described in the original Moxy issue (comment #2). This way there is no need to wait for this issue to be fixed in Moxy.

I have created a pull request: https://github.com/jersey/jersey/pull/134



 Comments   
Comment by Libor Kramolis [ 19/Jan/15 ]

Signed OCA submitted to 'oracle-ca_us@oracle.com' by Lasse. Waiting for confirmation by Oracle.

Comment by Libor Kramolis [ 28/Jan/15 ]

OCA confirmed.





[JERSEY-2757] Invoke Dynamic Proxy Client with Custom Content-Type Created: 16/Jan/15  Updated: 10/Feb/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.15
Fix Version/s: backlog

Type: New Feature Priority: Major
Reporter: elmar-schwarz Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

any



 Description   

We need a mechanism to invoke a dynamic client proxy with a specific content-type which is not necessarily identical with the first value in the “@Comsumes” annotation. In analogy, providing a custom “Accept”-Header is already working.

The provided piece of code in pull request https://github.com/jersey/jersey/pull/136 solves the problem for us. It could be considerable to try to match the header-value against the list of consumed content-types of the actual service, but for several reasons we decided to use the provided header without validating it. We left it to the service to make the final decision to accept the content-type or not.



 Comments   
Comment by Adam Lindenthal [ 16/Jan/15 ]

Thank you for creating the issue and the pull request. We will wait, until OCA is officially listed on the OCA page and then review and eventually merge your commits.

Cheers,
Adam

Comment by Libor Kramolis [ 19/Jan/15 ]

Signed OCA submitted to 'oracle-ca_us@oracle.com' by Elmar. Waiting for confirmation by Oracle.

Comment by elmar-schwarz [ 10/Feb/15 ]

OCA confirmed





[JERSEY-2756] @FormParam Resource Argument Uses Query String Parameters when Form Argument Absent Created: 14/Jan/15  Updated: 15/Jan/15  Resolved: 15/Jan/15

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 2.14
Fix Version/s: None

Type: Bug Priority: Major
Reporter: apjoseph Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

spring tomcat/jetty


Issue Links:
Duplicate
duplicates JERSEY-2637 sensitive params can be exposed in lo... Resolved

 Description   

If one issues the following request:

http://localhost/test/testQueryForm?testParam=abjectFailure

To the resource below:

@POST
@Consumes("application/x-www-form-urlencoded")
@Path("/testQueryForm")
public Response testQueryForm(@QueryParam("testParam") String testQueryParam, @FormParam("testParam") String testFormParam);

It results in dual values of "abjectFailure" for both testFormParam and testQueryParam if testParam is left out of the form.

In some instances this may be desired behavior, but there seems to be no global or resource local method that exists to require "strict" injection of parameters. Lack of strict injection logic could cause unnecessary instability in clients where someone has accidentally used a queryParameter in place of a formParameter should the resource later be changed to grab parameters directly from the form -rather than via annotation injection. Strict injection also helps prevent sensitive information (like passwords) from accidentally being written to server logs due to mistaken usage of queryParams (common error) -as any decently written API would notify the user that their credentials were incorrect or absent and thus nudge them towards discovering the error in their request.

The behavior currently exhibited is also inconsistent since a formParam cannot be used in place of a queryParam (nor can a header param be used in place of either)



 Comments   
Comment by Jakub Podlesak [ 15/Jan/15 ]

We need to come up with an option that would forbid consuming query parameters by forms. Detailed discussion on why things work as they work is included in the duplicated report.





[JERSEY-2755] JERSEY-1708: Implement sub-resource runtime model caching Created: 13/Jan/15  Updated: 13/Jan/15  Resolved: 13/Jan/15

Status: Closed
Project: jersey
Component/s: core
Affects Version/s: 2.14
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jakub Podlesak Assignee: Jakub Podlesak
Resolution: Invalid Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

https://java.net/jira/browse/JERSEY-1708

The caching should occur based on the run-time subresource instance Java type information and should provide a cache-entry ageing & configurable cache size to make sure the memory consumption by the cache is manageable.
should primarily work for class based subresources, ideally also for instance based subresources.



 Comments   
Comment by Jakub Podlesak [ 13/Jan/15 ]

wrong JIRA





[JERSEY-2754] JERSEY-2736: Impossible to define ConnectionReuseStrategy using ApacheConnector Created: 13/Jan/15  Updated: 13/Jan/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: None
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Jakub Podlesak Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

There is no way to define ConnectionReuseStrategy for Apache client (using ApacheConnector) through client config, and the fact that ApacheConnector is creating HttpClientBuilder with default value for boolean "systemProperties" (which is "false"), makes it impossible to use "http.keepAlive" system property.






[JERSEY-2753] UriBuilder should leave relative path relative Created: 13/Jan/15  Updated: 20/Jan/15  Resolved: 20/Jan/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 1.18.1, 2.14
Fix Version/s: 2.16

Type: Bug Priority: Major
Reporter: rdohna Assignee: Libor Kramolis
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   
    @Test
    public void jerseyUriBuilderShouldLeaveRelativePathRelative() {
        UriBuilder builder = UriBuilder.fromUri();
        builder.scheme("http");
        builder.replacePath("path");

        assertEquals("http:path", builder.build().toString());
    }

Throws:

org.junit.ComparisonFailure: expected:<http:[]path> but was:<http:[/]path>

The same test passes with Resteasy.



 Comments   
Comment by rdohna [ 13/Jan/15 ]

sorry: it should be UriBuilder builder = UriBuilder.fromUri("");... the empty string is missing. I actually used new UriBuilderImpl(); for 1.18.1, new JerseyUriBuilder(); for 2.14, and ResteasyUriBuilder.fromTemplate(""); for Resteasy.





Glassfish / Jersey throws NPE on startup of versioned app (JERSEY-2626)

[JERSEY-2752] This critical issue still exists Created: 13/Jan/15  Updated: 13/Jan/15

Status: Open
Project: jersey
Component/s: None
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Sub-task Priority: Critical
Reporter: lprimak Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Just trying to get someone to look at this issue again, as it's a critical issue
Thanks






[JERSEY-2751] Entity Filtering with MOXy doesn't work well for Maps Created: 11/Jan/15  Updated: 11/Jan/15

Status: Open
Project: jersey
Component/s: extensions
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: entity-filtering, moxy

 Description   

In case of Maps both keys and values have to be propagated into ObjectGraph, e.g. in a SubGraph the "key.HOME", "value.areaCode", "value.number" have to be present (take a look at entity-filtering-selectable example). This is not the case at the moment. It's possible that this change would require a change in APIs.

Question: How is map processing (and object graphs in particular) affected when a XmlAdapter is used on a Map field?






[JERSEY-2750] @RolesAllowed does not work in JettyHttpContainer Created: 09/Jan/15  Updated: 13/Jan/15  Resolved: 13/Jan/15

Status: Resolved
Project: jersey
Component/s: containers
Affects Version/s: None
Fix Version/s: 2.15

Type: Bug Priority: Major
Reporter: jbecicka2 Assignee: Jakub Podlesak
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

@RolesAllowed annotation forbids access to everything in JettyHttpContainer. I would say, that this is caused by wrong implementation of SecurityContext in JettyHttpContainer:

https://github.com/jersey/jersey/blob/2.14/containers/jetty-http/src/main/java/org/glassfish/jersey/jetty/JettyHttpContainer.java#L214

@Override
public boolean isUserInRole(final String role)

{ return false; }

It means, that user is not in any role. The fix seems to be trvial:

  • return false;
    + return request.isUserInRole(role);


 Comments   
Comment by jbecicka2 [ 09/Jan/15 ]

I'm sorry. JIRA somehow changed formatting.

Anyway the fix is (I would say) just return request.isUserInRole(role) instead of false.

Comment by Jakub Podlesak [ 13/Jan/15 ]

Fixed in the master branch.





[JERSEY-2749] RolesAllowedDynamicFeature and sub-resources Created: 07/Jan/15  Updated: 13/Jan/15

Status: Open
Project: jersey
Component/s: security
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: lmazuel Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi,
I try to use RolesAllowedDynamicFeature this way:

ViewResource.java
@Path("/view")
@RolesAllowed("myrole")
@Singleton
public class ViewResource {

    	@Path("/subresources")
	public Class<SubResource> subresources() {
		return SubResource.class;
	}
}
SubResource.java
@Singleton
public class SubResource

    /* My resources */
}

I have registered RolesAllowedDynamicFeature.

But the role is never applied. I try to debug, I have seen that the "subresources" method is never given to the "configure" method of RolesAllowedDynamicFeature. Then, there is no chance to register the "RolesAllowedRequestFilter" filter...

If I use my role directly in the subresource, all goes fine.






[JERSEY-2748] When running grizzly http server on z/OS, incoming JAX-RS based REST request URIs are incorrectly converted from UTF-8 to EBCDIC default charset and thus lead to HTTP 404 Created: 07/Jan/15  Updated: 15/Jan/15  Resolved: 15/Jan/15

Status: Resolved
Project: jersey
Component/s: None
Affects Version/s: 2.6
Fix Version/s: 2.16

Type: Bug Priority: Major
Reporter: reinhold.fuereder Assignee: Adam Lindenthal
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

z/OS, grizzly 2.3.6 http server with jersey 2.6 JAX-RS implementation



 Description   

From GRIZZLY-1726 which I filed for/in the wrong project according to @oleksiys:

In my environment (see above) URL requests (via curl) like this:

curl http://<zos hostname>:<port>/rse/mgmt/version -4

correctly comes in as ".../rse/mgmt/version" (UTF-8 I guess), before being converted to EBCDIC (cp1047) and thus no JAX-RS REST service is found for that weird characters and thus returns HTTP status code 404

I think the culprit code is one word/constant in
org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.getRequestUri(URI, Request):

    private URI getRequestUri(URI baseUri, Request grizzlyRequest) {
        // TODO: this is terrible, there must be a way to obtain the original request URI!
        String originalUri = UriBuilder
                .fromPath(
                        grizzlyRequest.getRequest().getRequestURIRef().getOriginalRequestURIBC()
                                .toString(Charsets.DEFAULT_CHARSET)).build().toString();
...

I think/claim, instead of Charsets.DEFAULT_CHARSET it should be Charsets.Charsets.UTF8_CHARSET (or even null to fallback to UTF-8). Because the incoming request URL from the request (buffer?) is already good as it is.

My follow-up comment:

Please note that I just tried/applied this mini change by patching my (old) grizzly jar ("jersey-container-grizzly2-http-2.6.jar") and it worked as expected...



 Comments   
Comment by oleksiys [ 07/Jan/15 ]

I think Charsets.ASCII_CHARSET should work for you, can you pls. try?

Comment by reinhold.fuereder [ 08/Jan/15 ]

Yes, I can: you are right, Charsets.ASCII_CHARSET also works as expected (so far...)


Of course in the original description I meant Charsets.UTF8_CHARSET instead of Charsets.Charsets.UTF8_CHARSET...

Comment by Adam Lindenthal [ 15/Jan/15 ]

Hi, thank you for submitting this and thanks Alex for the hint.
The change has been merged into master branch and the fix will be available in 2.16.

Regards,
Adam

Comment by oleksiys [ 15/Jan/15 ]

Thank you Adam!





[JERSEY-2747] Update Migration Guide Created: 05/Jan/15  Updated: 05/Jan/15

Status: Open
Project: jersey
Component/s: docs
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Improvement Priority: Major
Reporter: Michal Gajdos Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

By Guillaume Drouet:






[JERSEY-2746] RuntimeExceptions thrown by request filters do not propagate when using submit() with Futures. Created: 02/Jan/15  Updated: 13/Apr/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.13
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: mrandall_cerner_com Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: 1221
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The run() method in ClientRuntime.submit(...) invokes Stages.process(...) with no catch block for runtime exceptions. As a result, when a runtime exception is thrown in a filter, the submitted runnable dies. This throwable is never passed back to the response callback. This can leave to orphaned async processes, and wreaks havoc when attempting to troubleshoot bugs as the exceptions are swallowed.

Per 6.7.2 / 4.5.2 of the JAX-RS spec, the exception should be re-wrapped in a ProcessingException, and set as the failure in the corresponding response callback, which in turn will be re-wrapped in an ExecutionException per Invocation.submit()'s javadoc.






[JERSEY-2745] Package Scanning delimiter is inconsistent with spec. Created: 02/Jan/15  Updated: 28/Jan/15

Status: Open
Project: jersey
Component/s: core
Affects Version/s: 2.9, 2.14
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: martin.jamszolik Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Ubuntu 14.04
Tomcat on Oracle 1.7 JVM
Websphere 8.5.5.3 on 1.7 IBM JVM



 Description   

Here is the scenario:
We have the following packages that contain JAX-RS classes
com.bipt.tiva.rs
com.bipt.tiva.jaxrs
com.policyport.rs.open

However, see below how it's the only way we where able to have the scanning work in Webpshere 8.5 as described in web.xml

   <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.bipt.tiva.rs/,com.bipt.tiva.jaxrs/,com.policyport.rs.open/
            </param-value>
        </init-param>

Notice the forward slash before "comma" as the delimiter. That's the only way. We tried ";" "empty space","\n" as per spec but nothing else worked.

Fortunately, the "foward slash" still worked on tomcat, so for now we adopted the solution.

I am sure though that this is not intentional and is in fact a bug. Unless you guys can shed some light on this.



 Comments   
Comment by martin.jamszolik [ 02/Jan/15 ]

The full servlet configuration looks like this

<servlet> 
       <servlet-name>isf_rest_api_jersey2</servlet-name>
       <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>         
       <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.bipt.tiva.rs/,com.bipt.tiva.jaxrs/,com.policyport.rs.open/
            </param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.scanning.recursive</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.bipt.tiva.lib.JerseyISFApplication</param-value>
        </init-param>     
        <load-on-startup>2</load-on-startup>  
</servlet>   
Comment by brad103 [ 28/Jan/15 ]

I'm not sure if it's inconsistent with the spec, but it is inconsistent with IBM's interpretation of it.

From what I've seen, there's a classloader difference between Oracle Java and IBM Java which manifests in com.ibm.ws.classloader.CompoundClassLoader. In short,

  • org.glassfish.jersey.server.internal.scanning.PackageNamesScanner#init() asks the classloader for a base URI for a package
  • The class firsts converts the supplied package names from dot notation to slashes (eg my.pkg.here becomes my/pkg/here)
  • IBM's classloader will not return packages unless the path has a trailing slash (eg my/pkg/here - this is why the trailing slash worked in the example above)

There is some discussion that setting the JVM parameter com.ibm.ws.classloader.strict changes this behaviour to not need the trailing slash, but we haven't had any joy with that.

Our workaround is to use the same package descriptions as Martin described. Note we are using package scanning defined in a ResourceConfig class rather than web.xml, but the result is the same.

Refs:
http://code.google.com/p/reflections/issues/detail?id=158#c3
http://www-01.ibm.com/support/knowledgecenter/SSAW57_7.0.0/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/xrun_jvm.html?cp=SSAW57_7.0.0%2F3-16-5-448
https://blogs.oracle.com/bhaktimehta/entry/ibm_jdk_and_classloader_getresources (possibly related)

We're on WAS 8.5.0.1 and Java 7





[JERSEY-2744] @Resource injection doesn't work when Jersey & CDI are used in standalone mode Created: 01/Jan/15  Updated: 14/Jan/15

Status: Open
Project: jersey
Component/s: containers
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

See PerApplicationBeanTest in cdi-webapp example. @Resource injection will not work on SE, need to add a custom extension to make this work with Grizzly.



 Comments   
Comment by Adam Lindenthal [ 14/Jan/15 ]

Moving to backlog.





[JERSEY-2743] Jersey Async Client doesn't work with Jetty connector (jetty client >= 9.1.4.v20140401) Created: 01/Jan/15  Updated: 13/Jan/15

Status: Open
Project: jersey
Component/s: connectors
Affects Version/s: 2.14
Fix Version/s: backlog

Type: Bug Priority: Major
Reporter: Michal Gajdos Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Fix for Bug 430808 affected jersey-jetty-connector in a way it can't process async requests anymore. Underlying OutputStreamContentProvider is locked/blocked after write (and flush) is called and never woken up.

TODO: Remove jetty-maven-plugin version in rx-client-java8-webapp example when this issue is fixed.






[JERSEY-2742] LoggingFilter's LoggingStream does not delegate flush() Created: 01/Jan/15  Updated: 14/Jan/15  Resolved: 14/Jan/15

Status: Resolved
Project: jersey