[JERSEY-749] LoggingFilter does not log JSON entities Created: 09/Aug/11  Updated: 28/Mar/15  Resolved: 23/Jul/13

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

Type: Bug Priority: Major
Reporter: Francisco A. Lozano Assignee: Jakub Podlesak
Resolution: Won't Fix Votes: 4
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Java 1.6, Grizzly 1.9.27, Jackson 1.7.8



 Description   

I was using 1.5 and everything worked fine, I could see the JSON requests/responses going in and out.

Then I moved to 1.8 and it stopped working, the logger logs only the request and the headers but not the entities.

I've checked and it seems that it never passes from

if(in.available() > 0) {

I've copied the old Jersey 1.5 LoggingFilter to my source code tree (under a slightly different package name) and I can see again the JSON requests/responses perfectly logged.



 Comments   
Comment by Pavel Bucek [ 09/Aug/11 ]

can you share testcase?

That check was put there as a fix for another issue, so I'm a little reluctant to revert that change before I have a testcase which invalidates that change.

Comment by vguna [ 10/Apr/12 ]

Same here.

With Jersey 1.11, Tomcat 7 64bit, JDK 1.6.29 64bit. On my Windows7 PC, no logging for request entities work. just headers. Also debugged to the line mentioned in the initial post. For me it's always 0 - so no logging happens. If I read from the stream with a self-written MessageBodyReader after the LoggingFilter, I can output the request to the console without problems. So it has something todo with the available() implementation. It is the org.apache.catalina.connector.CoyoteInputStream and it returns 0. For sending requests I used soapUI 4.0.1 and the latest 4.5 version.

Funny thing: on my Ubuntu 10.04. Box (64bit, Tomcat 7 as well) for some requests it logs, for others not.

Hard to write a testcase for that. Maybe you can perform a quick check with the env specs given above.

For now I copy/pasted the 1.11'er LoggingFilter and reverted the changes of:

http://java.net/projects/jersey/sources/svn/diff/trunk/jersey/jersey-server/src/main/java/com/sun/jersey/api/container/filter/LoggingFilter.java?rev1=4834&rev2=4835

Comment by basalt79 [ 30/May/12 ]

Hi, I have the same problem like vguna.

The in.available() is called. if the application server is tomcat the InputStream is a org.apache.catalina.connector.CoyoteInputStream.

The org.apache.catalina.connector.InputBuffer available method will be called , but the state of this InputBuffer is still INITIAL_STATE and so the hock with ACTION_AVAILABLE will be called.
This action is not implemented in org.apache.coyote.http11.Http11Processor

So the only way to change the state is to call the realReadBytes method on InputBuffer.

I think the change has to be done in InputBuffer, because the available should also be set if the realReadBytes has not be called. because there is something to read and something to log.

So what was the issue you fixed with this in.available() if?

Tomcat Version Apache Tomcat/6.0.16
JVM Version 1.6.0_23-b05
JVM Vendor Sun Microsystems Inc.
OS Name Windows XP
OS Version 5.1
OS Architecture x86

Also tested with jetty and work fine.

Comment by increment1 [ 04/Feb/13 ]

I'm seeing this same issue with Jersey on Tomcat (but logs correctly on Jetty).

Pavel, can you comment on what issue that in.available() line was put in to fix, since I would like to create a filter without it but don't want to run into some unexpected issue.

Comment by increment1 [ 04/Feb/13 ]

For anyone else who is interested, I tracked down where/when/why the in.available() line was added to the LoggingFilter thus seemingly creating this particular issue with Tomcat (although I cannot comment on if this line is the actual cause and/or if the error is in Jersey or Tomcat):

summary: fixing container logging filter bug - timeout exception was produced when underlying connection was closed right after delivering entity-less response + re-enabling affected filter usages + fixed javadoc typo in ReaderWriter
revision: 4835
date: 2011-04-11 12:19:27 UTC (1 year)

http://java.net/projects/jersey/sources/svn/revision/4835

Comment by jose.cervera [ 12/Apr/13 ]

Also had this bug in Tomcat 7.0.35, JDK 1.7.0_07 Windows 32bits

For a quick workaround, and after seeing basalt79 comment, I changed the connector to HttpNioProtocol in Tomcat's server.xml:

<Connector port="80" protocol="org.apache.coyote.http11.Http11NioProtocol" ... />

The POST is now logged.

Regards.

Comment by Jakub Podlesak [ 23/Jul/13 ]

Resolving as won't fix as this seems to be only related to Tomcat and there is a known workaround.
I believe entity logging is needed for debug purpose only, and there the workaround should not hurt.
Please re-open, if you have strong objections.

Comment by quilleashm [ 30/Aug/13 ]

I would like to re-raise this please. We have observed using this setup

Jersey 1.17
Jetty 8.1.9

We always get the HTTP body for requests made within the same machine or machines within the same geographical area. However requests sent from a different country usually do not log the HTTP body. We have observed hitting the same server from two different locations where one logs correctly and the other does not, ruling out having the feature disabled.

My understanding of available() isn't perfect but I would imagine in any configuration it would be possible for the following to happen.

Client connects
Client renders HTTP headers
Client flushes
.. some time passes
Client renders HTTP body
Client flushes

Then the server would get

Incoming connection
Headers received
.. some time passes
Body received

If ContainerRequestFilters are fired once the headers are available but before the body has been received then available would return 0. Because of the available check the LoggingFilter does not wait for the body data and prints nothing. However if part/all of the body has been recieved (available returns > 0) then the filter reads until end-of-stream before logging.

I do not know the Jetty/Jersey internals but if neither of them ensure a complete request is available before filters are fired I could see this being possible.

Please let me know if you need any more information. Very difficult to provide a test case due to the intermittent nature of the problem.

Comment by jagathvijayan [ 16/May/14 ]

Using NIO connector as a workaround may not work for everyone. In some cases, we need to use BIO connector. So, please revert the change to in.available() > 0 and fix this issue.

Comment by dennisgermany [ 27/Oct/14 ]

We are using Tomcat 7 and Jersey 1.17 and cannot change the connector. We also vote for reopening. Thanks!

Comment by zeiss [ 20/Nov/14 ]

The same problem exists with com.sun.net.httpserver.HttpServer and Jersey 1.18.1, so it is not Tomcat-ony. Please reopen the issue.

Comment by luisjotapepe [ 28/Mar/15 ]

please open this. we are using 1.17 and even in 1.19 with Glassfish 3 and doesn't work! You can see that this is an important issue as many of us are looking for a legitimate solution. Thank you in advance.





[JERSEY-2645] jersey-proxy-client does not set accept header based on @Produces Created: 11/Sep/14  Updated: 27/Mar/15

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

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


 Description   

jersey-proxy-client appears to contain functionality to set the accept header in the request from the @Produces annotation. However, the accept header is not set.

I suspect that this is due to a bug in the class WebResourceFactory, where the accept header set in line 299 is overwritten again in line 305 when the other headers are set.

Testcase to reproduce:

public class AcceptTest {

	public static interface TestInterface {
		@GET
		@Produces(MediaType.TEXT_PLAIN)
		String testMethod();
	}
	
	@Test
	public void test() {
		Client client = ClientBuilder.newClient(new ClientConfig());
		ClientRequestFilter filter = new ClientRequestFilter() {
			@Override
			public void filter(ClientRequestContext requestContext) throws IOException {
				assertEquals(MediaType.TEXT_PLAIN, requestContext.getHeaderString(HttpHeaders.ACCEPT));
				requestContext.abortWith(Response.status(200).build());
			}
		};
		client.register(filter);
		
		WebTarget target = client.target("http://localhost");
		
		MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
		headers.putSingle(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN);
		
		TestInterface proxy = WebResourceFactory.newResource(TestInterface.class, target);
		proxy.testMethod();
		
	}


 Comments   
Comment by wimmelg [ 11/Sep/14 ]

PS: in the test case, the two lines that construct the "headers" map explicitly with the Accept header are unnecessary. Resp., they make the test run successfully if the headers map is passed to WebResourceFactory.newResource() on initialization of the proxy (as a possible workaround).

Comment by Adam Lindenthal [ 10/Oct/14 ]

Hi wimmelg,

thanks for creating the issue and submitting the test case.
I will move it to backlog now, so that we can get back to it once its planned for some sprint.

Thanks,
Adam

Comment by ShawnClark [ 27/Mar/15 ]

I ran into a similar issue to this. I found that the problem was in the WebResourceFactory. It was overwriting the accept header while creating the Invocation.Builder. I then found this bug JERSEY-2696 that shows that the issue has been resolved in 2.14.





[JERSEY-2831] Unable to parse wald.xsd schemas with newer jaxb plugin Created: 27/Mar/15  Updated: 27/Mar/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: None
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





[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-2830] Memory leak when of response.readEntity when using JAX-RS Client API Created: 27/Mar/15  Updated: 27/Mar/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	
	...





[JERSEY-2829] javax.ws.rs.core.Response#readEntity sometimes returns an empty string, if hasEntity() is called first Created: 26/Mar/15  Updated: 26/Mar/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.






[JERSEY-2626] Glassfish / Jersey throws NPE on startup of versioned app Created: 24/Aug/14  Updated: 24/Mar/15

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

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

Initiating Jersey application, version Jersey: 2.10.4 2014-08-08 15:09:00…]]
Glassfish 4.1 promoted build downloaded August 20th, 2014


Issue Links:
Cloners
is cloned by JERSEY-2629 CLONE - Glassfish / Jersey throws NPE... Closed
Duplicate
is duplicated by JERSEY-2807 Glassfish / Jersey throws NPE on star... Resolved
Sub-Tasks:
Key
Summary
Type
Status
Assignee
JERSEY-2752 This critical issue still exists Sub-task Open  
Tags: jersey

 Description   

Application fails to start in a Availability-enabled clustered environment.
The application works in the same domain when not deployed in a cluster.

Here is the NPE:

[2014-08-24T05:28:38.406-0400] [glassfish 4.1] [INFO] [] [org.glassfish.jersey.server.ApplicationHandler] [tid: _ThreadID=18 _ThreadName=RunLevelControllerThread-1408872414218] [timeMillis: 1408872518406] [l
evelValue: 800] [[
Initiating Jersey application, version Jersey: 2.10.4 2014-08-08 15:09:00...]]

[2014-08-24T05:28:38.787-0400] [glassfish 4.1] [SEVERE] [] [javax.enterprise.web] [tid: _ThreadID=18 _ThreadName=RunLevelControllerThread-1408872414218] [timeMillis: 1408872518787] [levelValue: 1000] [[
WebModule[/stage]StandardWrapper.Throwable
java.lang.NullPointerException
at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.registerEjbInterceptor(EjbComponentProvider.java:169)
at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.bind(EjbComponentProvider.java:251)
at org.glassfish.jersey.server.ApplicationHandler.bindWithComponentProvider(ApplicationHandler.java:903)
at org.glassfish.jersey.server.ApplicationHandler.bindProvidersAndResources(ApplicationHandler.java:832)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:435)
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.server.ApplicationHandler.<init>(ApplicationHandler.java:285)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:310)
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:244)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:406)
at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:243)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:329)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:377)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:461)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:227)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:84)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2258)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1162)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1147)
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)



 Comments   
Comment by lprimak [ 24/Aug/14 ]

I believe (this is just a guess) this is due to my application named my_app:20140824
I think some parts of GF are broken with this naming convention now.
This is crucial for clusters as it supports hot-deployment.

I believe other parts of Glassfish are broken in regards to application versioning

Comment by lprimak [ 24/Aug/14 ]

Yup. This is confirmed. Same application runs fine when not versioned,
i.e. deployed as my_app as opposed to my_app:20140824
Application versioning is broken.

Comment by Jakub Podlesak [ 01/Sep/14 ]

This is probably related to how Jersey uses GF internal API to get EJB info. The issue should be reproducible
also in a standalone server deployment (no cluster needed IIUC).

            final EjbContainerUtil ejbUtil = EjbContainerUtilImpl.getInstance();
            final ApplicationInfo appInfo = ejbUtil.getDeployment().get((String)initialContext.lookup("java:app/AppName"));

Above we need to make sure the version suffix is trimmed out if present.

Comment by Jakub Podlesak [ 01/Sep/14 ]

Hmmm, new InitialContext().lookup("java:app/AppName") works fine, the problem is in getting application info, as there
apparently the version info is required.

Comment by Jakub Podlesak [ 02/Sep/14 ]

Here is a link to application versioning doc: http://docs.oracle.com/cd/E18930_01/html/821-2417/gihzx.html#gkhhv

Moving this issue to backlog.

Comment by lprimak [ 08/Jan/15 ]

This is still an issue. Any updates are appreciated.
This prevents deployment of version applications using jersey on glassfish.

Comment by lprimak [ 27/Feb/15 ]

I am very surprised by lack of activity on this issue.
I even have a private patch for it.
It's hard for me to believe that no one is using Jersey versioned applications on GlassFish.

Comment by Andybailey [ 17/Mar/15 ]

We need to use versioned deployment too, this is broken as described and is critical to our deployment scenario.

Comment by Michal Gajdos [ 17/Mar/15 ]

@lprimak - Can you provide your patch as a GitHub pull request?

Comment by lprimak [ 23/Mar/15 ]

I am not very well familiar with git / github (I used Mercurial)
but here is the patch pasted here, it's not very large.
The only need is to compile / replace jersey-gf-ejb directory with this patch

VersionBug.patch
diff --git a/containers/glassfish/jersey-gf-ejb/src/main/java/org/glassfish/jersey/gf/ejb/internal/EjbComponentProvider.java b/containers/glassfish/jersey-gf-ejb/src/main/java/org/glassfish/jersey/gf/ejb/internal/EjbComponentProvider.java
index f08c81a..7d429be 100644
--- a/containers/glassfish/jersey-gf-ejb/src/main/java/org/glassfish/jersey/gf/ejb/internal/EjbComponentProvider.java
+++ b/containers/glassfish/jersey-gf-ejb/src/main/java/org/glassfish/jersey/gf/ejb/internal/EjbComponentProvider.java
@@ -42,6 +42,8 @@
 import com.sun.ejb.containers.BaseContainer;
 import com.sun.ejb.containers.EjbContainerUtil;
 import com.sun.ejb.containers.EjbContainerUtilImpl;
+import com.sun.enterprise.config.serverbeans.Application;
+import com.sun.enterprise.config.serverbeans.Applications;
 
 import java.lang.annotation.Annotation;
 import java.lang.reflect.InvocationHandler;
@@ -56,9 +58,11 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Set;
+import java.util.TreeSet;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -87,6 +91,7 @@
 import org.glassfish.hk2.utilities.binding.ServiceBindingBuilder;
 
 import org.glassfish.internal.data.ApplicationInfo;
+import org.glassfish.internal.data.ApplicationRegistry;
 import org.glassfish.internal.data.ModuleInfo;
 
 /**
@@ -106,7 +111,7 @@
     private final List<String> libNames = new CopyOnWriteArrayList<String>();
 
     private boolean ejbInterceptorRegistered = false;
-
+    
     /**
      * HK2 factory to provide EJB components obtained via JNDI lookup.
      */
@@ -158,13 +163,51 @@
         Injections.addBinding(Injections.newBinder(this).to(ResourceMethodInvocationHandlerProvider.class), configuration);
         configuration.commit();
     }
+    
+    private ApplicationInfo getApplicationInfo(EjbContainerUtil ejbUtil) throws NamingException
+    {
+        ApplicationRegistry appRegistry = ejbUtil.getServices().getService(ApplicationRegistry.class);
+        Applications applications = ejbUtil.getServices().getService(Applications.class);
+        String appNamePrefix = (String) initialContext.lookup("java:app/AppName");
+        Set<String> appNames = appRegistry.getAllApplicationNames();
+        Set<String> disabledApps = new TreeSet<>();
+        for (String appName : appNames) {
+            if (appName.startsWith(appNamePrefix)) {
+                Application appDesc = applications.getApplication(appName);
+                if (appDesc != null && !ejbUtil.getDeployment().isAppEnabled(appDesc)) {
+                    // skip disabled version of the app
+                    disabledApps.add(appName);
+                }
+                else
+                {
+                    return ejbUtil.getDeployment().get(appName);
+                }
+            }
+        }
+        
+        // grab the latest one, there is no way to make
+        // sure which one the user is actually enabling,
+        // so use the best case, i.e. upgrade
+        Iterator<String> it = disabledApps.iterator();
+        String lastDisabledApp = null;
+        while(it.hasNext())
+        {
+            lastDisabledApp = it.next();
+        }
+        if(lastDisabledApp != null) {
+            return ejbUtil.getDeployment().get(lastDisabledApp);
+        }
+        
+        throw new NamingException("Application Information Not Found");
+    }
 
     private void registerEjbInterceptor() {
         try {
             final Object interceptor = new EjbComponentInterceptor(locator);
             initialContext = getInitialContext();
             final EjbContainerUtil ejbUtil = EjbContainerUtilImpl.getInstance();
-            final ApplicationInfo appInfo = ejbUtil.getDeployment().get((String)initialContext.lookup("java:app/AppName"));
+            // FL Patch for https://java.net/jira/browse/GLASSFISH-21173
+            final ApplicationInfo appInfo = getApplicationInfo(ejbUtil);
             final List<String> tempLibNames = new LinkedList<String>();
             for (ModuleInfo moduleInfo : appInfo.getModuleInfos()) {
                 final String jarName = moduleInfo.getName();
Comment by lprimak [ 23/Mar/15 ]

I just figured out how to do pull requests:
https://github.com/jersey/jersey/pull/154

I did not test it against the current code, but it didn't change much so it should work just as well as with production GF 4.1 release

Comment by Jakub Podlesak [ 24/Mar/15 ]

Thanks for the patch! After you sign the OCA, we can proceed further. Please see my comment on your pull request for details.

Comment by lprimak [ 24/Mar/15 ]

Done





[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-705] Ability to share a single web server across multiple tests Created: 08/Apr/11  Updated: 24/Mar/15  Resolved: 24/Mar/15

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

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

Issue Links:
Duplicate
is duplicated by JERSEY-1366 Jersey Test Framework shall start and... Resolved

 Description   

In the interest of improving performance, I'd like to share a single web server across multiple JUnit tests. One approach would be to dedicate one server per test class. Another approach would be to dedicate one server across all tests.

Currently jersey-test restarts the server once per @Test which costs about 1 second (so 100 tests take a minimum of 100 seconds to complete).



 Comments   
Comment by henrik242 [ 01/Jun/11 ]

I made a quick and dirty workaround for myself:

package com.example;

import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import org.junit.AfterClass;

public class FastJerseyTest extends JerseyTest {

    private static FastJerseyTest self = null;

    public FastJerseyTest(WebAppDescriptor build) {
        super(build);
    }

    @Override
    public void setUp() throws Exception {
        if (self == null) {
            self = this;
            super.setUp();
        }
    }

    @Override
    public void tearDown() throws Exception {}

    @AfterClass
    public static void stop() throws Exception {
        self.stopContainer();
        self = null;
    }

    private void stopContainer() throws Exception {
        super.tearDown();
    }
}
Comment by cowwoc [ 01/Jun/11 ]

Just curious: why do you use setUp() to launch the server as opposed to using @BeforeClass?

I think the best approach is to launch one server per test and run tests in parallel. Scalability will increase as the number of CPUs increase and you still maintain state isolation across tests. Any idea on how to implement that?

Comment by henrik242 [ 01/Jun/11 ]

The @BeforeClass method is static, thus I don't have access to the non-static setUp(). setUp() seems to be the only way to start the server since JerseyTest doesn't expose the TestContainer (tc) variable.

I could have copied and modified the whole JerseyTest class, of course, but FastJerseyTest seemed to be the easiest way. My tests runs extremely fast now compared to what they did earlier, and I don't really need or want a whole lot of servers in my test scenarios.

Comment by cowwoc [ 13/Jun/13 ]

2 years later, I think we're better off fixing JERSEY-710 and using concurrent unit tests. This way tests will still be isolated from each other and performance should be decent. If the performance increase by JERSEY-710 isn't sufficient I would revisit this issue.

As for JerseyTest, I think we should remove all JUnit-specific code from this class and simply have it provide the building blocks for unit tests. I propose aggregation instead of subclassing. Here is what I did for my own application:

import com.google.inject.servlet.GuiceFilter;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import com.foobar.UsersResource;

/**
 * An embedded web server for tests.
 * <p/>
 * THREAD-SAFETY: This class is not thread-safe.
 * <p/>
 * @author Gili Tzabari
 */
public class TestServer implements AutoCloseable
{
	/**
	 * @return the client-side configuration for test clients
	 */
	private static ClientConfig getClientConfig()
	{
		ClientConfig result = new DefaultClientConfig();
		result.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
		result.getClasses().add(ObjectMapperProvider.class);
		return result;
	}

	/**
	 * The test configuration.
	 */
	private static class MyJerseyTest extends JerseyTest
	{
		MyJerseyTest(AppDescriptor ad)
		{
			super(ad);
		}
	}
	private final JerseyTest delegate;
	private boolean closed;

	public TestServer()
	{
		this.delegate = new MyJerseyTest(new WebAppDescriptor.Builder().
			contextListenerClass(JerseyContextListener.class).
			contextParam("modules", TestModule.class.getName()).
			filterClass(GuiceFilter.class).servletPath("/").
			clientConfig(getClientConfig()).build());
		try
		{
			delegate.client().addFilter(new LoggingFilter());
			delegate.setUp();
		}
		catch (Exception e)
		{
			// Implementation never actually throws an exception
			throw new AssertionError(e);
		}
	}

	/**
	 * Shuts down the server.
	 */
	@Override
	public void close()
	{
		if (closed)
			return;
		closed = true;
		try
		{
			delegate.tearDown();
		}
		catch (Exception e)
		{
			// Implementation never actually throws an exception
			throw new AssertionError(e);
		}
	}

	/**
	 * Create a web root whose URI refers to the base URI the Web application is deployed at.
	 * <p/>
	 * @return the created web root
	 */
	public WebResource resource()
	{
		return delegate.resource();
	}

	/**
	 * @return the users resource
	 */
	public UsersResource users()
	{
		return new UsersResource(resource().path("users/"));
	}
}

public class UserTest
{
	public void createUser()
	{
		try (TestServer server = new TestServer())
		{
			server.users().createUser(userName, userEmail, userPhoneNumber);
		}
	}
}
Comment by Jakub Podlesak [ 24/Mar/15 ]

Introduced (beta) JUnit concurrent test runners in test-framework/util/src/main/java/org/glassfish/jersey/test/util/runner, that only launch a single container per all included test methods:

  • ConcurrentParameterizedRunner.java
  • ConcurrentRunner.java




[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-2826] Jersey EntityFilteringFeature doesn't work correctly with abstract classes Created: 20/Mar/15  Updated: 23/Mar/15

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

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-2828] "Jersey bean validation" does not validate @PathParam on sub resource location Created: 20/Mar/15  Updated: 23/Mar/15

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

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






[JERSEY-2827] Filter priority - negative numbers Created: 20/Mar/15  Updated: 23/Mar/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





[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-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-2624] Docs and jersey-spring3 POM not aligned Created: 21/Aug/14  Updated: 23/Mar/15  Resolved: 23/Mar/15

Status: Resolved
Project: jersey
Component/s: docs, extensions
Affects Version/s: 2.11
Fix Version/s: 2.18

Type: Bug Priority: Minor
Reporter: sslavic Assignee: Libor Kramolis
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: spring

 Description   

Docs for Jersey Spring DI integration, Dependencies paragraph states:

...

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.11</version>
</dependency>

The above module does not add any transitive dependency to Spring modules, so you will need to add Spring 3 dependencies explicitly into your dependency list.
...

Statement about no Spring modules being included as transitive dependencies is simply not true. It would have been true if at least jersey-spring3 pom declared Spring dependencies with provided scope.

Please have docs and jersey-spring3 POM aligned. Personally I don't have preference, I don't mind if docs are one that are changed, or if POM gets changed.



 Comments   
Comment by Adam Lindenthal [ 13/Oct/14 ]

Thanks, moving to backlog.





[JERSEY-2818] RolesAllowedDynamicFeature can return 401 or 403 errors. Created: 10/Mar/15  Updated: 19/Mar/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





[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-2691] freemarker-webapp example does not work when running as a WAR Created: 22/Oct/14  Updated: 19/Mar/15  Resolved: 19/Mar/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: 2.13
Fix Version/s: 2.18

Type: Bug Priority: Major
Reporter: elamtb Assignee: Libor Kramolis
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

OS X 10.9.5
Tomcat 8.0.11


Tags: examples, freemarker, web-container

 Description   

Take the freemarker-webapp example application and build a war file (mvn install) then deploy it to Tomcat 8. When attempting to get the hello page (http://localhost:8080/freemarker-webapp/hello), you get an exception

javax.servlet.ServletException: java.lang.IllegalArgumentException: The resource path [freemarker/hello.ftl] is not valid
	org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:393)
	org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
	org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
	org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

It seems that when bundled as a WAR file, despite the templates appearing under WEB-INF/classes, they cannot be found by the classloader. This may be a bug in the example application (perhaps there is something missing in the MyApplication class or the Maven configuration? If so, the readme should be updated to explain) but it could potentially be a bug in Jersey's Freemarker plugin that does not properly look in the right place in the classpath for the templates.



 Comments   
Comment by elamtb [ 22/Oct/14 ]

Ok, I've done more research on this. The exception is thrown in AbstractTemplateProcessor here:

if (servletContext != null) {
    final InputStream stream = servletContext.getResourceAsStream(template);
    reader = stream != null ? new InputStreamReader(stream) : null;
}

The getResourceAsStream method throws the exception rather than return a null.

Comment by elamtb [ 22/Oct/14 ]

I was able to find a workaround. In the web.xml, the template base path needs to be preceded with a / and then it will work. This will work for me for now but I still think that a relative path should be supported and this is still a bug, likely in the Jersey-mvc package (can't seem to edit the issue to chose that as a component).

Comment by Adam Lindenthal [ 31/Oct/14 ]

Hi elamtb,

thanks for creating and investigating this. I will move the issue to backlog, so that some work can be planned to do on this in one of the future sprints.
We should check if there is something to change in the template resolution code or if at least the docs should be updated to describe the behaviour (the path roots, etc) more in detail.

Regards,
Adam

Comment by elamtb [ 31/Oct/14 ]

Great, thank you.





[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-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-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-2688] Memory leak with the shutdown hooks queue when changing the state of a unique client for each requests Created: 18/Oct/14  Updated: 18/Mar/15  Resolved: 18/Mar/15

Status: Resolved
Project: jersey
Component/s: connectors
Affects Version/s: 2.13
Fix Version/s: 2.18

Type: Bug Priority: Major
Reporter: clardeur 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-2786 Memory leak with shutdown hooks, caus... Resolved

 Description   

This is the minimalist snippet of code to reproduce the memory leak :

MemoryLeakJerseyCLient.java
public class MemoryLeakJerseyClient {

    private static Client client;

    static {
        ClientConfig config = new ClientConfig()
                .property(CONNECT_TIMEOUT, 100)
                .connectorProvider(new ApacheConnectorProvider());

        client = ClientBuilder.newBuilder()
                .withConfig(config)
                .build();
    }

    public static void main(String... args) {
        while (true) {
            client.property(PROXY_URI, "http://127.0.0.1:8080");
            try {
                client.target("http://localhost:8080/ping")
                        .request()
                        .get();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

When executing this code for each request a new ApacheConnector is created due to the change of the client configuration state and a shutdown hook is registered in the JerseyClient. If the client is not closed or released the shutdown hooks queue become larger and lead to an java.lang.OutOfMemoryError: Java heap space.

I read in the documentation that the number of instances of a client should be limited because of it's weight. I have resolved my problem by instantiating a client per request, do you have any recommandation on this ?

Maybe the problem could be resolved only if there is one and only one shutdown hook that is registered.



 Comments   
Comment by clardeur [ 18/Oct/14 ]
Heap monitoring

Heap dump (inspect the JerseyClient)

Comment by Adam Lindenthal [ 22/Oct/14 ]

Hi Clardeur,

thanks for creating the issue and for a nice description.
I am moving this to backlog, so that we can work on the issue in one of the future sprints.

Regards,
Adam

Comment by Michal Gajdos [ 12/Feb/15 ]

Can you, please, provide a more real-life example? The test-case you provided seems more like an anti-pattern (changing configuration of client for each request).

Comment by clardeur [ 12/Feb/15 ]

We have many HTTP proxies in our company and we want to use them to not exceed free quota on some web services, and for other purposes like crawling. That's why we simply tried to change the proxy configuration on each requests and that's lead to a memory leak.

A first workaround was to have a pool of client, each one configured with a proxy, and when free quota has been exceeded the client was removed from the pool. The second workaround more easier to implement was just to provide a new client for each requests. We have decided that the cost of creating a new client on each requests was acceptable for our use case.

I hope you better understand why we would like to change the configuration for each requests.

Comment by Jakub Podlesak [ 17/Mar/15 ]

As a workaround you should be able to set the property on Invocation.Builder directly:

public static void main(String... args) {
        while (true) {
            try {
                client.target("http://localhost:8080/ping")
                        .request().property(PROXY_URI, "http://127.0.0.1:8080")
                        .get();
            } catch (Exception e) {
                // ignore
            }
        }
    }
Comment by Jakub Podlesak [ 18/Mar/15 ]

Fixed in the master branch.





[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-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-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-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-2469] JerseyUriBuilder do not conform to javax.ws.rs.core.UriBuilder spec for query param encoding Created: 03/Apr/14  Updated: 14/Mar/15

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

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

Tags: pull-request

 Description   

org.glassfish.jersey.uri.internal.JerseyUriBuilder is not encoding query parameters as the spec in https://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/core/UriBuilder.html.
Query params should be encoded using application/x-www-form-urlencoded rules (even though RFC 3986 allows more characters on query parameters, javax.ws.rs.core.UriBuilder defines a strict approach:
Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components.
).
So far I detected these chars as not being encoded ! * ' ( ) ; : @ $ , / ?
I have the fix for these ready to make the pull request.



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

Pull request created https://github.com/jersey/jersey/pull/76 by @EzequielB, thanks.

Comment by phraktle2 [ 13/Mar/15 ]

This pull request was apparently abandoned. Please fix, as this is clearly undesirable behavior.

Comment by ezequielmbf [ 13/Mar/15 ]

At the time of the pull request, the change on UriBuilder required a spec change/clarification. So it was decided to put aside until jax-rs is changed. I think there were no change in the UriBuilder spec.

Comment by phraktle2 [ 14/Mar/15 ]

I would argue, that 1) the behavior is undesirable as currently implemented (and subtly breaks most code that relies on this function) 2) this detail is not properly specified in the spec (i.e. the spec does not mandate the undesirable behavior).

Therefore, as the JAX-RS reference implementation, Jersey should provide the implementation that people would expect.

The spec should also be clarified to ensure this detail is well specified, but this is not a precondition of fixing this.

Comment by phraktle2 [ 14/Mar/15 ]

I have also tested Resteasy, which implements the expected behavior, as demonstrated by the code below. I don't think you could argue they are doing it wrong based on the spec either.

UriBuilderTest.java
package test;

import java.net.URI;
import java.net.URISyntaxException;

import javax.ws.rs.core.UriBuilder;

import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
import org.jboss.resteasy.specimpl.ResteasyUriBuilder;

public class UriBuilderTest {

    public static void main(String[] args) throws Exception {

        // http://mysite.com/?foo=b%3Da:r
        System.out.println("jersey  : " + build(new JerseyUriBuilder()));

        // http://mysite.com/?foo=b%3Da%3Ar
        System.out.println("resteasy: " + build(new ResteasyUriBuilder()));
    }

    private static String build(UriBuilder b) throws URISyntaxException {
        b.uri(new URI("http://mysite.com/"));
        b.queryParam("foo", "b=a:r");
        return b.build().toString();
    }

}
Comment by phraktle2 [ 14/Mar/15 ]

To further demonstrate how this breaks the expectation of anyone using the library: all other libraries with a similar purpose encode parameters properly (as does resteasy above), yielding http://mysite.com/?foo=b%3Da%3Ar

Jetty client
new HttpClient().newRequest("http://mysite.com/").param("foo", "b=a:r").getURI().toString();
Apache HttpClient
new URIBuilder("http://mysite.com/").addParameter("foo", "b=a:r").toString();
Comment by ezequielmbf [ 14/Mar/15 ]

Yes that is exactly the behavior that is not right.
I haven't tested on Restesay, great for that, only on jdk URLEncoder.
I can bring to life this pull request, but I think we should ask Marek Potociar. Will do so, re opening the pull request and linking it to here.
Thanks a lot for the additional info!.





[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-2723] grizzly parse uri error for URI path beginning with two consecutive slashes Created: 04/Dec/14  Updated: 11/Mar/15

Status: Open
Project: jersey
Component/s: containers
Affects Version/s: 2.13
Fix Version/s: backlog

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


 Description   

The exception happens whenever handling URI path beginning with two consecutive slashes (three slashes are fine from that perspective).

"stack message"
javax.ws.rs.core.UriBuilderException: java.net.URISyntaxException: Expected authority at index 2: //
	at org.glassfish.jersey.uri.internal.JerseyUriBuilder.createURI(JerseyUriBuilder.java:908) ~[jersey-common-2.13.jar:na]
	at org.glassfish.jersey.uri.internal.JerseyUriBuilder._build(JerseyUriBuilder.java:897) ~[jersey-common-2.13.jar:na]
	at org.glassfish.jersey.uri.internal.JerseyUriBuilder.build(JerseyUriBuilder.java:810) ~[jersey-common-2.13.jar:na]
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.getRequestUri(GrizzlyHttpContainer.java:451) ~[jersey-container-grizzly2-http-2.10.1.jar:na]
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:348) ~[jersey-container-grizzly2-http-2.10.1.jar:na]
	at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:219) ~[grizzly-http-server-2.3.16.jar:2.3.16]
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565) [grizzly-framework-2.3.16.jar:2.3.16]
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545) [grizzly-framework-2.3.16.jar:2.3.16]
	at java.lang.Thread.run(Thread.java:745) [na:1.7.0_65]

please fix bug at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer private URI getRequestUri(URI baseUri, Request grizzlyRequest)

"GrizzlyHttpContainer"

private URI getRequestUri(URI baseUri, Request grizzlyRequest) {
        // TODO: this is terrible, there must be a way to obtain the original request URI!
      +//please use getRequestURIRef().getDecodedURI() or normalize 
        String originalUri = UriBuilder.fromPath(
                grizzlyRequest.getRequest().getRequestURIRef().getOriginalRequestURIBC().toString(Charsets.DEFAULT_CHARSET)
        ).build().toString();

        String queryString = grizzlyRequest.getQueryString();
        if (queryString != null) {
            originalUri = originalUri + "?" + ContainerUtils.encodeUnsafeCharacters(queryString);
        }

        return baseUri.resolve(originalUri);
    }

please use getRequestURIRef().getDecodedURI() or normalize

  
        String originalUri = UriBuilder.fromPath(
grizzlyRequest.getRequest().getRequestURIRef().getOriginalRequestURIBC().toString(Charsets.DEFAULT_CHARSET)
        ).build().toString();

please! thanks lot



 Comments   
Comment by Jakub Podlesak [ 09/Dec/14 ]

Any chance you could submit a pull request containing a reproducible test covering your use case? Thanks in advance for any response!

Comment by icode [ 09/Dec/14 ]

please visit http://localhost:port// on grizzly container

Comment by Jakub Podlesak [ 10/Dec/14 ]

Things will not be that easy, we need to be able to retain multiple consecutive slashes in the URI. However we should try to address this issue somehow.

We should avoid any code leading to new URI("//") call which could be caused also by URI.resolve method invocation.

Comment by icode [ 10/Dec/14 ]

why move to backlog?this important!grizzly can't use basic

Comment by Jakub Podlesak [ 10/Dec/14 ]

While i agree this is important, the bug could still be worked around using e.g. an appropriately
configured Apache httpd server instance running in front of Grizzly.
Schedule for the current Jersey sprint is very tight, and i am not sure this would fit in, that is all the backlog assignment says.





[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-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-2698] ApacheConnector doesn't respect per-request timeouts Created: 31/Oct/14  Updated: 10/Mar/15  Resolved: 10/Mar/15

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

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


 Description   

Setting ClientProperties.READ_TIMEOUT or ClientProperties.CONNECT_TIMEOUT per-request has no effect. Only the timeout values that were present in the RequestConfig when the ApacheConnector is constructed are used.

This is in contrast to the behavior of the HttpUrlConnector, which respects per-request timeout properties.



 Comments   
Comment by Adam Lindenthal [ 31/Oct/14 ]

Rohan (reporter) created a pull request: https://github.com/jersey/jersey/pull/121

Comment by Adam Lindenthal [ 03/Nov/14 ]

Waiting for OCA, in the meantime moving the issue to backlog.

Comment by Adam Lindenthal [ 10/Mar/15 ]

Merged, thanks for cooperating.

Regards,
Adam





[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-2690] GF: Fail to lookup EJB that is declared in war module of an EAR Created: 21/Oct/14  Updated: 08/Mar/15

Status: Open
Project: jersey
Component/s: containers
Affects Version/s: 2.10, 2.13
Fix Version/s: backlog

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

Glassfish 4.1 (jersey module version 2.10.4)



 Description   

When declare EJB to be JAX-RS endpoint inside war module that included in EAR like this:

@Stateless
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class UsersResource {
...

Name of the war module is "op-client"
I got following exception in the logs:

[2014-10-20T18:56:53.226+0200] [glassfish 4.1] [WARNING] [] [org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider] [tid: _ThreadID=31 _ThreadName=http-listener-1(5)] [timeMillis: 1413824213226] [levelValue: 900] [[
  An instance of EJB class, com.mycompany.opclient.rest.UsersResource, could not be looked up using simple form name. Attempting to look up using the fully-qualified form name.
javax.naming.NamingException: Lookup failed for 'java:app/someothermodule/UsersResource' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:app/someothermodule/UsersResource]
	at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
	at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
	at javax.naming.InitialContext.lookup(InitialContext.java:411)
	at javax.naming.InitialContext.lookup(InitialContext.java:411)
	at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.lookupSimpleForm(EjbComponentProvider.java:378)
....

Note that lookup is complains about "someothermodule" not "op-client". Earlier in the logs though there is following message:

[2014-10-20T18:08:29.484+0200] [glassfish 4.1] [INFO] [AS-EJB-00054] [javax.enterprise.ejb.container] [tid: _ThreadID=44 _ThreadName=admin-listener(4)] [timeMillis: 1413824909484] [levelValue: 800] [[
  Portable JNDI names for EJB UsersResource: [java:global/earmodule/op-client/UsersResource, java:global/earmodule/op-client/UsersResource!com.mycompany.opclient.rest.UsersResource]]]

Which means that bean was successfully discovered and registered and should be available for lookup. Evaluating expression with proper name for lookup at breakpoint in EjbComponentProvider confirms that.
Digging deeper into the problem I've found that patch that was made to fix this issue (325a2f214e093859d41d81f9f06652c169a03aa4) introduced following code in registerEjbInterceptor method of EjbComponentProvider:

    private void registerEjbInterceptor() {
        try {
            final Object interceptor = new EjbComponentInterceptor(locator);
            initialContext = getInitialContext();
            final EjbContainerUtil ejbUtil = EjbContainerUtilImpl.getInstance();
            final ApplicationInfo appInfo = ejbUtil.getDeployment().get((String)initialContext.lookup("java:app/AppName"));
            final List<String> tempLibNames = new LinkedList<String>();
            for 
(ModuleInfo moduleInfo : appInfo.getModuleInfos()) {
                final String jarName = moduleInfo.getName();
                if (jarName.endsWith(".jar")) {
                    final String moduleName = jarName.substring(0, jarName.length() - 4);
                    tempLibNames.add(moduleName);
....

Note jarName.endsWith(".jar") part. This check for file extension basically prevents all beans that live inside "*.war" being discovered when doing cycle in lookupSimpleForm method:

    private static Object lookupSimpleForm(InitialContext ic, String name, EjbComponentProvider provider) throws NamingException {
        if (provider.libNames.isEmpty()) {
            String jndiName = "java:module/" + name;
            return ic.lookup(jndiName);
        } else {
            NamingException ne = null;
            for (String moduleName : provider.libNames) {
                String jndiName = "java:app/" + moduleName + "/" + name;

because now we never see war file in provider.libNames collection. This breaks my and not only my (https://java.net/jira/browse/GLASSFISH-21114) application and should be fixed.



 Comments   
Comment by Adam Lindenthal [ 22/Oct/14 ]

Hi Gray,

thanks for creating the issue. I am moving it to backlog, so that we can plan it for one of the future sprints.

Regards,
Adam

Comment by Sparksis [ 14/Jan/15 ]

Hi Adam,

Is there an ETA on when this could be revisited? As is glassfish 4.1 does not support JAX-RS with @Stateless EJBs in web archives.

Thanks,

Comment by lberteau [ 22/Jan/15 ]

Hi everyone,

If it may help, I have noticed that I have this issue within 32 bits environnements.
The same code works fine within a 64 bits JDK.

Don't have a clue about the reasons, but that's what I observed.

Regards,
Laurent

Comment by MarvinEmilBrach [ 08/Mar/15 ]

posssible workaround: replace @Stateless with:
@javax.enterprise.context.RequestScoped
@javax.enterprise.context.ApplicationScoped
@javax.enterprise.context.ConversationScoped // NOT tested
@javax.enterprise.context.SessionScoped // NOT tested





[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-2498] ByteBufferInputStream violates InputStream definition Created: 28/Apr/14  Updated: 06/Mar/15

Status: Reopened
Project: jersey
Component/s: core
Affects Version/s: 2.7
Fix Version/s: backlog

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

Issue Links:
Duplicate
is duplicated by JERSEY-2817 ByteBufferInputStream has bad casts f... Resolved
Tags: incomplete

 Description   

The ByteBufferInputStream implementation does not properly convert values returned by "ByteBuffer.get()" to integer values. The current implementation converts via numeric cast. The preserves the numeric value and the not bit pattern. Integer conversion should be preformed via a bitwise-and (ie ByteBuffer.read() & 0xFF).

This is causing problems with binary http response entities when using the Async features of the Jersey HTTP client. In some cases I am seeing bytes within the response body whose value is 0xFF to be silently dropped.



 Comments   
Comment by Michal Gajdos [ 30/Apr/14 ]

Closing the issue as I understood that there is no data corruption. Feel free to reopen the issue (or make a comment and I'll reopen it) if you have a particular use-case in which you encounter data corruption.

Comment by joey_hart [ 30/Apr/14 ]

InputStream.read() requires that integer values returned be in the range '-1' to '255'. The current ByteBufferInputStream implementation allows values of the range '-128' to '127' to be returned from ByteBufferInputStream.read().

This cause problems with some Filtering Input Stream implementations such as GZIPInputStream that expects these values to be returned as specified by InputStream.read().

Further more there is no way to distinguish between end-of-stream and a -1 (ie 0xFF) in the payload.

I need to clear it with my company but I do have a use case where I pre-compress an entity using gzip and server that compressed entity with a Content-Type of 'application/octet-stream' to clients. When I use any of the aync http client connectors (grizzly & jetty) I end up losing two bytes of data. Both of which happen to have the value of '0xFF'. In this case my http server delivers 1789 bytes of data but the client only delivers a byte[] of length 1787.

Comment by joey_hart [ 02/May/14 ]

I do not have permission to reopen this issue. Can someone please respond to my last comment?

Comment by Michal Gajdos [ 02/May/14 ]

Reopening. Please, provide a test case if possible.

Do you use GzipEncoder from Jersey to do the encoding/decoding for you or are you working with GZIPInputStream/GZIPOutputStream directly?

Comment by joey_hart [ 02/May/14 ]

I will work on the test case this weekend and should have something to you by Monday.

GzipEncoder is not used. The binary response from the Jersey Client is decompressed using GZIPInputStream within my application code. The server is NOT sent the "Accept-Encoding: gzip" header when the GET is issued. As far as the HTTP Server & Jersey is concerned the Entity is just a plain old binary file.

Comment by b_porter [ 04/Mar/15 ]

I have run in to this issue, and created a pull request - with unit test.
https://github.com/jersey/jersey/pull/147





[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-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-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-2812] Thread not released when Jersey configured as a filter Created: 03/Mar/15  Updated: 05/Mar/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: 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-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-609] Resource classes unable to be found and registered using package scanning under Websphere 7 Created: 01/Dec/10  Updated: 04/Mar/15  Resolved: 16/May/12

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

Type: Bug Priority: Minor
Reporter: padolan Assignee: Michal Gajdos
Resolution: Cannot Reproduce Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

IBM Websphere 7.0.0.3, Windows XP, Unix


Tags: gf3_1-exclude

 Description   

Related to JERSEY-558...

The problem (unable to get the websphere runtime to pick up resource classes located in java projects using the jersey package scanning ResourceConfig) was reported fixed with JBoss, but appears to still exist for websphere. The project structure is straightforward:
EAR

-----WAR

-----JAR

My web.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>
TestWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TransSystemAdminRestServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.walmart.trans</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>TransSystemAdminRestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

The full stacktrace I get is:

[12/1/10 8:01:40:638 CST] 00000017 PackagesResou I Scanning for root resource and provider classes in the packages:
com.walmart.trans
[12/1/10 8:01:40:982 CST] 00000017 WebApplicatio I Initiating Jersey application, version 'Jersey: 1.4 09/11/2010 10:41 PM'
[12/1/10 8:01:41:794 CST] 00000017 RootResourceU E The ResourceConfig instance does not contain any root resource classes.
[12/1/10 8:01:41:794 CST] 00000017 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0100E: Uncaught init() exception created by servlet TransSystemAdminRestServlet in application TestEAR: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:103)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1182)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$600(WebApplicationImpl.java:161)
at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:698)
at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:695)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:197)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:695)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:690)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:438)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:287)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:587)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:213)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:342)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:516)
at javax.servlet.GenericServlet.init(GenericServlet.java:241)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:326)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:165)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.initialize(ServletWrapper.java:1600)
at com.ibm.wsspi.webcontainer.extension.WebExtensionProcessor.createServletWrapper(WebExtensionProcessor.java:98)
at com.ibm.ws.webcontainer.webapp.WebApp.getServletWrapper(WebApp.java:939)
at com.ibm.ws.webcontainer.webapp.WebApp.getServletWrapper(WebApp.java:860)
at com.ibm.ws.webcontainer.webapp.WebApp.initializeTargetMappings(WebApp.java:541)
at com.ibm.ws.webcontainer.webapp.WebApp.commonInitializationFinish(WebApp.java:363)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:293)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:100)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:166)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:728)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:613)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:376)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:668)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1144)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1313)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:611)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:938)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:723)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$1.run(ApplicationMgrImpl.java:1288)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:4388)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:4566)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1293)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2065)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:437)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:122)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:380)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:651)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:613)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:243)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1085)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1310)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1203)
at com.ibm.ws.management.connector.AdminServiceDelegator.invoke(AdminServiceDelegator.java:181)
at com.ibm.ws.management.connector.rmi.RMIConnectorService.invoke(RMIConnectorService.java:282)
at com.ibm.ws.management.connector.rmi._RMIConnectorService_Tie.invoke(_RMIConnectorService_Tie.java:395)
at com.ibm.ws.management.connector.rmi._RMIConnectorService_Tie._invoke(_RMIConnectorService_Tie.java:160)
at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:622)
at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:475)
at com.ibm.rmi.iiop.ORB.process(ORB.java:504)
at com.ibm.CORBA.iiop.ORB.process(ORB.java:1573)
at com.ibm.rmi.iiop.Connection.respondTo(Connection.java:2845)
at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2714)
at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:63)
at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527)

[12/1/10 8:01:41:794 CST] 00000017 extension E com.ibm.wsspi.webcontainer.extension.WebExtensionProcessor createServletWrapper Error occured while preparing the servlet for initialization.
javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:378)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:165)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.initialize(ServletWrapper.java:1600)
at com.ibm.wsspi.webcontainer.extension.WebExtensionProcessor.createServletWrapper(WebExtensionProcessor.java:98)
at com.ibm.ws.webcontainer.webapp.WebApp.getServletWrapper(WebApp.java:939)
at com.ibm.ws.webcontainer.webapp.WebApp.getServletWrapper(WebApp.java:860)
at com.ibm.ws.webcontainer.webapp.WebApp.initializeTargetMappings(WebApp.java:541)
at com.ibm.ws.webcontainer.webapp.WebApp.commonInitializationFinish(WebApp.java:363)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:293)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:100)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:166)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:728)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:613)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:376)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:668)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1144)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1313)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:611)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:938)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:723)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$1.run(ApplicationMgrImpl.java:1288)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:4388)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:4566)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1293)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2065)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:437)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:122)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:380)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:651)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:613)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:243)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1085)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1310)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1203)
at com.ibm.ws.management.connector.AdminServiceDelegator.invoke(AdminServiceDelegator.java:181)
at com.ibm.ws.management.connector.rmi.RMIConnectorService.invoke(RMIConnectorService.java:282)
at com.ibm.ws.management.connector.rmi._RMIConnectorService_Tie.invoke(_RMIConnectorService_Tie.java:395)
at com.ibm.ws.management.connector.rmi._RMIConnectorService_Tie._invoke(_RMIConnectorService_Tie.java:160)
at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:622)
at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:475)
at com.ibm.rmi.iiop.ORB.process(ORB.java:504)
at com.ibm.CORBA.iiop.ORB.process(ORB.java:1573)
at com.ibm.rmi.iiop.Connection.respondTo(Connection.java:2845)
at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2714)
at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:63)
at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527)
Caused by: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:103)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1182)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$600(WebApplicationImpl.java:161)
at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:698)
at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:695)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:197)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:695)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:690)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:438)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:287)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:587)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:213)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:342)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:516)
at javax.servlet.GenericServlet.init(GenericServlet.java:241)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:326)
... 61 more

The workaround I have is to remove the servlet init parameter, and ensure my resource classes are in the WEB-INF/lib folder of the WAR project. I'd prefer to not have to do this if possible.

Thanks for any help.



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

Can you provide an example to this issue (e.g. by attaching a sample application that fails to start after the deployment), because unfortunately I am not able to reproduce the problem? Does this problem occur even with the Jersey samples (e.g. helloworld-webapp, extended-wadl-webapp) for you?

Comment by Michal Gajdos [ 16/May/12 ]

Resolving as 'Cannot Reproduce'. Feel free to reopen if the problem persist.

Comment by Ramasarma [ 04/Mar/15 ]

I am able to reproduce this issue in my local.

[3/4/15 6:07:58:454 EST] 00000019 WebApplicatio I Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
[3/4/15 6:07:58:843 EST] 00000019 RootResourceU E The ResourceConfig instance does not contain any root resource classes.
[3/4/15 6:07:58:845 EST] 00000019 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper init Uncaught.init.exception.thrown.by.servlet
[3/4/15 6:07:58:845 EST] 00000019 webapp E com.ibm.ws.webcontainer.webapp.WebApp commonInitializationFinally SRVE0266E: Error occured while initializing servlets:

{0}

javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:391)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:168)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.loadOnStartupCheck(ServletWrapper.java:1274)
at com.ibm.ws.webcontainer.webapp.WebApp.doLoadOnStartupActions(WebApp.java:586)
at com.ibm.ws.webcontainer.webapp.WebApp.commonInitializationFinally(WebApp.java:557)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:421)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:748)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:633)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:422)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:714)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1134)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1369)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:638)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startModule(ApplicationMgrImpl.java:1632)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.access$400(ApplicationMgrImpl.java:206)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$3.run(ApplicationMgrImpl.java:1567)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5277)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5493)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl._startModule(ApplicationMgrImpl.java:1596)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:49)
at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:256)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1085)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1334)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1227)
at com.ibm.ws.management.application.sync.StartDeploymentTask.startDeployment(StartDeploymentTask.java:236)
at com.ibm.ws.management.application.sync.StartDeploymentTask.fineGrainUpdate(StartDeploymentTask.java:187)
at com.ibm.ws.management.application.sync.StartDeploymentTask.performTask(StartDeploymentTask.java:99)
at com.ibm.ws.management.application.sync.AppBinaryProcessor$ExpandApp.expand(AppBinaryProcessor.java:1539)
at com.ibm.ws.management.application.sync.AppBinaryProcessor.postProcessSynchronousExt(AppBinaryProcessor.java:701)
at com.ibm.ws.management.bla.sync.BLABinaryProcessor.postProcess(BLABinaryProcessor.java:575)
at com.ibm.ws.management.bla.sync.BLABinaryProcessor.onChangeCompletion(BLABinaryProcessor.java:452)
at com.ibm.ws.management.repository.FileRepository.postNotify(FileRepository.java:1936)
at com.ibm.ws.management.repository.FileRepository.update(FileRepository.java:1445)
at com.ibm.ws.management.repository.client.LocalConfigRepositoryClient.update(LocalConfigRepositoryClient.java:189)
at com.ibm.ws.sm.workspace.impl.WorkSpaceMasterRepositoryAdapter.update(WorkSpaceMasterRepositoryAdapter.java:657)
at com.ibm.ws.sm.workspace.impl.RepositoryContextImpl.update(RepositoryContextImpl.java:1998)
at com.ibm.ws.sm.workspace.impl.RepositoryContextImpl.synch(RepositoryContextImpl.java:1946)
at com.ibm.ws.sm.workspace.impl.WorkSpaceImpl.synch(WorkSpaceImpl.java:549)
at com.ibm.ws.management.configservice.ConfigServiceImpl.save(ConfigServiceImpl.java:717)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:49)
at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:256)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1085)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1334)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1227)
at com.ibm.ws.management.remote.AdminServiceForwarder.invoke(AdminServiceForwarder.java:334)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1438)
at javax.management.remote.rmi.RMIConnectionImpl.access$200(RMIConnectionImpl.java:83)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1276)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1371)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:799)
at javax.management.remote.rmi._RMIConnectionImpl_Tie.invoke(_RMIConnectionImpl_Tie.java:750)
at javax.management.remote.rmi._RMIConnectionImpl_Tie._invoke(_RMIConnectionImpl_Tie.java:158)
at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:626)
at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:479)
at com.ibm.rmi.iiop.ORB.process(ORB.java:514)
at com.ibm.CORBA.iiop.ORB.process(ORB.java:1574)
at com.ibm.rmi.iiop.Connection.respondTo(Connection.java:2880)
at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2753)
at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:63)
at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1648)
Caused by: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
at javax.servlet.GenericServlet.init(GenericServlet.java:161)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:329)
... 85 more





[JERSEY-2633] Jersey server force all request handling threads to pass through a single lock Created: 29/Aug/14  Updated: 03/Mar/15  Resolved: 03/Dec/14

Status: Resolved
Project: jersey
Component/s: core, performance
Affects Version/s: 2.12
Fix Version/s: 2.14

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

Linux 3.13.0-34-generic #60-Ubuntu SMP Wed Aug 13 15:45:27 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

Jetty 9.2.2.v20140723


Attachments: Zip Archive jersey-2633.zip    

 Description   

It seems like Jersey server requires all request handling threads to pass through a sychronized lock in org.jvnet.hk2.internal.Utilities(Utilities.java:148), below is a stack trace I was able to capture during a load test with a lot of concurrent requests. Several threads were waiting for the same lock (but from slightly different code paths).

It's not a deadlock, but it could be something which significantly reduces scalability of Jersey when you have many concurrent requests and several CPU cores available.

"qtp330351192-119" prio=10 tid=0x00007f3710017800 nid=0x321f waiting for monitor entry [0x00007f36b98d5000]
java.lang.Thread.State: BLOCKED (on object monitor)
at org.jvnet.hk2.internal.Utilities.computeElementAnnotationInfo(Utilities.java:1576)

  • waiting to lock <0x00000000c06a27b8> (a java.lang.Object)
    at org.jvnet.hk2.internal.Utilities.getInjectAnnotation(Utilities.java:1609)
    at org.jvnet.hk2.internal.Utilities.getInjectionResolver(Utilities.java:1854)
    at org.jvnet.hk2.internal.Utilities.getInjectionResolver(Utilities.java:1886)
    at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:938)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:902)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:892)
    at org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider.getValueFactory(AbstractValueFactoryProvider.java:136)
    at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getValueFactory(ParameterValueHelper.java:145)
    at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.createValueProviders(ParameterValueHelper.java:124)
    at org.glassfish.jersey.server.model.Invocable.getValueProviders(Invocable.java:322)
    at org.glassfish.jersey.server.model.ResourceMethodValidator.checkValueProviders(ResourceMethodValidator.java:164)
    at org.glassfish.jersey.server.model.ResourceMethodValidator.checkMethod(ResourceMethodValidator.java:106)
    at org.glassfish.jersey.server.model.ResourceMethodValidator.visitJaxrsResourceMethod(ResourceMethodValidator.java:102)
    at org.glassfish.jersey.server.model.ResourceMethodValidator.visitResourceMethod(ResourceMethodValidator.java:92)
    at org.glassfish.jersey.server.model.ResourceMethod.accept(ResourceMethod.java:854)
    at org.glassfish.jersey.server.model.ComponentModelValidator.validateWithErrors(ComponentModelValidator.java:161)
    at org.glassfish.jersey.server.model.ComponentModelValidator.validateWithErrors(ComponentModelValidator.java:167)
    at org.glassfish.jersey.server.model.ComponentModelValidator.validateWithErrors(ComponentModelValidator.java:167)
    at org.glassfish.jersey.server.model.ComponentModelValidator.validateWithErrors(ComponentModelValidator.java:167)
    at org.glassfish.jersey.server.model.ComponentModelValidator.access$000(ComponentModelValidator.java:90)
    at org.glassfish.jersey.server.model.ComponentModelValidator$1.run(ComponentModelValidator.java:151)
    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.server.model.ComponentModelValidator.validate(ComponentModelValidator.java:146)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter$1.run(SubResourceLocatorRouter.java:205)
    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.server.internal.routing.SubResourceLocatorRouter.validate(SubResourceLocatorRouter.java:201)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:160)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
    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:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
    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.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769)


 Comments   
Comment by Miroslav Fuksa [ 29/Aug/14 ]

hi,

thanks for creating the issue. I am moving the issue to the backlog.

thanks
Mira

Comment by Marek Potociar [ 09/Sep/14 ]

Hi, would you be able to provide a simple web application that you have used for the load testing and can reliably reproduce this issue?

Many thanks in advance.

Comment by mikaelstaldal [ 10/Sep/14 ]

Unfortunately, that will not be easy to do. I did the testing on a big and complex web application, which is also written in Scala.

Comment by Adam Lindenthal [ 11/Sep/14 ]

Hi Mikael,

unfortunately, I am not able to reproduce the problem you described. I understand, that your use case is complex, but would it be possible to try to create something minimalistic which still keeps running into same concurrency problem?

Or at least some more information about your resource configuration and about the amount of load needed to run into issues would be helpful (e.g. to find out, that I need far more load to reproduce it).

I created a simple (bare-bone) test app, it uses sub-resource locator (according to your thread dump it looks like you've been using this as well), some parameter injection, etc. I tried to load it with two Apache Bench ab clients and tried to capture something similar in visualvm but with no success. I also tried to play a bit with the Grizzly worker thread pool size, but without any significant change regarding locking.

I will attach the test app, would you be able to try to reproduce it with that using the similar load?
You just need to:

Many thanks!

Comment by mikaelstaldal [ 11/Sep/14 ]

My application run as a Servlet in Jetty 9.2.2.v20140723, it uses sub-resource locators quite extensively.

My load test tool (custom application, using Jersey client) simulates 250 concurrent users, each making a request with 10 second delay in between. Jetty is configured with a request pool of 200 threads. My application makes an outbound request to another web service (using Jersey client) for each inbound request, and I did setup the external web service to take 30 seconds to respond. I do not use asynchronous processing. This force exhaustion of the request handling threads in Jetty, which was the purpose.

The purpose of my test was not primarily to test Jersey, I just accidentally happen to discover this.

Here are some snippets from my application (Scala 2.10):

class Application extends javax.ws.rs.core.Application {
  val root = new Root()

  override def getClasses: java.util.Set[Class[_]] =
    Set[Class[_]](
      classOf[MultiPartFeature],
      classOf[EncodingFilter],
      classOf[GZipEncoder]
      // and some custom stuff
)

  override def getSingletons: java.util.Set[AnyRef] = Set[AnyRef](root)
}


@Path("/")
class Root{
  @Path("org/{id}")
  def orgMethod(@PathParam("id") id: String) = {
     new SubResource1(orgId)
  }
}

class SubResource1(orgId: String) {
  @Path("device")
  def device(@HeaderParam(HttpHeaders.AUTHORIZATION) authorization: String,
             @CookieParam("authCookie") authCookie: Cookie,
             @Context config: Configuration,
             @Context requestContext: ContainerRequestContext) = {
    new SubResource2()
  }
}

class SubResource2 {
  @Path("session")
  def session = new SubResource3()
}

class SubResource3  {
  @Path("{id}")
  def forSession(@PathParam("id") sessionId: String) = {
     new SubResource4(sessionId)
  }
}

class SubResource4(sessionId: Int) {
  @GET
  @Path("foo")
  def foo(@Context uriInfo: UriInfo, @QueryParam("bar") bar: Int): AnyRef = {
    // make outbound request here, will delay 30 seconds
  }
}

And web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <servlet>
        <servlet-name>JAXRSServlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.mycompany.Application</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAXRSServlet</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
</web-app>
Comment by Adam Lindenthal [ 24/Sep/14 ]

Hi Mikael,

I don't really think that not using asynchronous processing for a long running request is a typical use case. On the other hand - you are right that if the (synchronous) resource method is slowed down, there are blocked worker threads as you described (trying to read the hk2 cache).

I've posted a diff with a change suggestion to the hk2 team. I'll try to keep you informed as soon as I know more myself.

Cheers,
Adam

Comment by Adam Lindenthal [ 14/Oct/14 ]

FYI, the pull request in hk2 was just merged. This issue remains still open, as Jersey does not use the latest hk2 version yet.

Comment by Adam Lindenthal [ 03/Dec/14 ]

Jersey hk2 dependency has been upgraded, the issue should be gone in the latest snapshot.





[JERSEY-2625] Declarative linking with mixed JAXB/JPA entities using EclipseLink leads to ValidationException Created: 21/Aug/14  Updated: 03/Mar/15  Resolved: 02/Mar/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: 2.10.1
Fix Version/s: 2.17

Type: Bug Priority: Major
Reporter: HeinBloed Assignee: Adam Lindenthal
Resolution: Fixed Votes: 1
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File DeclarativeLinkingDemo.war     Zip Archive DeclarativeLinkingDemo.zip    

 Description   

This issue must be due to the same reasons as https://java.net/jira/browse/JERSEY-2490, however in this specific situation, it is not only an improvement request but a bug.

I'm using mixed JAXB/JPA entities like this:

@Entity
@Table( name = "user", schema = "public" )
@Access( AccessType.PROPERTY )
@XmlAccessorType( XmlAccessType.PROPERTY )
@XmlRootElement
public class User implements Serializable
{
   private Integer dbid;
   private String login;
   private String password;
   private Integer version;
   private List<Role> roles;

   @Id
   @GeneratedValue( strategy = GenerationType.IDENTITY )
   @Column( name = "dbid" )
   public Integer getDbid()
   {
      return this.dbid;
   }

   public void setDbid( Integer dbid )
   {
      this.dbid = dbid;
   }

   @Column( name = "login", unique = true, nullable = false, length = 256 )
   public String getLogin()
   {
      return this.login;
   }

   public void setLogin( String login )
   {
      this.login = login;
   }

   [...]
}

If I just register the DeclarativeLinkingFeature, i.e. not even use any @InjectLink annotations, I run into this exception:

Exception [EclipseLink-7097] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Operation not supported: [iterator].
	at org.eclipse.persistence.exceptions.ValidationException.operationNotSupported(ValidationException.java:1493)
	at org.eclipse.persistence.internal.helper.linkedlist.ExposedNodeLinkedList.iterator(ExposedNodeLinkedList.java:67)
	at org.glassfish.jersey.linking.FieldProcessor.processLinks(FieldProcessor.java:145)
	at org.glassfish.jersey.linking.FieldProcessor.processMember(FieldProcessor.java:161)
	at org.glassfish.jersey.linking.FieldProcessor.processLinks(FieldProcessor.java:152)
	at org.glassfish.jersey.linking.FieldProcessor.processMember(FieldProcessor.java:161)
	at org.glassfish.jersey.linking.FieldProcessor.processLinks(FieldProcessor.java:152)
	at org.glassfish.jersey.linking.FieldProcessor.processMember(FieldProcessor.java:161)
	at org.glassfish.jersey.linking.FieldProcessor.processLinks(FieldProcessor.java:152)
	[...]

There is actually a huge sequence of FieldProcessor.processMember/processLink calls below that. By debugging, I found out that the processed HashSet in FieldProcessor grows to about 315,000 entries just before the ExposedNodeLinkedList is processed. I presume that that is due to JPA proxying the entity with all sorts of extra properties, all of which are then processed recursively. In fact, I found countless JPA-related objects in the processed HashSet on further inspection.

The real "culprit" is ExposedNodeLinkedList, which does not support iterator() (which gets called implicitly in FieldProcessor line 145:
for (Object member : collection)), so this could be regarded as a problem of EclipseLink.

But the declarative linking feature is basically unusable in this situation. Needless to say that recursing through those 300k+ objects also takes quite some time.

Offering something like a @NoLink annotation, like suggested in the other issue, would not even help with this problem.



 Comments   
Comment by Adam Lindenthal [ 01/Sep/14 ]

Hi HeinBloed,

thank you for reporting an issue and thumbs up for taking your time to provide such detailed description. We appreciate this.
However, this seems to be happening in a bit more complex environment - I did not succeed to reproduce this using small sample project based on your code and instructions.

It would be very helpful, if you could provide some bare-bone minimalistic (ideally maven-based) project, that would reproduce the failure, so that we have the entire context (incl. dependencies, etc).

For now, I am moving the issue to backlog.

Regards,
Adam

Comment by HeinBloed [ 01/Sep/14 ]

Hi Adam,

thanks for your reply. I'm afraid I don't have a Maven project right now (we're really "old school" here ), but I'll try to assemble a complete list of files for a minimalistic demonstration project.

Comment by Adam Lindenthal [ 01/Sep/14 ]

Thanks! Maven is not necessary, some zipfile with content, that is runnable (or deployable) somehow and demonstrates the problem you are facing is just fine.

Just to warn you - you don't have to hurry, the issue is not yet planned and unfortunately it may take some time...

Comment by HeinBloed [ 03/Sep/14 ]

Hi Adam,

I'd have a minimal project ready to share now, is there a preferred way to make it accessible to you? Otherwise I'd just upload the zip/war file to a free filehoster?

Comment by Adam Lindenthal [ 03/Sep/14 ]

Hi HeinBloed,

unfortunately, our JIRA instance does not support file upload by users. So I leave this up to you - choose free file hosting or simply send it to me via email (adam.lindenthal at oracle.com).
I will attach it here to the JIRA issue.

Thanks!

Comment by HeinBloed [ 03/Sep/14 ]

I've sent you an email with some deployment instructions - hope you can get it to work.

Comment by Adam Lindenthal [ 03/Sep/14 ]

Attaching the sample from HeinBloed.

Comment by Adam Lindenthal [ 03/Sep/14 ]

Hi,

thank you for the sample and for the further explanation. I will quote he the email from you, as someone else might investigate this issue:

I've attached two files. The WAR file should be deployable as is on a GlassFish 4.x instance, provided you have a running PostgreSQL database and defined a JDBC resource for that database in the GlassFish administration that is named "jdbc/demoResource".

I've been using GF nightly builds recently that include Jersey 2.10.1 (or even 2.10.4 now). The "com.acme.User" JPA entity is quite hackish; it uses the built-in PostgreSQL pseudo-table "user" so that you don't have to create an extra table for the test. If Postgres is not an option, just change the JDBC connection pool in GF accordingly and optionally adjust the User entity mapping.

After deploying, you should get the cited exception after a little time upon making an HTTP GET request to http://[host]:8080/DeclarativeLinkingDemo/users. If you unregister the DeclarativeLinkingFeature in "com.acme.DeclarativeLinkingDemoApplication", the current Postgres user (in my example) will just be returned without errors.

The ZIP file just contains my raw Eclipse project export with the sources and project setting files (sources also included in the WAR).

I hope you can make it run relatively easily now, feel free to ask for support if you think I can help with it.

Let me reiterate: the problem must be that the Declarative Linking feature recurses through all the properties found on a JAXB object to be marshalled. If that object is proxied by a mechanism like JPA, this number of properties is large and recursing through their whole hierarchy takes very long, and in the case of EclipseLink as the JPA provider eventually runs into an Exception.

Thanks,
Adam

Comment by gdavison [ 18/Feb/15 ]

Sorry about the problem you were seeing, I am looking into this now and it appears that for most JPA implementations that the extra field is labeled as being synthetic, so I am going to look at whether filtering those out solves the problem.

Comment by Adam Lindenthal [ 27/Feb/15 ]

There is a pull-request from Gerard waiting for last few small steps before being merged.

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

Regards,
Adam

Comment by Adam Lindenthal [ 02/Mar/15 ]

Pull request from gdavison was merged, closing the issue. Thanks for reporting.





[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-1988] Add Mvc Velocity support Created: 23/Jul/13  Updated: 02/Mar/15

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

Type: New Feature Priority: Minor
Reporter: paulkmoore Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: mvc, velocity

 Description   

The current (2.1) implementation of Jersey supports JSP and FileMarker Mvc integration through the following modules:

jersey-mvc-jsp
jersey-mvc-filemarker

This feature request is to integrate Apache Velocity support in a similar manner.



 Comments   
Comment by Libor Kramolis [ 01/Aug/13 ]

Note: Paul Moore is currently working on implementation.

Comment by Adam Lindenthal [ 25/Feb/15 ]

Hi Paul, are you still planning to develop this feature?

Comment by paulkmoore [ 27/Feb/15 ]

Hi Adam, I got quite far down the track implementing this in Oct/Nov 2013. Michal Gajdos reviewed the code and made some minor changes and it was ready to be integrated. Unfortunately in the same time frame, Oracle dropped production support for Glassfish, which was (very) annoying. I moved all development to WildFly and haven't touched Glassfish since. If there's interest I could point you at the last know good point in my GitHub repo, but I'm not planning to revisit the Jersey/Glassfish code base any time soon I'm afraid.

Comment by Adam Lindenthal [ 02/Mar/15 ]

Hi Paul,

thanks for your answer. Said to hear you left Jersey, but I understand your reasons.
I do not know about any plans to implement Velocity support internally. However, if you have done some portion of work on that, it would be waste of your time not to share it somewhere. Depending on the status of your work, it might be worth to create a gist, pull-request, link to the github repo, blogpost or whatever and share it here (and elsewhere) in case someone would be willing to continue where you stopped.
I'll talk to Michal to learn in what state your source code is and what's left to be done.

Anyway, many thanks,
Adam





[JERSEY-2763] @PathParam with commas to List<MyObject> Created: 25/Jan/15  Updated: 02/Mar/15

Status: In Progress
Project: jersey
Component/s: core
Affects Version/s: 2.15
Fix Version/s: backlog

Type: Bug Priority: Minor
Reporter: guillaume.l Assignee: Michal Gajdos
Resolution: Unresolved 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-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-2713] jersey 2.13 charset ISO-8859-9 is not working Created: 25/Nov/14  Updated: 27/Feb/15  Resolved: 27/Feb/15

Status: Resolved
Project: jersey
Component/s: release
Affects Version/s: 1.18.1, 2.13
Fix Version/s: None

Type: Bug Priority: Major
Reporter: creativeUser Assignee: Unassigned
Resolution: Invalid Votes: 0
Labels: incomplete
Remaining Estimate: 2 weeks
Time Spent: Not Specified
Original Estimate: 2 weeks
Environment:

Java Tomcat 7 Jersey 2.13



 Description   

The charset for Turkish is not responding in 2.13 release but works for 1.18
Details;

http://stackoverflow.com/questions/26897632/restful-service-jersey-2x-charset-iso-8859-9-is-not-working



 Comments   
Comment by Libor Kramolis [ 14/Jan/15 ]

I can not reproduce the problem. Try to prepare reproducible test case. I've prepared unit test for you - https://gist.github.com/shamoh/692ff96e86f5ce775d51.

Comment by Michal Gajdos [ 18/Feb/15 ]

Hi, have you tried to run the provided test-case?

Comment by Adam Lindenthal [ 27/Feb/15 ]

Seems that creativeUser is not an activeUser any more

I will close the issue now, feel free to request reopening in case you can provide a reproducible test case (e.g. based on LIbor's code).

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-2772] Tomcat memory leak on undeploy Created: 03/Feb/15  Updated: 27/Feb/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: 0
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.





[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-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-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-2724] The proxy client throws UnsupportedOperationException when calling toString Created: 07/Dec/14  Updated: 24/Feb/15  Resolved: 24/Feb/15

Status: Resolved
Project: jersey
Component/s: extensions
Affects Version/s: 2.13
Fix Version/s: 2.17

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


 Description   

If I call toString() on a proxy client, it throws an UnsupportedOperationException:

@Path("/")
interface MyClient {
    @GET String get();
}

@Test
public void buildClient() {
    WebTarget target = ClientBuilder.newClient()
                            .target("http://localhost/");

    MyClient client = WebResourceFactory.newResource(MyClient.class, target);

    client.toString(); //<-- throws java.lang.UnsupportedOperationException: Not a resource method
}

It's not a good thing to throw exceptions in toString

Pull request:
https://github.com/jersey/jersey/pull/131



 Comments   
Comment by Jakub Podlesak [ 09/Dec/14 ]

Thanks for the pull request, we will incorporate this after 2.14 is out (it is being released nowadays).

Comment by eiden [ 09/Dec/14 ]

Great. I have some other suggestions for improvement of the proxy client. Should I create JIRA tickets for those suggestions, or do you prefer to take the discussion on the dev mailing list first?





[JERSEY-1658] NPE on multipart/form-data if boundary not set Created: 16/Jan/13  Updated: 24/Feb/15

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

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


 Description   

I am using the @FormDataParam annotation to upload a file. I use a REST client to create a request which does not contain any file. Therefore it also does not contain a "boundary" attribute in the Content-Type header. Jersey issues a NullPointerException on this request. It should rather return 400 Bad Request.

Method is unquoteMediaTypeParameters() in class MultiPartReaderClientSide



 Comments   
Comment by raminz71 [ 23/Mar/13 ]

I am facing the same problem. Regardless of uploading a file or not. In the Controller i tried different MediaTypes.
@Consumes("multipart/mixed") and
@Consumes(MediaType.MULTIPART_FORM_DATA)

java.lang.NullPointerException
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.unquoteMediaTypeParameters(MultiPartReaderClientSide.java:227)

Comment by kaandok [ 05/Sep/13 ]

Same here as well, we have a multipurpose endpoint that can sometimes contain files and sometimes an empty request.
If this is going to be fixed, my 2 cents is that no predefined error should be returned to the client.

Is there any reason an empty multipart/form-data request is a bad request warranting an http 400 response?

Comment by Libor Kramolis [ 20/Jan/14 ]

What type of connector do you use on client side?
There is an issue to modify headers in WriterInterceptor or MessageBodyWriter using other than default Connector (HttpUrlConnector), see JERSEY-2123 or JERSEY-2206.

Do you use Apache or Jetty or Grizzly connector in your app? Is it your case? Thanks.





[JERSEY-1377] Interaction of jersey server with multipart with cxf client fails Created: 16/Aug/12  Updated: 24/Feb/15  Resolved: 24/Feb/15

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

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

Windows 7 and tomcat 7


Tags: cxf, jersey, multipart

 Description   

When using a jersey client to retrieve multipart from a jersey server in a jersey-client/cxf mixed app reports that there is a missing start boundary.

After debugging I found that MediaType in jsr311-api-1.0.jar (used by cxf 2.2.2) is converting headers to lowercase. Since com.sun.jersey.multipart.Boundary.java is generating boundaries as
return new StringBuilder("Boundary_").
append(boundaryCounter.incrementAndGet()).
append('_').
append(new Object().hashCode()).
append('_').
append(System.currentTimeMillis()).
toString();
}

with an Upper case "Boundary", cxf would fail to find it in the body after the boundary case in the Content-Type is lowercased.

I am using jersey-client, yet javax.ws.rs is loaded from cxf given that the META-INF/services/javax.ws.rs.ext.RuntimeDelegate is found first in cxf and not in jersey-core.(I suspect that the web loader in tomcat finds "c" before "j")

Jersey's header and body are practically OK. It would be a cxf bug, except that it has to do with classpath conflicts between cxf and jersey-client. This could be easily fixed in Jersey by producing an all lowercase boundary.

The actual issue is that I have a legacy app that mixes both cfx and jersey-client. IMPORTANT: I am using the jersey client but cxf takes over. It would be OK for cfx to take over and it would do the right thing had it been lowercase.

The current workaround is to:
extract jersey's javax.ws.rs.ext.RuntimeDelegate
build the client WAR with the structure WEB-INF/classes/META-INF/services/javax.ws.rs.ext.RuntimeDelegate
start the app.

This is not entirely proper since the portions of the legacy application that use cxf would load jersey javax.ws.rs now.

The real fix is to force jersey-client to load its own classes, not going to the RuntimeDelegate et al to get the class names it requires. Going to get class names for RuntimeDelegate breaks jersey's encapsulation. It is an invitation for bugs.



 Comments   
Comment by Martin Matula [ 21/Aug/12 ]

OK, so the issue is that the Jersey uses RuntimeDelegate to get internal classes instead of just using them directly. And you are saying if we fix this, it will fix the issue, right?
Note that JAX-RS API itself uses RuntimeDelegate, so if it is in fact not the jersey client, but the jax-rs api that calls RuntimeDelegate, we can't fix it. Do you have any particular calls to RuntimeDelegate in mind?

Comment by Michal Gajdos [ 10/Sep/12 ]

Actually converting headers to lowercase is not done by javax.ws.rs.core.MediaType but the problem is in CXF (and because of the fact that RuntimeDelegate service class is picked up from CXF instead of Jersey).

org.apache.cxf.jaxrs.impl.MediaTypeHeaderProvider from CXF is responsible for parsing header lines and creating MediaType instance using the MediaType(String type, String subtype, Map<String, String> parameters) constructor. At this point the parameter names and values are already in lowercase (see [1] line 67-68).

Before touching anything in the Jersey code, can you change the version of CXF you're using? It seems that this problem has been fixed in CXF 2.2.5 (see [2], lines 67-68).

[1] http://grepcode.com/file/repo1.maven.org/maven2/org.apache.cxf/cxf-rt-frontend-jaxrs/2.2.2/org/apache/cxf/jaxrs/impl/MediaTypeHeaderProvider.java#67
[2] http://grepcode.com/file/repo1.maven.org/maven2/org.apache.cxf/cxf-rt-frontend-jaxrs/2.2.5/org/apache/cxf/jaxrs/impl/MediaTypeHeaderProvider.java#67

Comment by Michal Gajdos [ 12/Sep/12 ]

The issue with wrong RuntimeDelegate instance cannot be fixed in Jersey code in this case. As I mentioned the problem is in HeaderDelegate<MediaType> implementation present in CXF and an instance of this class is obtained and held in MediaType class itself (see [1], lines 44-45) which is in JAX-RS API.

One thing you can do is to set the RuntimeDelegate instance yourself (before any other Jersey code is invoked):

RuntimeDelegate.setInstance(new com.sun.ws.rs.ext.RuntimeDelegateImpl());

[1] http://grepcode.com/file/repo1.maven.org/maven2/javax.ws.rs/jsr311-api/1.1.1/javax/ws/rs/core/MediaType.java#44

Comment by jaimegarza61 [ 12/Sep/12 ]

I have realized that the only fix that could work for the Jersey team is for Jersey to produce headers in lower case.

I have set the runtime delegate with META-INF property files, which is similar to the last suggestion, and I am just waiting to find the shoe drop on the cxf side, with some kind of CXF client issue. I will be trying to upgrade my cxf across the company. Thanks for the comments.





[JERSEY-2490] Declarative linking recurses into too many things Created: 22/Apr/14  Updated: 24/Feb/15  Resolved: 24/Feb/15

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

Type: Improvement Priority: Major
Reporter: ojacobson Assignee: Libor Kramolis
Resolution: Fixed Votes: 2
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

There's no way to stop @InjectLink processing from descending into an object, making it impractical to use code like

@InjectLink(
	resource = Hex.class,
	method = "create",
	condition = "${instance.canCreateHex}")
private String createHex;
private SecurityContext securityContext; // trouble

@JsonInclude(Include.NON_NULL)
public String getCreateHex() {
	return createHex;
}

@JsonIgnore
public boolean isCanCreateHex() {
	return securityContext.isUserInRole("ROLE_CREATE_HEX");
}

Spring-security's SecurityContext is the specific case that bit me, since it contains a huge amount of data, including whole classloaders. Any large data structure would cause the same problem.

Having an @NoLink annotation, or stopping recursion at transient fields, would make it easier to use non-serialized information to decide whether to generate links.



 Comments   
Comment by Libor Kramolis [ 22/Apr/14 ]

I'm sorry I don't see your problem. Where is a recursion? What field should be transient? On which fields/methods could be @NoLink annotation used and what is meaning of that annotation? Thanks for more explanation.

Comment by ojacobson [ 25/Apr/14 ]

The SecurityContext field takes a very long time to scan for link injection, because it connects to a very large data structure including ClassLoaders and other large, "internal" objects. It's not technically part of the response, and won't be serialized by Jackson (note the lack of @JsonInclude), but @InjectLink processing doesn't know that, so inspects it "just in case" I send it back.

It turns out that having large contextual objects attached to responses can be useful. The example in the ticket uses a context object (the SecurityContext) to control the behaviour of other response processors (Jackson, InjectLink processing). Unfortunately, while Jackson is smart enough not to recurse through objects it's not serializing, there's no mechanism for InjectLink processing to do the same thing.

Rather than building a special-case thing that tries to recognize this kind of context object, it'd be nice (see ticket type) if there was a way to mark them explicitly, to stop InjectLink from considering them or recursing through them.

Comment by Libor Kramolis [ 28/Apr/14 ]

Thanks for your explanation.

Community contribution is welcome.

Comment by jmetcher [ 30/Jan/15 ]

I had the same issue with a UriInfo object in a transient field. It turns out that UriInfo is not ultimately accessible to reflection (many layers down there's a logger with an inaccessible field), so this ended up throwing an InvalidAccessExecption. Having link injection recurse down into a variable that has been explicitly marked with @XmlTransient makes no sense at all, hence much time wasted debugging this one.

Edit: my bad - I wasn't aware that @XmlTransient is non-transitive, so it does make sense to recurse down. Still would be good to be able to turn that off.





[JERSEY-2510] @Context parameter injection doesn't respect a @Qualifier Created: 07/May/14  Updated: 24/Feb/15  Resolved: 12/May/14

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

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


 Description   

DelegatedInjectionValueFactoryProvider.getInjectee(Parameter) sets InjecteeImpl.setRequiredQualifiers(Collections.emptySet()) instead of grabbing qualifier annotations from the parameter being injected, so any Factory bound to that class could be called, ignoring the qualifier to which that Factory was bound (via ServiceBindingBuilder.qualifiedBy(Annotation)).



 Comments   
Comment by Michal Gajdos [ 12/May/14 ]

Using @Context with @Qualifier is not required by JAX-RS. Is it possible for you to inject parameter via @Inject and bind appropriate object to the contract in HK2 Binder?

Feel free to reopen the issue.





[JERSEY-2500] InternalServerErrorException is not caught by ExceptionMapper<WebApplicationException> Created: 30/Apr/14  Updated: 24/Feb/15  Resolved: 26/May/14

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

Type: Bug Priority: Major
Reporter: jan.supol Assignee: Unassigned
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Spec. Section 4.2.2, step 7 says:

Otherwise, the server runtime MUST generate a generate an InternalServerErrorException,
a subclass of WebApplicationException with its status set to 500

Having a mapper:

@Provider
public class WebAppExceptionMapper implements
		ExceptionMapper<WebApplicationException> {

	@Override
	public Response toResponse(WebApplicationException exception) {
             ...
	}
}

and a resource:

@Path("resource")
public class Resource {
	@GET
	@Path("fail")
	@Produces(MediaType.TEXT_PLAIN)
	public Resource fail() {
		return this;
	}
}

The status 500 is returned from the server with message containing:

<b>root cause</b> <pre>org.glassfish.jersey.message.internal.MessageBodyProviderNotFound
Exception: MessageBodyWriter not found for media type=text/plain, type=class Resource

Either InternalServerErrorException is not thrown, or the exception is not mapped by the mapper






[JERSEY-2538] java.lang.IncompatibleClassChangeError when loading AnnotatedClassVisitor Created: 08/Jun/14  Updated: 24/Feb/15  Resolved: 17/Jun/14

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

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


 Description   

I am currently using jersey-server 2.9 with datanucleus-appengine 2.1.2 that depends on asm 4.0. When the class AnnotatedClassVisitor from AnnotationAcceptingListener is loading, i have a java.lang.IncompatibleClassChangeError.



 Comments   
Comment by sberoard [ 08/Jun/14 ]

i have found where the problem is coming from. Though you repackaged the asm package 'jersey.repackaged.org.objectweb.asm', imports in AnnotationAcceptingListener are still referencing 'org.objectweb.asm'.
When i reset the imports with 'jersey.repackaged.org.objectweb.asm' in AnnotationAcceptingListener, i managed to get it right.

Comment by Miroslav Fuksa [ 11/Jun/14 ]

hi,

thanks for the issue. I am moving it to the backlog.

Mira

Comment by Miroslav Fuksa [ 17/Jun/14 ]

Hi,

after investigation it looks like ASM imports of the AnnotationAcceptingListener class are all properly changed to use the repackaged ASM classes in the jersey server jar.

please provide a reproducible test case if you still have the problem with this issue and create a new bug.

Thanks
Mira





[JERSEY-2580] Hitting application with Incorrect parameters makes JVM to crash Created: 08/Jul/14  Updated: 24/Feb/15  Resolved: 29/Jul/14

Status: Resolved
Project: jersey
Component/s: core
Affects Version/s: 1.18.1, 2.10.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: kevin.onik Assignee: Unassigned
Resolution: Incomplete Votes: 0
Labels: unplanned
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Tomcat 7.0.45, JDK 6u45, Jersey 2.10.1



 Description   

Calling a DELETE method which expects a parameter, without the parameter for several times, causes the vm to fill up the heap until it shuts down the VM with out of memory error.
See attachments for more info.



 Comments   
Comment by kevin.onik [ 08/Jul/14 ]

The Application code is:

@Path("service")
public class Service {

    @DELETE
    @Path("/delete/{parameter}")
    public Response delete(@PathParam("parameter") String parameter) {
        return Response.ok().entity("delete, parameter: '" + parameter + "'").type("application/x-www-form-urlencoded").build();
    }
    
}

and the web.xml:

web.xml
    <servlet>
        <servlet-name>DeleteSample</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>
            <param-value>com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>DeleteSample</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

    <error-page>
        <error-code>404</error-code>
        <location>/error.html</location>
    </error-page>
    
    <error-page>
        <error-code>405</error-code>
        <location>/error.html</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/error.html</location>
    </error-page>

    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>

A log from calling the method without providing the parameter:

http://i.imgbox.com/YZ8cHLkO.jpg

Comment by Michal Gajdos [ 08/Jul/14 ]

In the environment field you mention Jersey 2.10.1 but the excerpt from web.xml points to Jersey 1.x. Have you tried this on Jersey 2.x as well? Thanks.

Comment by kevin.onik [ 10/Jul/14 ]

Yes I have tested with both versions and the same issue exists.

Comment by Michal Gajdos [ 10/Jul/14 ]

Thanks for clarifying! Moving to backlog.

Comment by Michal Gajdos [ 10/Jul/14 ]

Hi, would it be possible for you to provide a simple test case? I am not able to simulate this problem (my jvm behaves nicely). Thanks!

Comment by Adam Lindenthal [ 29/Jul/14 ]

Hi Kevin,

I re-tried and also did not manage to reproduce. Are you sure you ruled out all the other influences which might be causing your issue? Have you tried it with really the simple barebone one-service example (like the one you've attached)?

I am sorry, but unless you provide us with a reproducible test case, we cannot really help you. I have to close the issue as incomplete for now. If you manage to create an app + test case that shows the described behaviour, we can reopen it eventually.

Thanks,
Adam





[JERSEY-2609] Request handler being called multiple times from JerseyTestNg integration test Created: 11/Aug/14  Updated: 24/Feb/15  Resolved: 30/Sep/14

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

Type: Bug Priority: Major
Reporter: lobsang Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: async, test-ng
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File jersey-integration-test-issue.tgz    

 Description   

I am developing an integration test based on the JerseyTestNg class.

Within the test I am performing one synchronous POST request to a resource which handles processing of that request asynchronously using AsyncResponse.

For handling my single POST request I can observe that my request handler is called multiple times (>5 times in my stripped down example, >20 times in my real code). My expectation is that is called exactly once.

I enclosed a stripped down example which can be used to reproduce the issue.

The problem DOES NOT occur when I run the integration test against a jetty instance running within a different JVM.



 Comments   
Comment by lobsang [ 11/Aug/14 ]

Since I can't attach any files to this issue you can find an stripped down example project which reproduces the bug under the following link: https://dl.dropboxusercontent.com/u/106020427/jersey-integration-test-issue.tgz

Comment by Adam Lindenthal [ 27/Aug/14 ]

Attaching the test case provided by lobsang.

Comment by Adam Lindenthal [ 27/Aug/14 ]

Hi, thanks for creating the issue and preparing the reproducible test case. I am moving the issue to backlog, we will get to it in one of the future sprints.

Adam

Comment by lobsang [ 30/Sep/14 ]

After having read the changelog for 2.13 I suspected this problem could have been fixed together with JERSEY-2616. As it turns out, it was!

Comment by Adam Lindenthal [ 30/Sep/14 ]

Nice catch, thanks for pointing that out. I am thus closing the issue as duplicate.

Cheers,
Adam





[JERSEY-2463] Memory leak of response.readEntity when using JAX-RS Client API Created: 28/Mar/14  Updated: 24/Feb/15  Resolved: 07/Aug/14

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

Type: Bug Priority: Critical
Reporter: jwjang0702 Assignee: Jakub Podlesak
Resolution: Fixed Votes: 4
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

OS : Ubuntu 13.10 64bit
WAS : apache-tomcat-7.x
JDK : jdk1.7.0_45


Attachments: PNG File entry-detail.png     Zip Archive jersey-2463.zip     PNG File similar-entries.png    
Issue Links:
Dependency
depends on HK2-205 Memory leak in PerThreadContext Closed
Related
is related to JERSEY-2676 HK2 ServiceLocator Cache growing too... Resolved
Tags: incomplete, memory-leak, unplanned

 Description   

We detected memory leak in response.readEntity.

When we use "response.readEntity(String.class)", there were not memory leak.
But when we use "MediaType.TEXT_XML" and "response.readEntity(ErrorBean.class);", then memory leak was occurred.

The following table is the result of 'jstat -gcutil' when memory full is occurred.

S0 S1 E O P YGC YGCT FGC ...
0.00 0.00 98.78 99.96 99.36 10975 176.220 2665 ...
0.00 0.00 100.00 99.96 99.36 10975 176.220 2666 ...
0.00 0.00 100.00 99.96 99.36 10975 176.220 2666 ...

And the following is the problematic codes.
They are called in JAX-RS Resource deployed on tomcat7.

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://xxxx.xxx");		
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_XML);
try {
  response = invocationBuilder.post(Entity.entity("<test><id>1234</id></test>", MediaType.TEXT_XML));
  ErrorBean err = response.readEntity(ErrorBean.class);
} catch(Exception e) {
  // handle Exception
} finally {
  if (response != null) {
    response.close();
  }
}
@XmlRootElement(name = "error")
public class ErrorBean {	
	private String code;
	private String message;
	private String resource;
	
	public ErrorBean() {}
	
	public String getCode() {
		return code;
	}
	
	public void setCode(String code) {
		this.code = code;
	}
	
	public String getMessage() {
		return message;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	public String getResource() {
		return resource;
	}
	
	public void setResource(String resource) {
		this.resource = resource;
	}
}


 Comments   
Comment by jwjang0702 [ 28/Mar/14 ]

Regarding above issue, refer to Tomcat log below.

org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [org.glassfish.hk2.internal.PerThreadContext$1] (value [org.glassfish.hk2.internal.PerThreadContext$1@5ea04c]) and a value of type [java.util.HashMap] (value [{SystemDescriptor(
        implementation=org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider
        contracts={javax.xml.parsers.SAXParserFactory}
        scope=org.glassfish.hk2.api.PerThread
        qualifiers={}
        descriptorType=PROVIDE_METHOD
        descriptorVisibility=NORMAL
        metadata=
        rank=0
        loader=org.glassfish.hk2.utilities.binding.AbstractBinder$2@446dddc4
        proxiable=false
        proxyForSameScope=null
        analysisName=null
        id=40
        locatorId=252766
        identityHashCode=150639093
        reified=true)=org.glassfish.jersey.message.internal.SecureSaxParserFactory@7a84706d}]) 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 minfrin [ 11/Apr/14 ]

Also seeing the same thing:

SEVERE: The web application [] created a ThreadLocal with key of type [org.glassfish.hk2.internal.PerThreadContext$1] (value [org.glassfish.hk2.inte
rnal.PerThreadContext$1@214613fa]) and a value of type [java.util.HashMap] (value [{SystemDescriptor(
        implementation=org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider
        contracts={javax.xml.parsers.SAXParserFactory}
        scope=org.glassfish.hk2.api.PerThread
        qualifiers={}
        descriptorType=PROVIDE_METHOD
        descriptorVisibility=NORMAL
        metadata=
        rank=0
        loader=org.glassfish.hk2.utilities.binding.AbstractBinder$2@adbe555
        proxiable=false
        proxyForSameScope=null
        analysisName=null
        id=68
        locatorId=0
        identityHashCode=1789736196
        reified=true)=org.glassfish.jersey.message.internal.SecureSaxParserFactory@1173d053}]) 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 Libor Kramolis [ 24/Apr/14 ]

And does the problem occur because of repeated stop/start or (re)deploy of the application? Or it just occurs in fresh tomcat and newly installer jersey application? How many times to code has to be call the memory leak occurs?

Thanks.

Comment by Libor Kramolis [ 25/Apr/14 ]

I'm sorry I am not able to reproduce the problem. I have been trying to find the test case to reproduce the memory leak. But I am not able to move forward without more info from reporter.

@jwjang0702, please could you prepare reproducible test case, simple maven project to reproduce the problem you have? Thanks a lot.

Comment by jwjang0702 [ 28/Apr/14 ]

Here is pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>mytest</groupId>
	<artifactId>mytest</artifactId>
	<version>0.0.1</version>
	<packaging>war</packaging>

	<properties>
		<maven.test.skip>false</maven.test.skip>

		<java.version>1.7</java.version>
		<javax.servlet.version>3.1.0</javax.servlet.version>

		<org.glassfish.jersey.version>2.7</org.glassfish.jersey.version>
		<org.reflections.version>0.9.9-RC1</org.reflections.version>
	</properties>

	<dependencies>		
		<dependency>
		  <groupId>javax.servlet</groupId> 
		  <artifactId>javax.servlet-api</artifactId> 
		  <version>${javax.servlet.version}</version> 
		  <scope>provided</scope> 
	  	</dependency>
	  
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId> 
	  		<artifactId>jersey-container-servlet</artifactId>
	  		<version>${org.glassfish.jersey.version}</version>
		</dependency>
		
		<dependency> 
		    <groupId>org.glassfish.jersey.media</groupId> 
		    <artifactId>jersey-media-moxy</artifactId> 
		    <version>${org.glassfish.jersey.version}</version>
		</dependency>
	  
		<dependency>
		 	<groupId>org.glassfish.jersey.ext</groupId> 
			<artifactId>jersey-bean-validation</artifactId>
			<version>${org.glassfish.jersey.version}</version>
		</dependency>
	</dependencies>

	<build>
		...
	</build>
</project>

And.. You must do a load test for several minutes or an hour for each AS-IS & TO-BE codes in the below table.
and must do memory monitoring.
AS-IS codes result in memory leak, but, TO-BE codes not

AS-IS
response = invocationBuilder.post(Entity.entity("xml format data", MediaType.TEXT_XML));
ErrorBean err = response.readEntity(ErrorBean.class);
TO-BE
JAXBContext context = context = JAXBContext.newInstance(ErrorBean.class);
String str = response.readEntity(String.class);				
ErrorBean err = ErrorBean.class.cast(context.createUnmarshaller().unmarshal(new StringReader(str.trim())));
Comment by Libor Kramolis [ 28/Apr/14 ]

Please, could you provide us complete test application, server and client side including execution steps (shell or maven) to run server and client side? I see a lot of variables and I want to be sure I have same test case as you.

In issue description you speak about bigger memory consumption when JAXB entity used. But at following parts you speak about memory leak and I don't see any clues to memory leak problem. I am not sure what part of your application has problem if it is server side or client side. API you mention is client side. Looking at the tomcat log I could say it is server side.

Please, try to prepare me the test application. Thanks.

Comment by Libor Kramolis [ 28/Apr/14 ]

I have already fixed JERSEY-2496 that fixed server side memory leak while doing deploy and undeploy operation multiple times (on WLS). This is not probably your case but I will notice you whenever is SNAPSHOT build available in maven repository to use it.

Comment by jwjang0702 [ 28/Apr/14 ]

The problematic code is the below JAX-RS Client code running on the server-side webresource(or servlet) of tomcat.

response.readEntity(ErrorBean.class); 
// cause memery leak when reading xml format data like "<error><code>111</code><message>error</message>...</error>"

call flow is as follows
==> http client(browser or http client app)
calls a server-side web resource
which has jax-rs client code which calls other restful web service on a separate tomcat.

I think you can easily make a test code.

And..
The problematic code does not produce functional errors. It's working well.
but we found that "ScopedJaxrsResponse" of jax-rs client cause memory leak when reading xml format data
FullGC did not collect garbage memory in Old Gen. of jvm when we did load test about 200 tps for an hour.

Comment by jwjang0702 [ 28/Apr/14 ]

I correct mistyping : "ScopedJaxrsResponse" ==> "org.glassfish.jersey.client.InboundJaxrsResponse"
I could not found any clues that "ScopedJaxrsResponse" is called.

Comment by Libor Kramolis [ 30/Apr/14 ]

Test application attached.

How to reproduce the problem.

  1. Build a war file: mvn package
  2. Copy the war file from target to Tomcat webapps directory
  3. Start the Tomcat, application is running at http://localhost:8080/jersey-2463-2.9-SNAPSHOT/resource URL
  4. Run "unit" test app to invoke the URL for lomg time: mvn install

The problem is on server (Tomcat) side. The HK2 class PerThreadContext collects map entries: org.jvnet.hk2.internal.SystemDescriptor = org.glassfish.jersey.message.internal.SecureSaxParserFactory, that are never cleaned.

Jersey code that uses HK2's PerThread:
https://github.com/jersey/jersey/blob/e3d0c1b14eccf108262279f3f15ffbe8514a322d/core-common/src/main/java/org/glassfish/jersey/message/internal/SaxParserFactoryInjectionProvider.java#L71

Comment by Libor Kramolis [ 06/May/14 ]

Screenshots of YourKit Java Profiler:

  • list of similar map entries
  • detail of one entry
Comment by Libor Kramolis [ 29/May/14 ]

Waiting for fix in HK2: HK2-205

Comment by Libor Kramolis [ 22/Jun/14 ]

I just tried hk2 2.3.0-b09 but the problem remains.

The HK2 still collects map entries with key org.jvnet.hk2.internal.SystemDescriptor and value org.glassfish.jersey.message.internal.SecureSaxParserFactory.

Comment by Libor Kramolis [ 16/Jul/14 ]

Jakub is working on it together with hk2's John.

Comment by Jakub Podlesak [ 07/Aug/14 ]

Fixed in the master branch.

Comment by karparov [ 15/Aug/14 ]

Hi all,

It's very good that this issue is finally resolved.
However, the fix version is "backlog" and it's not clear whether this will be included in Jersey 2.12.
I checked that the related HK2-205 issue is fixed in HK2 version 2.3.0 but Jersey 2.12 has HK2 version 2.3.0-b10 dependency (which I'm not sure includes the HK2-205 fix).

Can you please provide information about the Jersey fix version?

Thanks,
Serafim

Comment by nhurion [ 22/Aug/14 ]

Hello,

I'm having the same issue using jersey client 2.4.1 and 2.6. I've bumped version of hk2 to 2.3 but it did not solve the issue.
The work around provided by jwjang0702 (the manual unmarshalling) did work for me.

Do you plan to release a fix in a java 6 version of jersey client? and if you do, when?

Thanks,
Nicolas.





[JERSEY-2711] Quality factor does not work for multiple output MIME types Created: 21/Nov/14  Updated: 24/Feb/15  Resolved: 28/Jan/15

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

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

Attachments: Zip Archive jersey-2711-reproducer.zip    

 Description   

I want to set application/x-javascript as default output so using the qs as below:

    @GET
    @JSONP(queryParam = "callback")
    @Produces({"application/x-javascript;qs=2", "application/json"})
    public AppSettingsWrapper loadClientAppSettings() {
        AppSettingsWrapper appSettingsWrapper = new AppSettingsWrapper();
       //...business code
        return appSettingsWrapper;
    }

Jersey Application code:

public class XXXServiceApplication extends ResourceConfig {

    /**
     * Register JAX-RS application components.
     */
    public XXXServiceApplication() {
        super(JacksonFeature.class, JsonObjectMapperProvider.class);
        super.setApplicationName("mcws");

        register(RequestContextFilter.class);
        register(CORSResponseFilter.class);
        register(ValidationConfigurationContextResolver.class);
        register(LoggingFilter.class);
        register(XXXApplicationEventListener.class);

        packages("com.XXX");
    }


}

However, when the client send the request with header Accept: /, the server always return the response with content-type:application/json.

It works when client request with header Accept: application/x-javascript. I hopefully want to produce jsonp result default.

An ideas?



 Comments   
Comment by Jakub Podlesak [ 10/Dec/14 ]

The bug is not specific to JSON with padding support, but is also not general.
I.e. server quality parameter works in certain cases even with multiple media types specified as produced on a resource method.

In any case, i am able to reproduce this.

Comment by Adam Lindenthal [ 23/Jan/15 ]

Hi Vickl,

even though Jakub wrote, that he was able to reproduce the issue, I am unfortunately not. I talked to Jakub and it works fine for him now as well (but he promised to re-try).

I am attaching a zip with a trivial (non)reproducer test case base on our archetype example project. Would you be able to adjust it, so that it reproduces the issue? I am always getting the expected content type and the response correctly wrapped with the JSONP callback.

Currently the example uses Jersey 2.7 (the same version you reported as affected), but I've tried 2.6 up to current with the same results (feel free to try that as well, it involves just changing one constant in the pom.xml).

Many thanks,
Adam

Comment by Adam Lindenthal [ 28/Jan/15 ]

Hi Vickl,

unfortunatelly, still did not succeed reproducing it. Thus, closing as "cannot reproduce".
If you will be able to provide more information that will lead to successful, repeatable reproduction, feel free to request re-opening.

Regards,
Adam





[JERSEY-2706] Jersey 2.13 doesn't work in IBM WebSphere Liberty Profile Created: 17/Nov/14  Updated: 24/Feb/15  Resolved: 09/Feb/15

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

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

IBM WebSphere Liberty Profile 8.5.5.3 + a simple JAX-RS application



 Description   

Built a war file with a simple JAX-RS application relying on Servlet 3 features to auto-write everything (so no web.xml) using @ApplicationPath on a class that extends ResourceConfig.

When deploying this war file to Tomcat, it works.
Deployed to Jersey it fails with the following NPE:

Stack Dump = java.lang.NullPointerException
        at org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer.mappingExists(JerseyServletContainerInitializer.java:350)
        at org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer.addServletWithApplication(JerseyServletContainerInitializer.java:286)
        at org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer.onStartupImpl(JerseyServletContainerInitializer.java:176)
        at org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer.onStartup(JerseyServletContainerInitializer.java:143)
        at com.ibm.ws.webcontainer.webapp.WebApp.initializeServletContainerInitializers(WebApp.java:2324)
        at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:954)
        at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:6092)
        at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.startWebApp(DynamicVirtualHost.java:440)
        at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.createRunnableHandler(DynamicVirtualHost.java:252)
        at com.ibm.ws.http.internal.VirtualHostImpl.discriminate(VirtualHostImpl.java:458)
        at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:203)
        at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:448)
        at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:382)
        at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:282)
        at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:253)
        at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:174)
        at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:83)
        at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:502)
        at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:559)
        at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:908)
        at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:991)
        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 Adam Lindenthal [ 02/Dec/14 ]

Hi Zoltan, thank you for submitting this.
Without knowing much about WebSphere, I checked the stack trace and the relevant code and it looks like the ServletContext that Jersey gets from the underlying container differs with WS.
Just to rule everything out, I would ask you to double check the configuration and ideally to provide some minimalistic testcase (sources for a war, that works on tomcat and does not work on WS).
Anyway, I guess we should add some extra null checks to the mappingExists() method.

Moving the issue to backlog, so that we can plan the work on it.

Regards,
Adam

Comment by Marek Potociar [ 04/Dec/14 ]

IMO, this is really a bug that should be filed agains WebSphere. A call to ServletContext.getServletRegistrations().values() returns null as one of the servlet registration values.

This is IMO not an expected behavior in an Servlet API implementation.

Comment by Adam Lindenthal [ 04/Dec/14 ]

Marek: Agreed, could be bug in WS or maybe even something wrong with the app configuration. I put that to backlog just because I think we should fail more gracefully if we do not get proper ServletContext, the mappingExists() method does not count with nulls.

But of course, feel free to close this.

Comment by Marek Potociar [ 09/Feb/15 ]

I disagree. We should not try to check for null values returned from API that is expected to never return null values. Closing the issue.





[JERSEY-1729] @Uri parses paths wrongly. Created: 13/Feb/13  Updated: 24/Feb/15  Resolved: 13/Feb/15

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

Type: Bug Priority: Major
Reporter: Miroslav Fuksa Assignee: Unassigned
Resolution: Works as designed Votes: 0
Labels: None
Remaining Estimate: 3 hours
Time Spent: Not Specified
Original Estimate: 3 hours


 Description   

Example:

This is resource method:

        @GET
        @Path("{param}")
        public String doGet(@Uri("resource?id={param}") WebTarget webTarget) {
            return webTarget.getUri().toString();
        }

for param=parameter it should return:
resource?id=parameter

but it returns:
/resource%3Fid=parameter

"?" should not be percent encoded. This is a case for relative path.

Another case for absolute path:

The same code injecting target with @Uri("resource?id=

{param}

" should be resolved to http://oracle.com?id=parameter but is resolved to http://oracle.com?/id=parameter
(/ before id).



 Comments   
Comment by Marek Potociar [ 25/Mar/13 ]

IMO the @Uri value parsing should behave as @Path parsing - i.e. only path is considered and query params should be only added as part of derivation from the injected target.

I'm basing my opinion on the fact that while URIs with the same path and different query params in general CAN reference unrelated resources, in reality query params typically are used to merely provide additional narrowing of representational scope in the main resource (e.g. particular location in a map resource, particular search query in a search resource etc.).

So what you are asking for could be modelled (slightly more verbosely) as:

@GET
@Path("{param}")
public String doGet(
        @Uri("resource") WebTarget webTarget, 
        PathParam("param") String param) {

    return webTarget.queryParam("id", param).getUri().toString();
}

Maybe I am missing some important use cases you have in mind though.





[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-2663] Why two temp file is created during file upload with jersey 2? Created: 26/Sep/14  Updated: 23/Feb/15  Resolved: 23/Feb/15

Status: Resolved
Project: jersey
Component/s: media
Affects Version/s: 2.0
Fix Version/s: 2.17

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

Attachments: File JerseyFileUploadDemo.war    

 Description   

I have post question with detail
My Question

  • I need direct file object in resource method, So i have used @FormDataParam("upload") File file which created other temp file in temp folder, Why this needed ? Why you can not serve MIMExxx file to us.

In case of large file jersey take lots of time to create this two file before calling resource method. So some how i need to stop creating this other repxxx file and get directly MIMExxx file path.



 Comments   
Comment by Adam Lindenthal [ 08/Oct/14 ]

Hi U2Answer,

I just quickly checked the code and to me it appears, that the MIMExxx file is created just to verify, that it is possible to create a temp file (and eventually log a warning). After that, the file should be deleted immediately. So I assume, the file should be zero-sized.

I might be wrong though. Could you please confirm or disprove?
If my assumption is correct, than I would expect this to have minimal impact on the response time and the problem would be somewhere else (or simply implicated by the size of the file).

Regards,
Adam

Comment by Adam Lindenthal [ 08/Oct/14 ]

Oh, I forgot - just in case you are not satisfied with my answer...

It would be very helpful if you could share some small reproducing sample, something like a minimal maven project.

Thanks,
Adam

Comment by Ankit337 [ 09/Oct/14 ]

@Adam
Thanks!

that it is possible to create a temp file (and eventually log a warning). After that, the file should be deleted immediately. So I assume, the file should be zero-sized.
I might be wrong though. Could you please confirm or disprove?

No, File is not going to delete and even it's not 0kb file(It may show wrong size, Select that file refresh F5 it.). Yes, At the end both file is going to delete after executing my resource method.

You can also regenerate this bug by using below resource method

 @PUT
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response uploadFileSimple(@FormDataParam("upload") File file, @FormDataParam("upload") FormDataContentDisposition formData)
    {
       // my stuff
    }
  • fist MIMExxxxx.tmp which jersey create for multipart request (store inputStream)
  • Second rep23xxxx which is created for @FormDataParam("upload") File file (Note: If you not use @FormDataParam("upload") File file in resource method then this rep23xxxx file is not going to create)

First jersey take time to write MIMExx file and then take time to write repxxx file and then call reach to resource method, So in case of large file jersey take lot of time before calling resource method*(MIMExx-->repxx->resource method)*

NOTE: As you seen in temp folder there is two file with same size (please select file and refresh F5 so you can see its actual size otherwise many time it just show 0kb, I think that actually miss guide every one, we just look at temp folder and see that ohhh! there is 0kb file it's not take much time but actually It's not 0kb select that file and refresh, it will show actual size)

  • As per your suggestion I will give you a demo if you can't regenerate bug.

– Ankit337

Comment by Adam Lindenthal [ 09/Oct/14 ]

Hi,

I haven't really seen it because I was not trying to reproduce the issue and just checked the code for the beginning. I've found something like File.createTempFile("MIME", ...).delete() and did not find another place where a temp file with that prefix would be created.

Thanks for clarifying, I'll move the issue to backlog.

Comment by Ankit337 [ 09/Oct/14 ]

Hi Adam

– I have create one demo file upload, Download war file, You can directly import war in eclipse and run

– I have run that demo using tomcat 7.6, windows 7, eclipse Jersey 2.0-rc1

Comment by Ankit337 [ 09/Oct/14 ]

I have used Jersey 2.0-rc1 version , (Debug code)Put break point on first line of your resource method and find temp folder to see generated files.

  • Can you please tell me with which version you have tested ?
  • If File.createTempFile("MIME", ...).delete() then where file stream is written ?/
  • When MIME file going to delete ?

See jersey document

The File type can also be used when consuming a representation (request entity). In that case a temporary file will be created from the incoming request entity and passed as a parameter to the resource method.

Document it self say if you use FILE type then other temporary file(file name start with rep) is created and passed as a parameter to the resource method

Comment by Adam Lindenthal [ 09/Oct/14 ]

Attaching the war file linked by the reporter.

Comment by Ankit337 [ 09/Oct/14 ]

Here is code for creating rep temp file

File f = File.createTempFile("rep", "tmp");

Here is code for creating MIME temp file

File.createTempFile("MIME", null, tempDir != null ? new File(tempDir) : null).delete();
Comment by Adam Lindenthal [ 09/Oct/14 ]

Hi, I'll start from the top...

Can you please tell me with which version you have tested ?

I mentioned that above - I have not tested this yet. I am not actually working at the issue, I am just cleaning up our JIRA a bit.
But I did check the code quickly.

If File.createTempFile("MIME", ...).delete() then where file stream is written ?

As I told before - I guess this is just a test if a temp file can be successfully created. The obvious intent here was to delete the file immediately. If it's not the case (as you described), than this is the problem to solve.
The actual uploaded entity is being stored in the other file.

When MIME file going to delete ?

I do not understand that question. I would expect it to be deleted ASAP (and to be empty), but you reported different behaviour. Someone from our team (me or someone else, once we schedule the work on this into some sprint) has to take a look on this a bit deeper - reproduce, debug, find out what takes the most of the time (because your primary motivation for reporting this was performance) and eventually fix.

Document it self say if you use FILE type then other temporary file(file name start with rep) is created and passed as a parameter to the resource method

Yes, but this file is OK, isn't it? The other one is redundant. This is really meant to contain the uploaded data.

Comment by Adam Lindenthal [ 09/Oct/14 ]

Hi, just to react to your updated comment, yes - exactly based on those to places in the code I wrote my first impressions. There are no other significant spots in Jersey code (ignoring examples, etc), where tempfiles would be created (AFAIK).

Comment by Ankit337 [ 10/Oct/14 ]

Currently I get MIME path using java reflection, So jersey not going to create rep file for me.
My resource method like

 @PUT
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response uploadFileSimple(FormDataMultiPart form)
    {
           FormDataBodyPart filePart = form.getField("file");
           File file = getFileObjFromFilePart(filePart);
           //My stuff
    }

Here is the method from which I get file object of MIME using java reflection

	private File getFileObjFromFilePart(FormDataBodyPart filePart) throws Exception
	{
		BodyPartEntity bodyPart = (BodyPartEntity) filePart.getEntity();
		MIMEPart mimePart = (MIMEPart) readFieldValue("mimePart", bodyPart);
		Object dataHead = readFieldValue("dataHead", mimePart);
		Object dataFile = readFieldValue("dataFile", dataHead);
		File file = null;
		if (dataFile != null)
		{
			Object weakDataFile = readFieldValue("weak", dataFile);
			file = (File) readFieldValue("file", weakDataFile);
		}
		else
		{
			file = filePart.getValueAs(File.class);
		}
		return file;
	}

	private static Object readFieldValue(String fieldName, Object obj) throws Exception
	{
		Field field = obj.getClass().getDeclaredField(fieldName);
		field.setAccessible(true);
		return field.get(obj);
	}

Is this way is valid for preventing other rep file?

My purpose :

  • Need file object or temp file path directly in resource method (Jersey should not take extra time for writing file like rep, Some how user can get file path/object which is created by jersey internally(MIME) in resource method)
  • Quick patch is appreciated
Comment by Michal Gajdos [ 23/Feb/15 ]

If File is about to be injected into resource class or resource method then the temporary file created by mimepull is moved (not copied) to a new location defined by Jersey.





[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-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-2636] POST requests without Content-Type header pass throught @Consumes check Created: 02/Sep/14  Updated: 20/Feb/15

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

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


 Description   

I have a resource method like this:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
    // do stuff with formParams
}

If the request contains a Content-Type header set to something else than "application/x-www-form-urlencoded", a 415 response is generated and the method is never invoked, as expected.

However, if the request contains no Content-Type header at all and no body (you can generate such request with "curl -X POST url"), the method is invoked with the formParams parameter set to null. I think the container should generate a 400 or 415 response and not invoke the method in that case.



 Comments   
Comment by mikaelstaldal [ 02/Sep/14 ]

The same issue actually exist without @Consumes annotation as well. The problem is that no Content-Type and no body is not handled correctly.

Comment by Miroslav Fuksa [ 03/Sep/14 ]

hi,

thanks for creating an issue. I think this is a bug.

I checked the JAX-RS 2.0 specification and in chapter 3.7.2, steps 3/a it says:

-----------------
Filter M by removing members that do not meet the following criteria:
....
The media type of the request entity body (if any) is a supported input data format (see Section
3.5). If no methods support the media type of the request entity body an implementation
MUST generate a NotSupportedException (415 status) and no entity.
....
------------------

It am not 100% sure from the text what to do but I would say that we should not allow processing of no Content type by method with defined @Consumes to any specific type. I would still allow to process request without any Content-type by method with @Consumes("/").

Another argument: I think sending the entity without Content-type is incorrect and therefore it should not be processed by the method with specific @Consumes type.

I am moving the issue to the backlog.

thanks
Mira

Comment by cbeer [ 23/Sep/14 ]

I believe this is a blocker for me. I have a Jersey Resource like this:

@Path("/path")
public class ExampleApp {
    @POST
    @Timed
    public Response createObject(@QueryParam("mixin") final String mixin) { ... }

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Timed
    public Response createObjectFromFormPost(@FormDataParam("mixin") final String mixin) { }
}

If the client doesn't include a Content-Type, the createObjectFromFormPost is invoked and this exception is throw (because of the @FormDataParam):

java.lang.NullPointerException: null
	at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:205) ~[jersey-media-multipart-2.12.jar:na]
	at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81) ~[jersey-server-2.12.jar:na]
	at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:121) ~[jersey-server-2.12.jar:na]
	at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152) ~[jersey-server-2.12.jar:na]
	at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104) ~[jersey-server-2.12.jar:na]
Comment by mikaelstaldal [ 20/Feb/15 ]

The same issue with PUT requests.





[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-2680] Exception in jersey path mapper bubbles up until top Created: 09/Oct/14  Updated: 19/Feb/15  Resolved: 19/Feb/15

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

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


 Description   

Some specific illegal URLs cause Jersey to throw an exception that causes an error page to be displayed if no error-page element is defined in the web.xml. An example for a stack trace generated by this can be seen below (in this case the URL ends with an opening brace).
In ServletContainer:333 there is already a try/catch that catches UriBuilderException. I think that at this point we should also catch IllegalArgumentException. What do you think?

java.lang.IllegalArgumentException: Invalid syntax in the template "/service/v1/test/{". Check if a path parameter is terminated with a "}".
	org.glassfish.jersey.uri.internal.UriTemplateParser.parse(UriTemplateParser.java:258)
	org.glassfish.jersey.uri.internal.UriTemplateParser.<init>(UriTemplateParser.java:110)
   org.glassfish.jersey.uri.UriTemplate.createUriComponent(UriTemplate.java:1001)
	org.glassfish.jersey.uri.UriTemplate.createURIWithStringValues(UriTemplate.java:961)
	org.glassfish.jersey.uri.UriTemplate.createURIWithStringValues(UriTemplate.java:906)
	org.glassfish.jersey.uri.UriTemplate.createURI(UriTemplate.java:871)
	org.glassfish.jersey.uri.internal.JerseyUriBuilder._build(JerseyUriBuilder.java:893)
	org.glassfish.jersey.uri.internal.JerseyUriBuilder.build(JerseyUriBuilder.java:810)
	org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:330)
	org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
	com.aldiinternational.esb.framework.filter.AuthorizationFilter.doFilter(AuthorizationFilter.java:124)
	org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
	org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)


 Comments   
Comment by camann9 [ 09/Oct/14 ]

See pull request https://github.com/jersey/jersey/pull/114

Comment by Adam Lindenthal [ 22/Oct/14 ]

Hi camann9,

thanks for creating the issue and the pull request.
As we are already in contact also on github, I am moving the issue to backlog for now.

Regards,
Adam





[JERSEY-2677] Leak for RequestScoped injectables if async server model is used Created: 06/Oct/14  Updated: 19/Feb/15  Resolved: 19/Feb/15

Status: Resolved
Project: jersey
Component/s: core, performance
Affects Version/s: 2.12, 2.13
Fix Version/s: 2.17

Type: Bug Priority: Critical
Reporter: bodewig Assignee: Adam Lindenthal
Resolution: Fixed Votes: 0
Labels: hk2, memory-leak
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The dispose method of a HK2 factory bound to RequestScoped is never called when the async server model is used. I intend to attach a simple unit test using grizzly but we see the same result using Jetty as runtime.

It seems that the RequestScoped.Instance reference count is not decremented often enough to trigger disposal in the async case as we managed to work around the problem with a custom RequestListener that captures the current Instance for async requests and invokes release on it on the FINISHED event (twice as it is responsible for one reference itself).



 Comments   
Comment by bodewig [ 06/Oct/14 ]

I can't attach anything here, is this correct?

OK, here is my unit test inline

package org.example.jersey_bug;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;

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

public class RequestScopedAndAsyncTest extends JerseyTest {

    public static class Injectable {
        // just a placeholder
    }

    public static class InjectableFactory implements Factory<Injectable> {
        private static final Object LOCK = new Object();
        private static int provided;
        private static int balance;

        @Override
        public Injectable provide() {
            synchronized(LOCK) {
                provided++;
                balance++;
            }
            return new Injectable();
        }

        @Override
        public void dispose(Injectable i) {
            synchronized(LOCK) {
                balance--;
            }
        }

        public static void reset() {
            synchronized(LOCK) {
                provided = balance = 0;
            }
        }

        public static void assertProvidedOne() {
            synchronized(LOCK) {
                Assert.assertEquals(1, provided);
            }
        }

        public static void assertIsBalanced() {
            synchronized(LOCK) {
                Assert.assertEquals(0, balance);
            }
        }
    }

    @Path("test")
    public static class TestResource {

        @Inject
        private Injectable injectable;

        @GET
        @Path("sync")
        public Response sync() {
            return Response.noContent().build();
        }

        @GET
        @Path("async")
        public void async(@Suspended AsyncResponse ar) {
            ar.resume(Response.noContent().build());
        }
    }

    @Before
    public void resetCounters() {
        InjectableFactory.reset();
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(TestResource.class)
            .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bindFactory(InjectableFactory.class)
                            .to(Injectable.class)
                            .in(RequestScoped.class);
                    }
                });
    }

    @Test
    public void shouldProvideAndDisposeSync() {
        Assert.assertEquals(204, target("/test/sync").request().get().getStatus());
        InjectableFactory.assertProvidedOne();
        InjectableFactory.assertIsBalanced();
    }

    @Test
    public void shouldProvideAndDisposeAsync() {
        Assert.assertEquals(204, target("/test/async").request().get().getStatus());
        InjectableFactory.assertProvidedOne();
        InjectableFactory.assertIsBalanced();
    }

}
Comment by Adam Lindenthal [ 09/Oct/14 ]

Hi bodewig, correct - you cannot unfortunatelly attach files to the issue.

But we can - next time just drop a link to github project or whatever (e.g. you can send it via email to one of us after the communication starts here) and we will attach it for you.

Regarding the problem you are experiencing - this needs to be tested and investigated - thus I am moving it to backlog.

Thanks,
Adam

PS: should you still have something more to attach here, feel free to drop a link or send a zip to me.

Comment by Adam Lindenthal [ 19/Feb/15 ]

Fixed in 2.17.





[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-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-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-2727] Performance degradation after moving to jersey 2 (2.13) Created: 10/Dec/14  Updated: 18/Feb/15  Resolved: 18/Feb/15

Status: Resolved
Project: jersey
Component/s: