[JERSEY-3171] Allow Grizzly HttpServer to have configurable portRange Created: 30/Sep/16  Updated: 30/Sep/16

Status: Open
Project: jersey
Component/s: containers
Affects Version/s: 2.22.2, 2.24, 2.23.2
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: anthony-o Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 1 hour
Time Spent: Not Specified
Original Estimate: 1 hour


 Description   

My use case is to simply start a GrizzlyHttpServer without knowing the port on which it will be bound, but by specifying a port range on which it should bind.

Today, here is what I'm forced to do:

HttpServer server = GrizzlyHttpServerFactory.createHttpServer(new URI("http://localhost/api"), config, false);
NetworkListener grizzlyListener = server.getListener("grizzly");

// Set a range instead a single port
Field portField = grizzlyListener.getClass().getDeclaredField("port");
portField.setAccessible(true);
portField.set(grizzlyListener, -1);
Field portRangeField = grizzlyListener.getClass().getDeclaredField("portRange");
portRangeField.setAccessible(true);
portRangeField.set(grizzlyListener, new PortRange(49152, 65535)); // low & high thanks to http://stackoverflow.com/a/2675399/535203

server.start();

I think it should be easier if the port and portRange of grizzly NetworkListener fields were publicly settable.



 Comments   
Comment by anthony-o [ 30/Sep/16 ]

Created GRIZZLY-1870 in relation with this ticket.

Comment by anthony-o [ 30/Sep/16 ]

Perhaps one could introduce the portRange parameter in GrizzlyHttpServerFactory.createHttpServer(...) methods?





[JERSEY-3170] Release notes do not include Jersey 2.15 Created: 29/Sep/16  Updated: 29/Sep/16

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

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


 Description   

In the "Previous releases" section of the release notes, there is no link to the Jersey 2.15 release notes. It seems it was there in Jersey 2.16 but is gone from 2.17 onwards.

A link to the Jersey 2.15 release notes should be added at least to the next version's release notes, and maybe to the pages for previous versions retroactively, at least on the jersey.java.net site.






[JERSEY-3169] NPE in ClientBinder when receiving response from server Created: 29/Sep/16  Updated: 29/Sep/16

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

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


 Description   

An exception was thrown when we are firing async call from 2.23.1 client to 2.23.1 server.

Please find the attached response from 2.22.1 and 2.23.1 (2.23.1 NPE is the same even we are using 2.23.2)

Client side code:
client = ClientBuilder.newClient(clientConfig);
baseTarget = client.target(urlBase);
CacheBuilder.newBuilder().build(new CacheLoader<String, WebTarget>() {
public WebTarget load(String path)

{ return baseTarget.path(path); }

});

public void testTing(ValidationRequest valReq) throws Exception {
try {
cachedWebTargets.get("/validate/position/eee").request().accept(mediaType)
.property(ClientProperties.READ_TIMEOUT, 1000000) // Overridden timeout value for this request, null will use default to defaultChunkedResponseTimeout
.async().post(Entity.entity(valReq, mediaType), new InvocationCallback<ChunkedInput<String>>() {

@Override
public void completed(ChunkedInput<String> response) {
response.setParser(ChunkedInput.createParser(CommonConsts.CHUNKED_DELIMITER));
String chunk;
while ((chunk = response.read()) != null)

{ LOG.info(chunk); }


}

@Override
public void failed(Throwable throwable)

{ LOG.error(throwable, throwable); }

});
} catch (Exception e)

{ throw handleException(e); }

}

Server side:
@Path("/position")
public Class<PositionValidatorSubResource> validateOrder()

{ return PositionValidatorSubResource.class; }

Code Sniplet in PositionValidatorSubResource.class:
@POST
@Path("/eee")
@Consumes(

{ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }

)
public ChunkedOutput<String> validatePositionsWorkflowTest(com.ml.elt.vs.request.obj.ValidationRequest valReq) {
final ChunkedOutput<String> output = new ChunkedOutput<>(String.class, CommonConsts.CHUNKED_DELIMITER);
try

{ output.write("Testing001"); Thread.sleep(5000); output.write("Testing002"); output.write(null); }

catch (Exception e)

{ LOG.error(e, e); }

return output;
}

So in 2.22.1 we are working perfectly fine in calling async with chunked response, but it failed with such a strange error in 2.23.1. If we send the request without using async() call, then the return can be recieved successfully and object binding are all fine.

It looks like something has changed in 2.23.1 that break the async call which is expecting chunked return

all the dependencies are pulled from maven central



 Comments   
Comment by clsiu [ 29/Sep/16 ]

Forgot to included the attachment, i will instead paste the response from server for 2.22.1 and 2.23.1 here

Comment by clsiu [ 29/Sep/16 ]

Response from 2.22.1:
log4j:WARN No appenders could be found for logger (org.apache.commons.configuration.PropertiesConfiguration).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
1222 [validationclient-async-executor-0] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: default
1223 [validationclient-async-executor-0] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
1224 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection request: [route: {}->http://VFHKGP101172.ASIA.bankofamerica.com:20299][total kept alive: 1; route allocated: 1 of 200; total allocated: 1 of 200]
1224 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://VFHKGP101172.ASIA.bankofamerica.com:20299][total kept alive: 0; route allocated: 1 of 200; total allocated: 1 of 200]
1224 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Executing request POST /validate/position/eee HTTP/1.1
1224 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
1224 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
1224 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /validate/position/eee HTTP/1.1
1224 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept: application/xml
1224 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Type: application/xml
1225 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Jersey/2.22.1 (Apache HttpClient 4.5)
1225 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Transfer-Encoding: chunked
1225 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: VFHKGP101172.ASIA.bankofamerica.com:20299
1225 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
1225 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /validate/position/eee HTTP/1.1[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept: application/xml[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/xml[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Jersey/2.22.1 (Apache HttpClient 4.5)[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Transfer-Encoding: chunked[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: VFHKGP101172.ASIA.bankofamerica.com:20299[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "4b6[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "<?xml version="1.0" encoding="UTF-8" standalone="yes"?><validationRequest><productType>SWAPS</productType><reqID>1475116633083</reqID><clientAccount>MOON_CAP_LEV</clientAccount><clientSLAccountShortSellQty>0</clientSLAccountShortSellQty><clientSLAccountSynthShortSellQty>0</clientSLAccountSynthShortSellQty><cummQty>0</cummQty><deskSLAccountShortSellQty>0</deskSLAccountShortSellQty><deskSLAccountSynthShortSellQty>0</deskSLAccountSynthShortSellQty><elocateRequestRetryIntervalms>20</elocateRequestRetryIntervalms><elocateSiteID>

{E5285C1D-5E1A-4953-A00F-34779147328F}

</elocateSiteID><execID>1475116633083</execID><isEnableAutoElocate>true</isEnableAutoElocate><isOverrideRequest>false</isOverrideRequest><isRevalidateByElocateResponse>true</isRevalidateByElocateResponse><isUpdatePKE>true</isUpdatePKE><isValidateBANAClientList>true</isValidateBANAClientList><isValidateSEBIClientList>true</isValidateSEBIClientList><lastShares>0</lastShares><orderID>1475116633083</orderID><orderSide>5</orderSide><orderdQty>9000</orderdQty><originalOrderQty>0</originalOrderQty><requestValidationType>accepted</requestValidationType><transactionTime>0</transactionTime><underlying>0001.HK</underlying></validationRequest>[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "0[\r][\n]"
1444 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
6450 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
6450 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Type: application/xml[\r][\n]"
6451 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Date: Thu, 29 Sep 2016 02:37:18 GMT[\r][\n]"
6451 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
6451 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6451 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
6451 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/xml
6451 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Thu, 29 Sep 2016 02:37:18 GMT
6451 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
6453 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "a[\r][\n]"
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Testing001[\r][\n]"
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "2[\r][\n]"
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6461 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "a[\r][\n]"
6462 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Testing002[\r][\n]"
6462 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "2[\r][\n]"
6462 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6462 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6463 [validationclient-async-executor-0] INFO com.ml.equity.firm.validation.client.ValidationClient - Testing001
6463 [validationclient-async-executor-0] INFO com.ml.equity.firm.validation.client.ValidationClient - Testing002

Comment by clsiu [ 29/Sep/16 ]

Response from 2.23.1/2.23.2
log4j:WARN No appenders could be found for logger (org.apache.commons.configuration.PropertiesConfiguration).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
1571 [validationclient-async-executor-0] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: default
1573 [validationclient-async-executor-0] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
1573 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection request: [route: {}->http://VFHKGP101172.ASIA.bankofamerica.com:20299][total kept alive: 1; route allocated: 1 of 200; total allocated: 1 of 200]
1573 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://VFHKGP101172.ASIA.bankofamerica.com:20299][total kept alive: 0; route allocated: 1 of 200; total allocated: 1 of 200]
1574 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Executing request POST /validate/position/eee HTTP/1.1
1574 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
1574 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /validate/position/eee HTTP/1.1
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept: application/xml
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Type: application/xml
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Jersey/2.23.1 (Apache HttpClient 4.5)
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Transfer-Encoding: chunked
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: VFHKGP101172.ASIA.bankofamerica.com:20299
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
1574 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
1791 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /validate/position/eee HTTP/1.1[\r][\n]"
1791 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept: application/xml[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/xml[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Jersey/2.23.1 (Apache HttpClient 4.5)[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Transfer-Encoding: chunked[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: VFHKGP101172.ASIA.bankofamerica.com:20299[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "4b6[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "<?xml version="1.0" encoding="UTF-8" standalone="yes"?><validationRequest><productType>SWAPS</productType><reqID>1475116655171</reqID><clientAccount>MOON_CAP_LEV</clientAccount><clientSLAccountShortSellQty>0</clientSLAccountShortSellQty><clientSLAccountSynthShortSellQty>0</clientSLAccountSynthShortSellQty><cummQty>0</cummQty><deskSLAccountShortSellQty>0</deskSLAccountShortSellQty><deskSLAccountSynthShortSellQty>0</deskSLAccountSynthShortSellQty><elocateRequestRetryIntervalms>20</elocateRequestRetryIntervalms><elocateSiteID>

{E5285C1D-5E1A-4953-A00F-34779147328F}

</elocateSiteID><execID>1475116655171</execID><isEnableAutoElocate>true</isEnableAutoElocate><isOverrideRequest>false</isOverrideRequest><isRevalidateByElocateResponse>true</isRevalidateByElocateResponse><isUpdatePKE>true</isUpdatePKE><isValidateBANAClientList>true</isValidateBANAClientList><isValidateSEBIClientList>true</isValidateSEBIClientList><lastShares>0</lastShares><orderID>1475116655171</orderID><orderSide>5</orderSide><orderdQty>9000</orderdQty><originalOrderQty>0</originalOrderQty><requestValidationType>accepted</requestValidationType><transactionTime>0</transactionTime><underlying>0001.HK</underlying></validationRequest>[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "0[\r][\n]"
1792 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
6798 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
6798 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Type: application/xml[\r][\n]"
6799 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Date: Thu, 29 Sep 2016 02:37:40 GMT[\r][\n]"
6799 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
6799 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
6799 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
6799 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/xml
6799 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Thu, 29 Sep 2016 02:37:40 GMT
6799 [validationclient-async-executor-0] DEBUG org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
6803 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
6814 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: Shutdown connection
6815 [validationclient-async-executor-0] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection discarded
6815 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: Close connection
6815 [validationclient-async-executor-0] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://VFHKGP101172.ASIA.bankofamerica.com:20299][total kept alive: 0; route allocated: 0 of 200; total allocated: 0 of 200]
6815 [validationclient-async-executor-0] DEBUG org.apache.http.wire - http-outgoing-0 << "[read] I/O error: socket closed"
6816 [validationclient-async-executor-0] ERROR com.ml.equity.firm.validation.client.ValidationClient - javax.ws.rs.ProcessingException: A MultiException has 1 exceptions. They are:
1. java.lang.NullPointerException

javax.ws.rs.ProcessingException: A MultiException has 1 exceptions. They are:
1. java.lang.NullPointerException

at org.glassfish.jersey.client.ClientRuntime.processFailure(ClientRuntime.java:200)
at org.glassfish.jersey.client.ClientRuntime.access$500(ClientRuntime.java:74)
at org.glassfish.jersey.client.ClientRuntime$2$1$2.run(ClientRuntime.java:175)
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:340)
at org.glassfish.jersey.client.ClientRuntime$2$1.failure(ClientRuntime.java:173)
at org.glassfish.jersey.apache.connector.ApacheConnector$1.run(ApacheConnector.java:493)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at jersey.repackaged.com.google.common.util.concurrent.MoreExecutors$DirectExecutorService.execute(MoreExecutors.java:299)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:50)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:37)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:487)
at org.glassfish.jersey.client.ClientRuntime$2.run(ClientRuntime.java:180)
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:340)
at org.glassfish.jersey.client.ClientRuntime$3.run(ClientRuntime.java:208)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: A MultiException has 1 exceptions. They are:
1. java.lang.NullPointerException

at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:478)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:765)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getUnqualifiedService(ServiceLocatorImpl.java:772)
at org.jvnet.hk2.internal.IterableProviderImpl.get(IterableProviderImpl.java:111)
at org.glassfish.jersey.client.ChunkedInputReader.readFrom(ChunkedInputReader.java:97)
at org.glassfish.jersey.client.ChunkedInputReader.readFrom(ChunkedInputReader.java:67)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:368)
at org.glassfish.jersey.client.JerseyInvocation$7.completed(JerseyInvocation.java:948)
at org.glassfish.jersey.client.ClientRuntime.processResponse(ClientRuntime.java:196)
at org.glassfish.jersey.client.ClientRuntime.access$300(ClientRuntime.java:74)
at org.glassfish.jersey.client.ClientRuntime$2$1$1.run(ClientRuntime.java:166)
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:340)
at org.glassfish.jersey.client.ClientRuntime$2$1.response(ClientRuntime.java:164)
at org.glassfish.jersey.apache.connector.ApacheConnector$1.run(ApacheConnector.java:491)
... 20 more
Caused by: java.lang.NullPointerException
at org.glassfish.jersey.client.ClientBinder$PropertiesDelegateFactory.provide(ClientBinder.java:102)
at org.glassfish.jersey.client.ClientBinder$PropertiesDelegateFactory.provide(ClientBinder.java:91)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:153)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
... 46 more
Sep 29, 2016 10:37:40 AM org.glassfish.jersey.internal.Errors logErrors
WARNING: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 1
java.lang.NullPointerException
at org.glassfish.jersey.client.ClientBinder$PropertiesDelegateFactory.provide(ClientBinder.java:102)
at org.glassfish.jersey.client.ClientBinder$PropertiesDelegateFactory.provide(ClientBinder.java:91)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:153)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:765)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getUnqualifiedService(ServiceLocatorImpl.java:772)
at org.jvnet.hk2.internal.IterableProviderImpl.get(IterableProviderImpl.java:111)
at org.glassfish.jersey.client.ChunkedInputReader.readFrom(ChunkedInputReader.java:97)
at org.glassfish.jersey.client.ChunkedInputReader.readFrom(ChunkedInputReader.java:67)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:368)
at org.glassfish.jersey.client.JerseyInvocation$7.completed(JerseyInvocation.java:948)
at org.glassfish.jersey.client.ClientRuntime.processResponse(ClientRuntime.java:196)
at org.glassfish.jersey.client.ClientRuntime.access$300(ClientRuntime.java:74)
at org.glassfish.jersey.client.ClientRuntime$2$1$1.run(ClientRuntime.java:166)
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:340)
at org.glassfish.jersey.client.ClientRuntime$2$1.response(ClientRuntime.java:164)
at org.glassfish.jersey.apache.connector.ApacheConnector$1.run(ApacheConnector.java:491)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at jersey.repackaged.com.google.common.util.concurrent.MoreExecutors$DirectExecutorService.execute(MoreExecutors.java:299)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:50)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:37)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:487)
at org.glassfish.jersey.client.ClientRuntime$2.run(ClientRuntime.java:180)
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:340)
at org.glassfish.jersey.client.ClientRuntime$3.run(ClientRuntime.java:208)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)





[JERSEY-3168] Port to jackson 2.7.4 Created: 28/Sep/16  Updated: 28/Sep/16

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

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


 Description   

hi
wrote a little patch for port jersey-media-json-jackson to jackson 2.7.6
```
— /media/json-jackson/src/main/java/org/glassfish/jersey/jackson/internal/JacksonObjectProvider.java 2016-06-09 20:03:52.000000000 +0200
+++ /media/json-jackson/src/main/java/org/glassfish/jersey/jackson/internal/JacksonObjectProvider.java 2016-08-24 20:00:04.702617065 +0200
@@ -236,7 +236,7 @@
final JsonObjectFormatVisitor objectVisitor,
final SerializerProvider provider) throws JsonMappingException {
if (include(writer.getName()))

{ - writer.depositSchemaProperty(objectVisitor); + writer.depositSchemaProperty(objectVisitor, provider); }

}
```
thanks in advance for every suggestion
regards






[JERSEY-3167] ResourceMethodConfig.register should accept Feature contract Created: 26/Sep/16  Updated: 26/Sep/16

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

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


 Description   

Hi,

I noticed that ResourceMethodConfig.register will only accept ContainerRequestFilter, ContainerResponseFilter, ReaderInterceptor or WriterInterceptor.

But DynamicFeature.configure(ResourceInfo, FeatureContext) clearly states that Feature should also be accepted.

This is for example helpful to get injection of @Context (and @Inject I guess) in filters by making them implements Feature. I think this is related to the closed (but not fixed from my point of view) JERSEY-1960.






[JERSEY-3166] Configurable.register(Object) should also handle injection of DynamicFeature. Created: 26/Sep/16  Updated: 26/Sep/16

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

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


 Description   

Hi,

According to the JAX-RS specification, register(Object) is meant to inject @Context (and I guess @Inject?) into the object.

Currently, it does so if the object implements Feature but it should at least do so also for DynamicFeature, and maybe other classes (I'm not sure how to interpret "JAX-RS component" in the citation below).

Here is two relevant documentation of javax.ws.rs.core.Configurable.register(Object):

The registered JAX-RS component is registered as a contract provider of all the recognized JAX-RS or implementation-specific extension contracts including meta-provider contracts, such as {@code Feature} or {@link javax.ws.rs.container.DynamicFeature}.

Fields and properties of all registered JAX-RS component instances are injected with their declared dependencies (see {@link Context}) by the JAX-RS runtime prior to use.






[JERSEY-3165] jersey-quickstart-grizzly2 archetype calls deprecated method to shutdown HttpServer Created: 25/Sep/16  Updated: 25/Sep/16

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

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


 Description   

Example code from jersey-quickstart-grizzly2 archetype (taken from Getting started - new from archetype section) calls deprecated method public void stop() to shutdown HttpServer - instead public synchronized void shutdownNow() should be called.






[JERSEY-3164] OAuth2FlowGoogleBuilder.loginHint() uses wrong property key Created: 19/Sep/16  Updated: 19/Sep/16

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

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


 Description   

From OAuth2FlowGoogleBuilder.java:
```
public OAuth2FlowGoogleBuilder loginHint(String loginHint)

{ return property(OAuth2CodeGrantFlow.Phase.AUTHORIZATION, Display.getKey(), loginHint); }

```
Display.getKey() should probably be OAuth2FlowGoogleBuilder.LOGIN_HINT.






[JERSEY-3163] NettyResponseWriter closes channel on every request Created: 19/Sep/16  Updated: 19/Sep/16

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

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


 Description   

Unless I'm misunderstanding something, NettyResponseWriter closes the channel on every request. This seems obviously wrong.

        if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {

            JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());

            if (HttpUtil.isTransferEncodingChunked(response)) {
                ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(ChannelFutureListener.CLOSE);
            } else {
                ctx.write(jerseyChunkedInput).addListener(ChannelFutureListener.CLOSE);
            }
            return jerseyChunkedInput;

        } else {
            ctx.write(Unpooled.buffer(0)).addListener(ChannelFutureListener.CLOSE);
            return null;
        }


 Comments   
Comment by Pavel Bucek [ 19/Sep/16 ]

channel is not a connection, so the obviousness is not that clear to me.

Can you please share what and why is this not correct? Ideally with a code sample (can be pseudo code).

Comment by nkvoll [ 19/Sep/16 ]

Here's an example by using curl, running from `examples/helloworld-netty` using the git tag `2.23.2`:

$ curl -v localhost:8080/helloworld localhost:8080/helloworld
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /helloworld HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< content-length: 12
< connection: keep-alive
<
* Connection #0 to host localhost left intact
Hello World!* Found bundle for host localhost: 0x7fb57840fe70
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 8080 (#0)
> GET /helloworld HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
>
* Recv failure: Connection reset by peer
* Connection died, retrying a fresh connect
* Closing connection 0
* Issue another request to this URL: 'HTTP://localhost:8080/helloworld'
* Hostname localhost was found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#1)
> GET /helloworld HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< content-length: 12
< connection: keep-alive
<
* Connection #1 to host localhost left intact
Hello World!%

The connection is attempted re-used, but is closed.





[JERSEY-3162] Errors after abort SseListener before all events are received Created: 16/Sep/16  Updated: 16/Sep/16

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

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

Tags: sse

 Description   

If I abort an SseListener before all events are received,
some of the following requests run into exceptions like:

javax.ws.rs.client.ResponseProcessingException: Failed to convert a response into an exception.
Caused by: javax.ws.rs.ProcessingException: Failed to buffer the message content input stream.
Caused by: java.io.IOException: Invalid Http response
or
javax.ws.rs.ProcessingException: java.net.SocketException: Connection reset
or
org.apache.http.client.ClientProtocolException
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response

On the server side I get the exception:
2016-09-15 13:23:54.178 INFO 7207 — [pool-1-thread-1] o.apache.coyote.http11.Http11Processor : An error occurred in processing while on a non-container thread. The connection will be closed immediately
java.io.IOException: Datenübergabe unterbrochen (broken pipe)
at sun.nio.ch.FileDispatcherImpl.write0(Native Method) ~[na:1.8.0_11]
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47) ~[na:1.8.0_11]
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) ~[na:1.8.0_11]
at sun.nio.ch.IOUtil.write(IOUtil.java:65) ~[na:1.8.0_11]
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:466) ~[na:1.8.0_11]
at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:134) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:101) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:157) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.doWrite(NioEndpoint.java:1221) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.tomcat.util.net.SocketWrapperBase.flushBlocking(SocketWrapperBase.java:451) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.tomcat.util.net.SocketWrapperBase.flush(SocketWrapperBase.java:441) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.coyote.http11.Http11OutputBuffer.flushBuffer(Http11OutputBuffer.java:514) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.coyote.http11.Http11OutputBuffer.flush(Http11OutputBuffer.java:243) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.coyote.http11.Http11Processor.flush(Http11Processor.java:1494) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.coyote.AbstractProcessor.action(AbstractProcessor.java:284) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.coyote.Response.action(Response.java:167) [tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:336) [tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:303) [tomcat-embed-core-8.5.5.jar:8.5.5]
at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:109) [tomcat-embed-core-8.5.5.jar:8.5.5]
at org.glassfish.jersey.servlet.internal.ResponseWriter$NonCloseableOutputStreamWrapper.flush(ResponseWriter.java:330) [jersey-container-servlet-core-2.23.2.jar:na]
at org.glassfish.jersey.message.internal.CommittingOutputStream.flush(CommittingOutputStream.java:292) [jersey-common-2.23.2.jar:na]

During some of the following requests the http client receives garbage. It seems like the I/O buffer contains data of the previous request.

This produces such wire log:

13:10:46.782 [Thread-20] DEBUG org.apache.http.headers - >> GET /long?length=20 HTTP/1.1
13:10:46.783 [Thread-20] DEBUG org.apache.http.headers - >> Accept: /
13:10:46.784 [Thread-20] DEBUG org.apache.http.headers - >> Accept-Language: de
13:10:46.786 [Thread-20] DEBUG org.apache.http.headers - >> Host: localhost:8080
13:10:46.788 [Thread-20] DEBUG org.apache.http.headers - >> Connection: Keep-Alive
13:10:46.796 [Thread-20] DEBUG org.apache.http.wire - << "14[\r][\n]"
13:10:46.806 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultHttpResponseParser - Garbage in response: 14
13:10:46.810 [Thread-20] DEBUG org.apache.http.wire - << "01234567890123456789[\r][\n]"
13:10:46.811 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultHttpResponseParser - Garbage in response: 01234567890123456789
13:10:46.813 [Thread-20] DEBUG org.apache.http.wire - << "0[\r][\n]"
13:10:46.820 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultHttpResponseParser - Garbage in response: 0
13:10:46.824 [Thread-20] DEBUG org.apache.http.wire - << "[\r][\n]"
13:10:46.836 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultHttpResponseParser - Garbage in response:
13:11:46.906 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection 0.0.0.0:47265<->127.0.0.1:8080 closed
13:11:46.906 [Thread-20] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection 0.0.0.0:47265<->127.0.0.1:8080 shut down
13:11:46.906 [Thread-20] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@37a96452Exception in thread "Thread-20" org.apache.http.client.ClientProtocolException

To reproduce the error a sample application is provided at the following location:
https://github.com/morca/sse-test

The error occurs if I use tomcat 8.5.5 or newer (comes with spring-boot 1.4.0), in tomcat 8.0.36 there are no problems.






[JERSEY-3040] Server-sent events incorrectly sent on EOF Created: 21/Jan/16  Updated: 14/Sep/16

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

Type: Bug Priority: Major
Reporter: mick.frost Assignee: Pavel Bucek
Resolution: Unresolved Votes: 1
Labels: incomplete
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows


Sprint: Triaged

 Description   

EOF is no longer a valid delimiter for a server-sent event; it changed between these specification versions:
http://www.w3.org/TR/2011/WD-eventsource-20111020/
http://www.w3.org/TR/2011/WD-eventsource-20110310/

Jersey version 2.22.1 appears not to respect this, my test is as follows:
1. Open connection and begin receiving events
2. Suspend my process for > 10 minutes (TCP socket is closed)
3. Resume process
An incomplete event is received (data is truncated); I believe this can only be because EOF is considered as a delimtier.

My code is as follows:

public void subscribe (String name) {
        EventListener listener = new EventListener() {
            @Override
            public void onEvent(InboundEvent inboundEvent) {
                try {     
                    String data = inboundEvent.readData();
                    JSONObject json = new JSONObject(data);
                    System.out.println(inboundEvent.getName() + ":" + inboundEvent.getId() + ":" + json.getInt("datomic-t"));
                } catch (RuntimeException e) {
                    System.out.println(e.getMessage());
                    System.out.println(inboundEvent.getName() + ":" + inboundEvent.getId());
                };
            }
        };
        WebTarget target = ClientBuilder.newClient().register(SseFeature.class).target(query);
        EventSource source = EventSource.target(target).named(name).build();
        source.register(listener);
        source.open();
    }


 Comments   
Comment by Marek Potociar [ 25/Jan/16 ]

Few questions:

  1. How does the server side code looks like?
  2. Does this happen with older Jersey versions too?
  3. Can you perhaps provide a complete reproducer application?
Comment by Marek Potociar [ 25/Jan/16 ]

Marking as incomplete - more info requested from the filer.

Comment by mick.frost [ 03/Feb/16 ]

I'll spend some more time producing a more complete test.
The server side is pedestal, a clojure library, but underneath it is Jetty; we can produce a Jersey based server instead.

Comment by Niall.McCurry [ 29/Mar/16 ]

Hi Marek

I have have attempted to create a branch but it would appear that I need to wait for "Oracle Contributor Agreement" approval so can't push it to jersey git repo until that is approved. Then I can create a pull request for this bug bug on jersey.

I have uploaded a client test code at

http://wikisend.com/download/758962/simple-service.zip

Which run a client and server at a very low connection timeout ... to force the bug described above

Comment by Pavel Bucek [ 29/Mar/16 ]

not commenting the content of the patch, but..

generic git flow in this case is:

  1. fork jersey
  2. work on your fork
  3. create pull request (and using your fork as a source and jersey/master as a destination).

that way you don't need developer access to Jersey repo (which you won't get even after you sign contributor agreement)

Comment by Niall.McCurry [ 29/Mar/16 ]

I have created the following pull request

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

The client & server test example doesn't really sit well inside a unit test as it can be long running to present the error.

Comment by Niall.McCurry [ 03/May/16 ]

Is it possible to get the bug fix accepted into the master branch

I have create a repo for the test code ... note i'm using version 2.22.2 in the test code to demonstrate the issue

https://github.com/NiallMcCu/JerseyTest

Comment by Niall.McCurry [ 13/May/16 ]

Hi @pavel_bucek or @m_potociar is there any update on getting this fix in to the code base ?

Comment by Pavel Bucek [ 13/May/16 ]

Hi Niall,

in order to be able to contribute to Jersey project, you need to sign OCA: http://www.oracle.com/technetwork/community/oca-486395.html

You don't seem to be on that list, so we cannot accept the contribution yet.

Thanks and regards,
Pavel

Comment by Niall.McCurry [ 13/May/16 ]

I have signed this and emailed the "Oracle Contributor Agreement" approval on the 29 March ... as of yet i have not receided any thing back

Comment by Niall.McCurry [ 21/Jul/16 ]

@pavel_bucek Is there any update on this fix?

Comment by Pavel Bucek [ 21/Jul/16 ]

not at this moment, we haven't received any confirmation about your OCA yet.

Comment by Niall.McCurry [ 28/Jul/16 ]

You should have reveived this by now. I have received conformation of the accptance ... I'm under the Handle NiallMcCu ... which is my handle for the Branch i have generated

Comment by Niall.McCurry [ 14/Sep/16 ]

Is there any news, on where this fix is ? Pavel Bucek





[JERSEY-1841] ClientResponse.hasEntity() should not throw a NullPointerException Created: 11/Apr/13  Updated: 07/Sep/16

Status: Reopened
Project: jersey
Component/s: core
Affects Version/s: 1.17
Fix Version/s: 1.18

Type: Bug Priority: Major
Reporter: CodingFabian Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 0 minutes
Time Spent: 1 hour
Original Estimate: 3 hours

Issue Links:
Related
is related to JERSEY-1672 ClientResponse.close() should not thr... Reopened

 Description   

Similar to JERSEY-1672, the hasEntity method throws a null pointer exception when entity is null (like for a 500 response).
When you have filters which look at possible JSON entities, it would be great to not get a null pointer.

The workaround is to check for getEntityInputStream() != null first, which is kind of awkward.



 Comments   
Comment by Miroslav Fuksa [ 07/Nov/13 ]

Hi,

can you please provide more details? I cannot reproduce the NPE. I tried with 500 and 204 responses and never get NPE in ClientResponse.hasEntity(). I have tested it against 1.17 and with latest snapshot version. Exception stack trace and code example would help. The best would be simple maven project with test simulating the bug. Thanks.

I have the same problem with JERSEY-1672 as I cannot reproduce it.

Comment by Miroslav Fuksa [ 11/Nov/13 ]

I cannot reproduce the issue (I would need exception stack trace at least).

Comment by pabstec [ 07/Sep/16 ]

ClientResponse clientResponse = client.resource(url).delete(ClientResponse.class);

java.lang.NullPointerException
at com.sun.jersey.api.client.ClientResponse.hasEntity(ClientResponse.java:518)
at com.sun.jersey.api.client.filter.GZIPContentEncodingFilter.handle(GZIPContentEncodingFilter.java:125)
at com.sun.jersey.api.client.Client.handle(Client.java:652)

Comment by pabstec [ 07/Sep/16 ]

A work-around is to add this filter very first to the Client (which requires creating a ClientResponseWrapper class that simply delegates).

import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;

/**
 * A Client Filter that works around a NPE issue with {@link ClientResponse#hasEntity()}.
 * See <a href="https://java.net/jira/browse/JERSEY-1841">JERSEY-1841</a> and <a href="https://java.net/jira/browse/JERSEY-1672">JERSEY-1672</a>
 *
 * @author pabstec on 9/7/16.
 */
public class RobustClientResponseFilter extends ClientFilter {
  @Override
  public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
    return new ClientResponseWrapper(getNext().handle(request)) {
      @Override
      public boolean hasEntity() {
        return getEntityInputStream() != null && super.hasEntity();
      }

      @Override
      public void close() throws ClientHandlerException {
        if (getEntityInputStream() != null) {
          super.close();
        }
      }
    };
  }
}




[JERSEY-1672] ClientResponse.close() should not throw a NullPointerException Created: 27/Jan/13  Updated: 07/Sep/16

Status: Reopened
Project: jersey
Component/s: None
Affects Version/s: 1.17
Fix Version/s: 1.18

Type: Bug Priority: Major
Reporter: CodingFabian Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 0 minutes
Time Spent: 1 hour
Original Estimate: 3 hours

Issue Links:
Related
is related to JERSEY-1841 ClientResponse.hasEntity() should not... Reopened

 Description   

Currently closing the connection is not easy.
the easiest solution would be to have a finally block with just response.close().
However, depending on the server response entity may be null in ClientResponse#613
i think close should include a null check here. and just do nothing if it does not have an entity.



 Comments   
Comment by Miroslav Fuksa [ 07/Nov/13 ]

can you please provide more details? I cannot reproduce the NPE. I have tested it against 1.17 and with latest snapshot version. Exception stack trace and code example would help. The best would be simple maven project with test simulating the bug. Thanks.

Comment by Miroslav Fuksa [ 11/Nov/13 ]

I cannot reproduce the issue (I would need exception stack trace at least).

Comment by pabstec [ 07/Sep/16 ]

A work-around is to add this filter very first to the Client (which requires creating a ClientResponseWrapper class that simply delegates).

import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;

/**
 * A Client Filter that works around a NPE issue with {@link ClientResponse#hasEntity()}.
 * See <a href="https://java.net/jira/browse/JERSEY-1841">JERSEY-1841</a> and <a href="https://java.net/jira/browse/JERSEY-1672">JERSEY-1672</a>
 *
 * @author pabstec on 9/7/16.
 */
public class RobustClientResponseFilter extends ClientFilter {
  @Override
  public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
    return new ClientResponseWrapper(getNext().handle(request)) {
      @Override
      public boolean hasEntity() {
        return getEntityInputStream() != null && super.hasEntity();
      }

      @Override
      public void close() throws ClientHandlerException {
        if (getEntityInputStream() != null) {
          super.close();
        }
      }
    };
  }
}




[JERSEY-3161] Multiple cookies with same name are not supported Created: 04/Sep/16  Updated: 04/Sep/16

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

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

Server



 Description   

It's possible to have multiple cookies with the same name in the cookie header (e.g. cookies in subdomains/subpaths). So, the following is a valid header:
`Cookie:"token=val1; token=val2"`.

However, `org.glassfish.jersey.server.ContainerRequest.getCookies` returns a `Map<String, Cookie>`, indicating that it returns only one cookie per name. It calls `HttpRequestHeader.readCookies` which in turn calls `CookieParser.parseCookies`. The implementation of `parseCookies` makes it clear that for multiple cookies with the same name, the last one is returned in the map.






[JERSEY-3136] Proxy client throws UnsupportedOperationException when calling hashCode() Created: 14/Jul/16  Updated: 31/Aug/16

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

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


 Description   

In application tear-down phase, Spring Data JPA uses a remove() method on a ConcurrentHashMap (that's why it needs hashCode()) to close all entityManagers. This method is called for each registered bean, therefore the proxy clients as well. The proxy client throws UnsupportedOperationException.

Stack trace:

java.lang.UnsupportedOperationException: Not a resource method.
	at org.glassfish.jersey.client.proxy.WebResourceFactory.invoke(WebResourceFactory.java:189) ~[jersey-proxy-client-2.22.2.jar:na]
	at com.sun.proxy.$Proxy145.hashCode(Unknown Source) ~[na:na]
	at java.util.concurrent.ConcurrentHashMap.hash(ConcurrentHashMap.java:333) ~[na:1.7.0_79]
	at java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:1175) ~[na:1.7.0_79]
	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessBeforeDestruction(PersistenceAnnotationBeanPostProcessor.java:374) ~[spring-orm-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:243) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:972) [spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:979) [spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1006) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:982) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:901) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]

This is very similar to JERSEY-2724 and it is mentioned here



 Comments   
Comment by rsass [ 26/Jul/16 ]

I think there is already a pull request in "Waiting for OCA" state for this issue: https://github.com/jersey/jersey/pull/169

Comment by damokles [ 31/Aug/16 ]

With Spring Boot 1.4.0 another trigger for this problem was added.

Caused by: java.lang.UnsupportedOperationException: Not a resource method.
	at org.glassfish.jersey.client.proxy.WebResourceFactory.invoke(WebResourceFactory.java:189)
	at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
	at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:964)
	at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.requiresDestruction(ScheduledAnnotationBeanPostProcessor.java:423)
	at org.springframework.beans.factory.support.DisposableBeanAdapter.hasApplicableProcessors(DisposableBeanAdapter.java:431)

Looking at the PR 169, which is now older than a year, I highly doubt that the OCA will be signed. The fix itself is trivial however and should also include equals in addition to hashCode. Maybe someone with an already signed OCA could fix it an create a new PR?





[JERSEY-3024] Jersey client does not check response status code if no response type has been specified Created: 22/Dec/15  Updated: 29/Aug/16

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

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


 Description   

Consider a request to delete a resource as follows:

client.target("https://myrestapi.com/widgets/1234").delete();

If the server requires authentication for this request and none has been provided, i.e. no authorization header is present then the response will be 401 unauthorized. In this case I would expect an exception to be thrown however this did not happen. In fact the jersey api has a NotAuthorizedException which is documented to be thrown in such cases.

Looking at the code org.glassfish.jersey.client.JerseyInvocation I see these two methods:

@Override
public Future<Response> submit() {
final SettableFuture<Response> responseFuture = SettableFuture.create();
request().getClientRuntime().submit(requestContext, new ResponseCallback() {

@Override
public void completed(final ClientResponse response, final RequestScope scope) {
if (!responseFuture.isCancelled())

{ responseFuture.set(new InboundJaxrsResponse(response, scope)); }

else

{ response.close(); }

}

@Override
public void failed(final ProcessingException error) {
if (!responseFuture.isCancelled())

{ responseFuture.setException(error); }
}
});

return responseFuture;
}

@Override
public <T> Future<T> submit(final Class<T> responseType) {
if (responseType == null) { throw new IllegalArgumentException(LocalizationMessages.RESPONSE_TYPE_IS_NULL()); }
final SettableFuture<T> responseFuture = SettableFuture.create();
request().getClientRuntime().submit(requestContext, new ResponseCallback() {

@Override
public void completed(final ClientResponse response, final RequestScope scope) {
if (responseFuture.isCancelled()) { response.close(); return; }
try { responseFuture.set(translate(response, scope, responseType)); } catch (final ProcessingException ex) { failed(ex); }
}

@Override
public void failed(final ProcessingException error) {
if (responseFuture.isCancelled()) { return; }
if (error.getCause() instanceof WebApplicationException) { responseFuture.setException(error.getCause()); } else { responseFuture.setException(error); }

}
});

return responseFuture;
}

The former method is called if no response type class has been specified. If this method is called then no check of the response status code is made and therefore no exception is thrown. In the latter method, the call to translate does check the status code and throws an exception as expected.

IMHO this behaviour is surprising. Jersey 1.x always checked the response status code and threw an exception on a server error response unless the response type was set to "Response.class" (ClientResponse.class in Jersey 1.x).



 Comments   
Comment by mkull [ 29/Aug/16 ]

That behaviour is according to the JAX-RS specification. Any method which returns a response will not throw a WebapplicationException because you are expected to evaluate and close the returned response. (If you dont close, bad things happen)

If you look closely, each http verb comes in multiple forms:

  • Response delete(); // does not check response status and will not throw WebapplicationException
  • <T> T delete(Class<T> responseType); // checks response code and throws a WebapplicationException if not successful
  • <T> T get(GenericType<T> responseType); // similar to delete(Class<T> responseType), but for generics

A common workaround is delete(String.class) and ignoring the result.





[JERSEY-3153] Jersey doesn't allow to override a built-in ValidationExceptionMapper Created: 11/Aug/16  Updated: 29/Aug/16

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

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

Windows 7/ Ubuntu 16.04
Oracle JDK 1.7.0_75
Jetty 9.2.13.v20150730
Any Jersey version above 2.14


Tags: exceptions-handling, jersey-bean-validation, weld-integration

 Description   

In attachments you can see a project which uses: Jersey, Weld, Jetty and jersey bean validation module.

The problem is, when I've upgraded Jersey from 2.14 to 2.23.1 my custom exception mapper:

@Provider
public class ValidationExceptionMapper implements
        ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException exception) {
        final ResponseEntity resp = ResponseEntity.builder()
                .message("Hurray, my custom ValidationExceptionMapper was called!")
                .build();

        return Response.status(Status.BAD_REQUEST).entity(resp).build();
    }
}

is no longer called - Jersey uses the built-in exception mapper for this exception: org.glassfish.jersey.server.validation.internal.ValidationExceptionMapper and unfortunately I cannot override it.

The problem is strictly related to the Weld integration. Because without dependency to Weld, my custom exception mapper has a higher priority than the one provided by jersey-bean-validation module.



 Comments   
Comment by gdemecki [ 11/Aug/16 ]

Known workarounds:

  • Downgrade to Jersey 2.14
  • Remove Weld
  • Remove jersey-bean-validation module

BTW: How can I attach a sample reproducer app? Funny, I don't have permissions ^^

Comment by Pavel Bucek [ 11/Aug/16 ]

link to a public github repo is best way how to do that, java.net disabled attachments long time ago..

Comment by gdemecki [ 11/Aug/16 ]

Thanks Pavel,
example app is available on the GitHub.

Comment by Marek Potociar [ 15/Aug/16 ]

I have tried to run your example, but I can see some WELD scanning-related exceptions when I invoke mvn clean package jetty:run from my command line.
Please fix this problem in your reproducer.

Comment by Marek Potociar [ 15/Aug/16 ]

This is the error that I see:
WELD-ENV-000033: Invalid bean archive scanning result - found multiple results with the same reference

Comment by gdemecki [ 17/Aug/16 ]

Thanks Marek, indeed reproducer isn't perfect - I must admit that I've launched it only via the com.xyz.AppRunner.main() from my IDE. Please use it instead of jetty-maven-plugin, if it isn't a problem.





[JERSEY-3151] jersey-mvc-velocity Created: 09/Aug/16  Updated: 25/Aug/16

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

Type: New Feature Priority: Minor
Reporter: Feng-Zihao Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: mvc
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

similar with jersey-mvc-freemarker

provide an mvc extension for velocity



 Comments   
Comment by Feng-Zihao [ 09/Aug/16 ]

Please assign it to me. I would like to give a try on this.

Comment by Feng-Zihao [ 09/Aug/16 ]

Please also alter the affect versions from 2.23.2.

Comment by Pavel Bucek [ 09/Aug/16 ]

Hello,

the issue cannot be assigned to you, since you don't have "developer" role on Jersey project. That is still fine, you can submit pull request via github and the contribution will be considered.

Please note that unless you sign OCA - Oracle Contributor Agreement (http://www.oracle.com/technetwork/community/oca-486395.html), we cannot accept any contribution from you.

Don't hesitate to ask if you have any question.

Regards,
Pavel

Comment by Feng-Zihao [ 09/Aug/16 ]

OK. Fine. I've notice the OCA aggrement.

I'll signed that and proceed the application as a developer as an individual.

Thanks for reply.

Comment by Feng-Zihao [ 15/Aug/16 ]

Excuese me, what's the correct address to submit OCA?

I found 3 different address on OCA website, FAQ site, and the downloaded PDF. I've submitted to these 3 address at the same time.

One week passed, there's still no response.

Comment by Pavel Bucek [ 15/Aug/16 ]
Submitting the OCA procedure
1.  Download the OCA from here: http://www.oracle.com/technetwork/oca-405177.pdf
2.  Print it
3.  Fill out and sign the form (do not forget to fill in the point 7 and provide your mailing address not only your e-mail address)
4.  Scan the paper
5.  Send a picture/PDF to oracle-ca_us [at] oracle [dot] com

The process might take more time than one week, please be patient.

Comment by Feng-Zihao [ 15/Aug/16 ]

OK. Thanks.

Comment by Feng-Zihao [ 25/Aug/16 ]

The OCA is still not complete after 2 weeks.

I'm planning to contribute the code throught github. If I pull merge request from github, will it be merged and considered a contribution?

Also, how can I run all the tests in Jersey project? Where should I write test case? Any document on that?

Thanks.





[JERSEY-3044] File name contains the complete file path when uploaded from IE11 Created: 01/Feb/16  Updated: 24/Aug/16

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

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

IE11


Tags: filename, ie,, ie11, upload

 Description   

When the IE security setting "Include local directory path when uploading files to a server" is set to Enabled, the file name that we get is the complete path of the file.

Header being sent:
Content-Disposition: form-data; name="file"; filename="c:\folder\filename.txt"

File name returned by Jersey : "c:folderfilename.txt". (The path is not trimmed.)

Ideally it should be "filename.txt".



 Comments   
Comment by jsimomaa [ 24/Aug/16 ]

I created a duplicate issue :https://java.net/jira/browse/JERSEY-3159

In the comments there is a proposed pull request to solve this issue





[JERSEY-3159] File upload is broken with IE 11 and Edge: Backslashes in Content-Disposition filename Created: 24/Aug/16  Updated: 24/Aug/16

Status: Open
Project: jersey
Component/s: media
Affects Version/s: 2.22.1, 2.22.2
Fix Version/s: None

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

Windows NT 10.0; WOW64
Internet Explorer 11.51.14393.0
Microsoft Edge 38.14393.0.0


Tags: edge, ie, ie11, upload

 Description   

Original issue and discussion:
https://java.net/jira/browse/JERSEY-759

IE11 and Microsoft Edge both still send non-standard conforming filename:

-----------------------------7db13314200d0
Content-Disposition: form-data; name="file"; filename="C:\tmp\test.txt"
Content-Type: application/octet-stream
What my application gets when reading the filename is "C:tmptest.txt"

This could be fixed like the original issue by matching the User-Agent by adding matching for "Trident/" and "Edge/"



 Comments   
Comment by jsimomaa [ 24/Aug/16 ]

Pull request in GitHub: https://github.com/jersey/jersey/pull/233

Comment by jsimomaa [ 24/Aug/16 ]

Duplicate issue: https://java.net/jira/browse/JERSEY-3044





[JERSEY-3157] Please consider making OAuth2ClientFeature a public class Created: 22/Aug/16  Updated: 22/Aug/16

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

Type: Improvement Priority: Minor
Reporter: apps4u Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 30 minutes
Time Spent: Not Specified
Original Estimate: 30 minutes


 Description   

We have a use case where there is an OAuth2 request back end to back end, with no user interaction possible, so that it appears OAuth2CodeGrantFlow is not a possible solution as this flow expects user interaction, The user has already generated an Access Token and Refresh Token using OAuth2CodeGrantFlow that is stored in a database.

We wish to use the OAuth2ClientFeature as follows
Feature feature = new OAuth2ClientFeature();
client.register(feature);

However this is not possible as the class is package private. Also this would not handle the case that the AccessToken has expired.

Please confirm if this is a valid use case, or is there another way to accomplish what we want.






[JERSEY-3156] Server 500 Error COnn Close, Jersey 200 OK Created: 22/Aug/16  Updated: 22/Aug/16

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

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

Windows 7 Local Machine, Linux on AWS Virtual Server
Tomcat 8.0.36, Tomcat 9.0, Jetty 9.3.11.v20160721



 Description   

Continuously and absolute randomly receiving Internal server erro 500 while all code executing perfectly, logs show that method called was proper, all code executed and results returned in desired manner.

On top of all after going through Jersey "Monitoring Statistics as MBeans" the last method return code is 200 but Rest client always show 500.

Noticeable thing is that unlimited times first time 500 error come and then every thing goes fine on second time, and usually always 500 error come until i make some irrelevant change in code and redeploy.



 Comments   
Comment by khurram_kk [ 22/Aug/16 ]

Version 2.23.1 exactly

Comment by Pavel Bucek [ 22/Aug/16 ]

I'm pretty sure there is some exception logged on the server side. Can you please add it to your report?

Also, reproducible testcase is always appreciated. (you can state that it is reproducible on one of our samples, if you are able to verify that).

Comment by khurram_kk [ 22/Aug/16 ]

Not a single exception, Below is the server side log, I also enabled Jersey logging

***********************************************

INFO: Server startup in 17087 ms
Aug 22, 2016 10:56:05 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Server has received a request on thread http-nio-8080-exec-2
1 > POST http://localhost:8080/core/v1/auth/loginVendor
1 > accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
1 > accept-encoding: gzip, deflate
1 > accept-language: null
1 > connection: keep-alive
1 > content-length: 81
1 > content-type: application/json
1 > host: localhost:8080
1 > user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
10:56:05.759 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalRsRequestAuthFilter - Token recieved from headers : null
10:56:05.764 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalRsRequestAuthFilter - In Auth filter loginOrSignupReq : true - request.getRequestURL() : http://localhost:8080/core/v1/auth/loginVendor
10:56:05.764 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalRsRequestAuthFilter - uri : /core/v1/auth/loginVendor
10:56:06.037 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter - here . . .
10:56:06.040 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter - npe : null
10:56:06.040 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter - In isLoginOrSignupReq : true
10:56:07.243 [http-nio-8080-exec-2] INFO  com.stepSolar.web.rest.auth.AuthRS - login request starts.
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server 127.0.0.1:27017 to client view of cluster
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=MULTIPLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:1}] to 127.0.0.1:27017
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 1]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=8650665}
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Discovered cluster type of STANDALONE
Aug 22, 2016 10:56:09 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:2}] to 127.0.0.1:27017
10:56:10.866 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.id.impl.OgmSequenceGenerator - OGM000060: Sequence id generator used for entity 'InstallerPackaging' is not supported by grid dialect org.hibernate.ogm.datastore.mongodb.MongoDBDialect, falling back to table-based id generation. Consider to use @TableGenerator rather than @SequenceGenerator.
10:56:10.875 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.id.impl.OgmSequenceGenerator - OGM000060: Sequence id generator used for entity 'Currency' is not supported by grid dialect org.hibernate.ogm.datastore.mongodb.MongoDBDialect, falling back to table-based id generation. Consider to use @TableGenerator rather than @SequenceGenerator.
10:56:10.876 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.id.impl.OgmSequenceGenerator - OGM000060: Sequence id generator used for entity 'UserRole' is not supported by grid dialect org.hibernate.ogm.datastore.mongodb.MongoDBDialect, falling back to table-based id generation. Consider to use @TableGenerator rather than @SequenceGenerator.
10:56:10.876 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.id.impl.OgmSequenceGenerator - OGM000060: Sequence id generator used for entity 'Installer' is not supported by grid dialect org.hibernate.ogm.datastore.mongodb.MongoDBDialect, falling back to table-based id generation. Consider to use @TableGenerator rather than @SequenceGenerator.
10:56:10.876 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.id.impl.OgmSequenceGenerator - OGM000060: Sequence id generator used for entity 'InstallerSize' is not supported by grid dialect org.hibernate.ogm.datastore.mongodb.MongoDBDialect, falling back to table-based id generation. Consider to use @TableGenerator rather than @SequenceGenerator.
10:56:11.883 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.datastore.mongodb.impl.MongoDBEntityMappingValidator - OGM001218: Cannot use primary key column name 'sequence_name' for id generator, going to use '_id' instead
10:56:11.883 [http-nio-8080-exec-2] WARN  org.hibernate.ogm.datastore.mongodb.impl.MongoDBEntityMappingValidator - OGM001218: Cannot use primary key column name 'sequence_name' for id generator, going to use '_id' instead
10:56:12.103 [http-nio-8080-exec-2] INFO  com.stepSolar.web.ogm.dao.UsersDao - Validate user call against user : khokhar
10:56:12.319 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.ogm.dao.UsersDao - Query : {"userName":"khokhar","userPassword":"password","userRoles": {$regex : '.*vendor.*'}}
10:56:13.351 [http-nio-8080-exec-2] INFO  com.stepSolar.web.ogm.dao.UsersDao - Validate user call ended against user : 1
10:56:13.355 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - About to check token from cache/db if not expired and already present.
10:56:13.355 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - token from cache null so about to get from db.
10:56:13.355 [http-nio-8080-exec-2] INFO  com.stepSolar.web.ogm.dao.UsersDao - fetchTokenFromDbUsingUserName call against user : khokhar(id:null) - userRole : vendor - tokenID : null
10:56:14.619 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.ogm.dao.UsersDao - tokenFromDb : 57a991f0fd87bf0c5c6b1800
10:56:14.646 [http-nio-8080-exec-2] INFO  com.stepSolar.web.ogm.dao.UsersDao - AddReplace token call ended against user : null
10:56:14.646 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - token from db OK.
10:56:14.646 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - token found from cache or db so now checking expiry.
10:56:14.647 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - about to check token from db for expiry.
10:56:14.743 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - Token from db is unexpired.
10:56:14.744 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.bl.auth.AuthBL - Setting return token to token found
10:56:14.748 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.AuthRS - returnMessage.getData() : {"userId":"1","userName":"khokhar","userRole":"vendor","tokenExpiryStr":"2016-09-08T08:18:55.204","tokenString":"a2hva2hhcnwyMDE2LTA5LTA4VDA4OjE4OjU1LjIwNHx2ZW5kb3J8MQ==|1|vendor"}
10:56:14.748 [http-nio-8080-exec-2] INFO  com.stepSolar.web.rest.auth.AuthRS - login request Ends.
Aug 22, 2016 10:56:14 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Server responded with a response on thread http-nio-8080-exec-2
1 < 200
1 < Access-Control-Allow-Headers: Content-Type, USER-TOKEN
1 < Access-Control-Allow-Methods: GET, POST, DELETE, PUT
1 < Access-Control-Allow-Origin: http://localhost:9000		
1 < Content-Type: application/json
Comment by khurram_kk [ 22/Aug/16 ]

I can also attach the picture for JCOnsole, where Jersey is showing 200 in LastResponseCode for the method, but cant find any link to upload pics

Comment by khurram_kk [ 22/Aug/16 ]
	@POST
	@Path(LOGIN_VENDOR_REQ_PATH)
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	//@StepRoboticsAuthConf(rolesAllowed={UserRolesValues.VENDOR_USER,UserRolesValues.INSTALLER_USER,UserRolesValues.SALESREP_USER})
	public RsRespMessageNoDb loginVendorUser(VendorUser loginReq) throws Exception {
		
		RsRespMessageNoDb returnMessage = null;
		logger.info("login request starts.");
		AuthBL authBL = new AuthBL();
		returnMessage = authBL.loginVendorUser(loginReq);
		logger.debug("returnMessage.getData() : " + returnMessage.getData());
		logger.info("login request Ends.");
		return returnMessage;
	}

This is the method, the returned data is even logged succesfully so for sure every thing went fine but server returning 500. I tried with fresh server installation 3 times and tried it on 3 diff tomcat and 2 diff jetty versions.

Comment by khurram_kk [ 22/Aug/16 ]

Honestly I haven't tried it on any of Jersey Sample.

Comment by Pavel Bucek [ 22/Aug/16 ]

The problem here is that there is still not much we can do, since the code you presented doesn't seem to be reproducible anywhere else. HTTP 500 is usually produced when there is some not handled exception and it is thrown to the container. Put the processing into `try

{ .. }

catch` block and log everything which might be caught. Also, see your resource method signature - you are declaring that you are throwing an exception (maybe that is ok, if you have an exception mapper registered, but we cannot tell from what you presented).

Also, I noticed this line:

10:56:06.040 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter - npe : null

Seems like a NPE to me.

Comment by khurram_kk [ 22/Aug/16 ]

Though I have exception mapper in place but would you suggest me to check it again without throwing exception?

for the line

10:56:06.040 [http-nio-8080-exec-2] DEBUG com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter - npe : null

This is properly handled exception, no problem at all for this line

try

{ methodRolesAllowed = resourceInfo.getResourceMethod().getAnnotation(StepRoboticsAuthConf.class) .rolesAllowed(); }

catch (NullPointerException npe)

{ logger.debug("npe : " + npe.getMessage()); methodRolesAllowed = new String[1]; methodRolesAllowed[0] = "......."; }
Comment by khurram_kk [ 22/Aug/16 ]

I tried it with removing exception mapper , first time same issue second time onwards working fine, but let me tell you it usually happens like this, would you suggest me to try some other server as well.

Comment by Pavel Bucek [ 22/Aug/16 ]

All I'm saying is that it seems like your code is producing an unhandled exception, which is then processed by the container and returned to the client as HTTP 500.

I don't see any Jersey issue here and I cannot evaluate this based on your report, since you did not provide reproducible use case.

What I can advice is to put more loggers and see what is being logged - especially around possible exception sources. Also, if you could try to strip down your app to bare minimum, which still reproduces the issue, it might help to understand what is actually wrong.

Comment by khurram_kk [ 22/Aug/16 ]

Yes I cannot provide reproduce able case in Jersey Sample, but I can provide you this app live URL where you can run and see the error coming and in logs and MOST importantly "JConsole" with help of jersey mbeans is showing jersey results 200.

Comment by Pavel Bucek [ 22/Aug/16 ]

I see the issue with Jersey monitoring reporting 200, but that can still be an issue with the container - that means that Jersey returned Response with HTTP 200, but maybe container wasn't able to process it (the actual cause might be in Jersey, but unfortunately, there are no usable hints in the bug report).

If I were you, I'd start a debugging session (ideally if you can isolate the "500 case"), start somewhere in ApplicationHandler#handle (just to verify the response, code there), go up to container integration code and see what is written to the container. After that, I believe you have more information and the actual root cause.

Comment by Pavel Bucek [ 22/Aug/16 ]

(response is written by ContainerResponseWriter, I guess you are running on top of Servlet, so see (and put a break point into) org.glassfish.jersey.servlet.internal.ResponseWriter#writeResponseStatusAndHeaders )

Comment by khurram_kk [ 22/Aug/16 ]

Ye for sure I forgot to debug, let me debug, will come back with results

Comment by khurram_kk [ 22/Aug/16 ]

break point on
org.glassfish.jersey.servlet.internal.ResponseWriter#writeResponseStatusAndHeaders

LINE 169 :  final String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();

at the point the the variables are below

this	ResponseWriter  (id=82)	
contentLength	280	
responseContext	ContainerResponse  (id=87)	
	closed	true	
	mappedFromException	false	
	messageContext	OutboundMessageContext  (id=86)	
	requestContext	ContainerRequest  (id=102)	
	status	Response$Status  (id=104)	
		code	200	
		family	Response$Status$Family  (id=115)	
		name	"OK" (id=117)	
		ordinal	0	
		reason	"OK" (id=117)	
headers	HeaderUtils$3  (id=93)	

In rest client getting

Status Code: 500 Internal Server Error
    Connection: close
    Date: Mon, 22 Aug 2016 11:05:47 GMT
    Server: Apache-Coyote/1.1
Comment by khurram_kk [ 22/Aug/16 ]

In variables the header variable having value

{Content-Type=[application/json], Access-Control-Allow-Origin=[http://localhost:9000		], Access-Control-Allow-Methods=[GET, POST, DELETE, PUT], Access-Control-Allow-Headers=[Content-Type, USER-TOKEN], X-Jersey-Tracing-000=[START       [ ---- /  ---- ms |  ---- %] baseUri=[http://localhost:8080/core/] requestUri=[http://localhost:8080/core/v1/auth/signupVendor] method=[POST] authScheme=[n/a] accept=[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8] accept-encoding=[gzip, deflate] accept-charset=n/a accept-language=[null] content-type=[application/json] content-length=[946] ], X-Jersey-Tracing-001=[START       [ ---- /  0.14 ms |  ---- %] Other request headers: host=[localhost:8080] user-agent=[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0] connection=[keep-alive] ], X-Jersey-Tracing-002=[PRE-MATCH   [ 1.95 /  8.45 ms |  3.63 %] Filter by [org.glassfish.jersey.filter.LoggingFilter @1e3cc0ea #-2147483648]], X-Jersey-Tracing-003=[PRE-MATCH   [ 3.34 / 11.87 ms |  6.22 %] Filter by [com.stepSolar.web.rest.auth.filter.GlobalRsRequestAuthFilter @290f4bcc]], X-Jersey-Tracing-004=[PRE-MATCH   [ 5.48 / 11.94 ms | 10.21 %] PreMatchRequest summary: 2 filters], X-Jersey-Tracing-005=[MATCH       [ ---- / 12.02 ms |  ---- %] Matching path [/v1/auth/signupVendor]], X-Jersey-Tracing-006=[MATCH       [ ---- / 12.08 ms |  ---- %] Pattern [/application\.wadl(/)?] is NOT matched], X-Jersey-Tracing-007=[MATCH       [ ---- / 12.11 ms |  ---- %] Pattern [/application\.wadl(/.*)?] is NOT matched], X-Jersey-Tracing-008=[MATCH       [ ---- / 12.14 ms |  ---- %] Pattern [/v1/systemOffer(/.*)?] is NOT matched], X-Jersey-Tracing-009=[MATCH       [ ---- / 12.16 ms |  ---- %] Pattern [/v1/installer(/.*)?] is NOT matched], X-Jersey-Tracing-010=[MATCH       [ ---- / 12.18 ms |  ---- %] Pattern [/v1/dashboard(/.*)?] is NOT matched], X-Jersey-Tracing-011=[MATCH       [ ---- / 12.22 ms |  ---- %] Pattern [/v1/location(/.*)?] is NOT matched], X-Jersey-Tracing-012=[MATCH       [ ---- / 12.24 ms |  ---- %] Pattern [/v1/product(/.*)?] is NOT matched], X-Jersey-Tracing-013=[MATCH       [ ---- / 12.27 ms |  ---- %] Pattern [/v1/vendor(/.*)?] is NOT matched], X-Jersey-Tracing-014=[MATCH       [ ---- / 12.29 ms |  ---- %] Pattern [/v1/user(/.*)?] is NOT matched], X-Jersey-Tracing-015=[MATCH       [ ---- / 12.40 ms |  ---- %] Pattern [/v1/auth(/.*)?] IS selected], X-Jersey-Tracing-016=[MATCH       [ ---- / 12.45 ms |  ---- %] Matching path [/signupVendor]], X-Jersey-Tracing-017=[MATCH       [ ---- / 12.48 ms |  ---- %] Pattern [/updateVendorUser(/)?] is NOT matched], X-Jersey-Tracing-018=[MATCH       [ ---- / 12.51 ms |  ---- %] Pattern [/loadVendorUser/([^/]+)(/)?] is NOT matched], X-Jersey-Tracing-019=[MATCH       [ ---- / 12.60 ms |  ---- %] Pattern [/signupVendor(/)?] IS selected], X-Jersey-Tracing-020=[MATCH       [ ---- / 12.63 ms |  ---- %] Pattern [/loginVendor(/)?] is skipped], X-Jersey-Tracing-021=[MATCH       [ ---- / 12.65 ms |  ---- %] Pattern [/tokenauth(/)?] is skipped], X-Jersey-Tracing-022=[MATCH       [ ---- / 12.67 ms |  ---- %] Pattern [/logout(/)?] is skipped], X-Jersey-Tracing-023=[MATCH       [ ---- / 12.69 ms |  ---- %] Pattern [/qTest(/)?] is skipped], X-Jersey-Tracing-024=[MATCH       [ 1.34 / 13.33 ms |  2.50 %] RequestMatching summary], X-Jersey-Tracing-025=[REQ-FILTER  [ 5.06 / 18.50 ms |  9.42 %] Filter by [com.stepSolar.web.rest.auth.filter.GlobalAuthorizationFilter @785f9259]], X-Jersey-Tracing-026=[REQ-FILTER  [ 5.18 / 18.60 ms |  9.64 %] Request summary: 1 filters], X-Jersey-Tracing-027=[RI          [ 0.01 / 19.14 ms |  0.02 %] [org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor @bc6bef4 #10] BEFORE context.proceed()], X-Jersey-Tracing-028=[MBR         [ ---- / 19.22 ms |  ---- %] Find MBR for type=[com.stepSolar.web.ogm.entities.VendorUser] genericType=[com.stepSolar.web.ogm.entities.VendorUser] mediaType=[application/json] annotations=[]], X-Jersey-Tracing-029=[MBR         [ ---- / 19.37 ms |  ---- %] [com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider @24a28bf8] IS readable], X-Jersey-Tracing-030=[MBR         [ ---- / 19.41 ms |  ---- %] [org.glassfish.jersey.jaxb.internal.XmlCollectionJaxbProvider$General @7a203532] is skipped], X-Jersey-Tracing-031=[MBR         [ ---- / 19.44 ms |  ---- %] [org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider$General @3db538e6] is skipped], X-Jersey-Tracing-032=[MBR         [ ---- / 19.47 ms |  ---- %] [org.glassfish.jersey.jaxb.internal.XmlRootObjectJaxbProvider$General @5f01bb17] is skipped], X-Jersey-Tracing-033=[MBR         [ 1.48 / 20.99 ms |  2.75 %] ReadFrom by [com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider @24a28bf8]], X-Jersey-Tracing-034=[RI          [ 0.01 / 21.13 ms |  0.01 %] [org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor @bc6bef4 #10] AFTER context.proceed()], X-Jersey-Tracing-035=[RI          [ 2.06 / 21.17 ms |  3.83 %] ReadFrom summary: 1 interceptors], X-Jersey-Tracing-036=[INVOKE      [29.53 / 50.77 ms | 54.99 %] Resource [com.stepSolar.web.rest.auth.AuthRS @73b98e6a] method=[public com.stepSolar.web.messages.RsRespMessageNoDb com.stepSolar.web.rest.auth.AuthRS.addVendorUser(com.stepSolar.web.ogm.entities.VendorUser)]], X-Jersey-Tracing-037=[INVOKE      [ ---- / 50.91 ms |  ---- %] Response: [org.glassfish.jersey.message.internal.OutboundJaxrsResponse @1b726952 <200/SUCCESSFUL|OK|com.stepSolar.web.messages.RsRespMessageNoDb @434962c>]], X-Jersey-Tracing-038=[RESP-FILTER [ 0.03 / 51.08 ms |  0.06 %] Filter by [com.stepSolar.web.rest.auth.filter.ServerHeaderCustomizer @27bae976]], X-Jersey-Tracing-039=[RESP-FILTER [ 0.81 / 51.93 ms |  1.51 %] Filter by [org.glassfish.jersey.filter.LoggingFilter @499fcecf #-2147483648]], X-Jersey-Tracing-040=[RESP-FILTER [ 0.94 / 51.98 ms |  1.76 %] Response summary: 2 filters], X-Jersey-Tracing-041=[WI          [ 0.03 / 52.18 ms |  0.06 %] [org.glassfish.jersey.filter.LoggingFilter @76aff752 #-2147483648] BEFORE context.proceed()], X-Jersey-Tracing-042=[WI          [ 0.01 / 52.22 ms |  0.01 %] [org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor @bc6bef4 #10] BEFORE context.proceed()], X-Jersey-Tracing-043=[WI          [ 0.02 / 52.27 ms |  0.03 %] [org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor @26961f59 #4100] BEFORE context.proceed()], X-Jersey-Tracing-044=[MBW         [ ---- / 52.35 ms |  ---- %] Find MBW for type=[com.stepSolar.web.messages.RsRespMessageNoDb] genericType=[com.stepSolar.web.messages.RsRespMessageNoDb] mediaType=[[javax.ws.rs.core.MediaType @744ccfb1]] annotations=[@javax.ws.rs.POST(), @javax.ws.rs.Path(value=/signupVendor), @javax.ws.rs.Produces(value=[application/json]), @javax.ws.rs.Consumes(value=[application/json])]], X-Jersey-Tracing-045=[MBW         [ ---- / 52.43 ms |  ---- %] [com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider @1565ff3a] IS writeable], X-Jersey-Tracing-046=[MBW         [ ---- / 52.45 ms |  ---- %] [org.glassfish.jersey.jaxb.internal.XmlCollectionJaxbProvider$General @7a203532] is skipped], X-Jersey-Tracing-047=[MBW         [ ---- / 52.49 ms |  ---- %] [org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider$General @3db538e6] is skipped], X-Jersey-Tracing-048=[MBW         [ 0.99 / 53.52 ms |  1.85 %] WriteTo by [com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider @1565ff3a]], X-Jersey-Tracing-049=[WI          [ 0.00 / 53.59 ms |  0.01 %] [org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor @26961f59 #4100] AFTER context.proceed()], X-Jersey-Tracing-050=[WI          [ 0.00 / 53.62 ms |  0.01 %] [org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor @bc6bef4 #10] AFTER context.proceed()], X-Jersey-Tracing-051=[WI          [ 0.00 / 53.65 ms |  0.01 %] [org.glassfish.jersey.filter.LoggingFilter @76aff752 #-2147483648] AFTER context.proceed()], X-Jersey-Tracing-052=[WI          [ 1.54 / 53.67 ms |  2.87 %] WriteTo summary: 3 interceptors], X-Jersey-Tracing-053=[FINISHED    [ ---- / 53.70 ms |  ---- %] Response status: 200/SUCCESSFUL|OK]}
Comment by Pavel Bucek [ 22/Aug/16 ]

Well, that seems like Jersey returned HTTP 200 and the container converted it to something else. (Assuming that you are debugging the right requires/response pair, but I believe you do). Do you have any Servlet Filter or something like that in your application?

Also, you might want to put another breakpoint to "commit" and also continue with debugging further in the #writeResponseStatusAndHeaders method, since your request seem to have an entity and it is not read/written yet (and the error might be coming from some message body writer). #failure and #commit in the same class can be also useful, but I'd check what is happening with the response AFTER Jersey sends it back to the container.

Anyway, it really seems like "not a bug in Jersey", since everything indicates that Jersey does what it is supposed to do.

Comment by khurram_kk [ 22/Aug/16 ]

I told you same in very start that jersey returning 200, it is with container.

I haven't got any servlet filter but yes there are two "ContainerRequestFilter" one is pre matching and other is defauilt i.e post matching filter.

Right let me debug into commit and failure methods. Will come up with results.

Comment by khurram_kk [ 22/Aug/16 ]

Break point at
Line 194

    public void commit() {
        try {
            callSendError();********

The variables are

this	ResponseWriter  (id=83)	
	asyncExt	AsyncContextDelegateProviderImpl$ExtensionImpl  (id=119)	
	configSetStatusOverSendError	false	
	requestTimeoutHandler	JerseyRequestTimeoutHandler  (id=122)	
	response	ResponseFacade  (id=124)	
		response	Response  (id=133)	
			appCommitted	false	
			coyoteResponse	Response  (id=135)	
				characterEncoding	"ISO-8859-1" (id=178)	
				charsetSet	false	
				commited	false	
				commitTime	-1	
				contentLanguage	null	
				contentLength	281	
				contentType	"application/json" (id=181)	
				contentWritten	0	
				errorException	null	
				fireListener	false	
				headers	MimeHeaders  (id=183)	
				hook	Http11NioProcessor  (id=185)	
				listener	null	
				locale	Locale  (id=191)	
				message	"OK" (id=103)	
				nonBlockingStateLock	Object  (id=194)	
				notes	Object[32]  (id=195)	
				outputBuffer	InternalNioOutputBuffer  (id=196)	
				registeredForWrite	false	
				req	Request  (id=202)	
				status	200	
			errorState	AtomicInteger  (id=137)	
			facade	ResponseFacade  (id=124)	
			format	null	
			included	false	
			isCharacterEncodingSet	false	
			outputBuffer	OutputBuffer  (id=141)	
			outputStream	CoyoteOutputStream  (id=109)	
			redirectURLCC	CharChunk  (id=147)	
			request	Request  (id=150)	
			urlEncoder	UEncoder  (id=155)	
			usingOutputStream	true	
			usingWriter	false	
			writer	CoyoteWriter  (id=158)	
				autoFlush	false	
				error	false	
				formatter	null	
				lineSeparator	"\r\n" (id=164)	
				lock	OutputBuffer  (id=141)	
				ob	OutputBuffer  (id=141)	
				out	OutputBuffer  (id=141)	
				psOut	null	
				trouble	false	
				writeBuffer	null	
	responseContext	SettableFuture<V>  (id=126)	
		executionList	ExecutionList  (id=168)	
		sync	AbstractFuture$Sync<V>  (id=170)	
	useSetStatusOn404	false	

and as usual respopnse in client


    Status Code: 500 Internal Server Error
    Connection: close
    Date: Mon, 22 Aug 2016 11:59:23 GMT
    Server: Apache-Coyote/1.1
Comment by khurram_kk [ 22/Aug/16 ]

Added break point on 239

public void failure(final Throwable error) {
        try {
            if (!response.isCommitted()) {*******

It never reached.

Comment by khurram_kk [ 22/Aug/16 ]

Oooooops, even if failure is not reching and every thing fine, let me check keepAliveTimeout setting of tomcat ... as first time it takes a bit longer to initialiuze db on my side and may be timing out and second time ok......

Comment by khurram_kk [ 22/Aug/16 ]

But during debug, it took very long time but connection was not closed .... confusing





[JERSEY-3155] hk2-cdi bridge doesn't work correkt Created: 12/Aug/16  Updated: 12/Aug/16

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

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

Java SE 1.8.0_92-b14
Windows 7



 Description   

( With maven i use

<dependency>
        <groupId>org.glassfish.jersey.containers.glassfish</groupId>
    	<artifactId>jersey-gf-cdi</artifactId>
    	<version>2.14</version>
</dependency>

)

If i register a concrete resource class, injection works correct e.g.:

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(RootResource.class);
public class RootResource  
 {
  @Inject
  @SimpleDb(value="mariadb")
  private EntityManager em; 
	
  @GET
  @Produces({ "text/plain" })
  public final String getValue()
   {
     ...............................

But now, i load a resource class dynamically, with

c = Class.forName(.....);
and register ist with
resourceConfig.register(c);

or

resourceConfig.registerInstances(c.newInstance());

But, it doesn't work and crashes with error

Unknown HK2 failure detected:
MultiException stack 1 of 1
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl .......................

Have u overseen something, or is it not possible to use
such anonymous classes?






[JERSEY-3139] Jersey picks wrong method when regular expressions are used Created: 19/Jul/16  Updated: 11/Aug/16

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

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


 Description   

A JAX-RS interface has an existing method

    @PUT
    @Consumes("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    @Path("/models/{model}/data/{dataset}")
    public DataSetId uploadData(@PathParam("model") ModelId id, @PathParam("dataset") DataSetId qualifier, LocationData data);

This method works just fine.

Now, I add a new method:

    @GET
    @Path("/models/{model}/data/{dataset}{path:(/[A-Za-z0-9]+/[A-Za-z0-9]+)*}{element:(/[A-Za-z0-9]+)?}")
    public List<PathElement> getDirectChildren(@PathParam("model") ModelId id, @PathParam("dataset") DataSetId qualifier, @PathParam("path") List<PathElement> path, @PathParam("element") LevelId query);

This method also works as expected.

However, now when I try using the first method, I receive a 405:

INFO: 1 * Server responded with a response on thread http-bio-8181-exec-1
1 < 405
1 < Allow: GET,OPTIONS

What appears to be happening is that the call that was originally processed by uploadData(...) is now being sent to getDirectChildren(...). Both methods do match the same path (when "path" and "element" params are absent), but one of them is a PUT whereas the other one is a GET.

The expected behavior is for Jersey to still honor GET vs PUT when the resource path is ambiguous.



 Comments   
Comment by raner [ 11/Aug/16 ]

Any update on this? Has anyone seen a similar problem or can reproduce the issue? Am I making the wrong assumptions here?





[JERSEY-2722] ExceptionMapperFactory should take into account priority of mappers as set by @Priority annotation Created: 03/Dec/14  Updated: 11/Aug/16

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

Type: Improvement Priority: Major
Reporter: sarxos Assignee: Unassigned
Resolution: Unresolved Votes: 5
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:
  • OpenJDK 7 (1.7.0_65)
  • CentOS 6
  • Jetty Embedded 9.x


 Description   

Hello Jersey Team,

After upgrading from 2.6 to 2.13 I discover issue with Jersey exception mappers. I do have my own exception mapper defined for JsonMappingException (among many other mappers), but whenever I send invalid JSON, the Jersey is using default exception mapper that comes registered with JacksonFeature (see logs below):

Request:

2014-12-03 13:14:59,540 [qtp880578076-30] INFO  com.github.sarxos.elm.Application - 15 * Server has received a request on thread qtp880578076-30
15 > POST https://x.x.x.x:8443/xxx/api/register
15 > Content-Type: application/json; charset=UTF-8
{
"t":"abba",
"s":44444,
}

And the response:

2014-12-03 13:14:59,549 [qtp880578076-30] DEBUG org.glassfish.jersey.tracing.general - EXCEPTION_MAPPING Exception mapper [com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper @499ca5ec] maps [com.fasterxml.jackson.databind.JsonMappingException @6600e06] ('Numeric value (44444) out of range of Java byte
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@2eda6dd2; line: 3, column: 10] (through reference chain: com.github.sarxos.elm.Device["s"])') to <400/CLIENT_ERROR|Bad Request> [ 0.09 ms]
2014-12-03 13:14:59,550 [qtp880578076-30] INFO  com.github.sarxos.elm.Application - 16 * Server responded with a response on thread qtp880578076-30
16 < 400
16 < Content-Type: text/plain
Numeric value (44444) out of range of Java byte
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@2eda6dd2; line: 3, column: 10] (through reference chain: com.github.sarxos.elm.Device["s"])

This fragment is important:

Exception mapper [com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper @499ca5ec] maps [com.fasterxml.jackson.databind.JsonMappingException @6600e06] 

I can clearly see, that Jersey is using default JsonMappingExceptionMapper instead of my own mapper I created especially for this purpose.

I suspect that the effect I'm observing is caused by the enhancement implemented by JERSEY-2283 in 2.7, commit 4f04eda4079305b8f5b357902de7d9e09c581d34.

I'm unable to reproduce it on the development environment (Ubuntu 14, Oracle Java 8, Eclipse), but on the test environment (CentOS 6, OpenJDK 7) it is reproducible in 100% cases. I suspect that JARs order or class loading time is important here. In the Jersey ExceptionMapperFactory these two mappers (custom one I expect to be used, and a default one) has the same inheritance distance calculated, so I guess that it's safe to assume that the first one found will be always returned and there is no other order rule here.

Therefore, due to above, maybe it's worth to consider adding e.g. @Piority annotation value to be compared when distance for all available mappers of the same type is exactly the same? What do you think?



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

Until this gets implemented, you should be able to use https://jersey.java.net/apidocs/2.13/jersey/org/glassfish/jersey/spi/ExtendedExceptionMapper.html to workaround the issue.

Comment by sarxos [ 10/Dec/14 ]

Jakub,

Thank you. For now I w/a this by adding this piece of code in my ResourceConfig:

@Inject
public MyResourceConfig(ServiceLocator locator) {
	// w/a for JERSEY-2722
	register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
	// ...
}

This is to skip the code from if block from line 81 in JacksonFeature.java.

Comment by gdemecki [ 09/Oct/15 ]

@Jakub what is the correct usage of the ExtendedExceptionMapper?

I'm asking because with ExtendedExceptionMapper I've failed to override built-in exception mappers:

  • com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper
  • com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper

Only workaround given by @sarxos worked fine for me.

Comment by tomasz.kalkosinski [ 21/Dec/15 ]

This is still an issue in 2.22.1. In effect you cannot implement your own ExceptionMapper that implements ExceptionMapper<ValidationException> interface. Default ValidationExceptionMapper is always first on list and logic in ExceptionMapperFactory#find always prefers first one found.

Jakub Podlesak you cannot use ExtendedExceptionMapper because ExceptionMapperFactory#isPreferredCandidate can use it only if sameDistance is different, not equal.

I cannot workaround that and remove ValidationExceptionMapper from processing ValidationException.

Comment by gdemecki [ 11/Aug/16 ]

tomasz.kalkosinski your own ExceptionMapper<ValidationException> should always have a higher priority than anything provided by Jersey. If you encounter the opposite - please immediately report a bug.

In your case, it can be related to the JERSEY-3153 regression bug - which appears when you're using two Jersey extensions at the same time: jersey-bean-validation and jersey-weld2-se/ jersey-cdi1x. Because without a dependency to Weld, your custom ValidationExceptionMapper will take precedence over the one provided by jersey-bean-validation module.





[JERSEY-3152] Jersey Resource(Without spring @Component) should be able to handle @value annotation Created: 10/Aug/16  Updated: 10/Aug/16

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

Type: Improvement Priority: Minor
Reporter: jeffery.yuan Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: spring
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: spring

 Description   

Jersey 2 uses hk2 spring-brige, it can inject spring service, but can't handle spring's @Value annotation.

Please check http://stackoverflow.com/questions/38133680/why-do-we-need-component-spring-annotation-for-jersey-resource-in-spring-boot-s



 Comments   
Comment by Pavel Bucek [ 10/Aug/16 ]

Shouldn't this be filed against HK2 instead? See http://hk2.java.net/





[JERSEY-3076] Jersey2 + GuiceHK2Bridge and validations will not work Created: 09/Mar/16  Updated: 10/Aug/16

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

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

Java 8
Tomcat 7
Jersey 2.22.2
HK2 guide bridge 2.4.0



 Description   

I have a setup where I run Jersey2 together with Guice through the HK2 bridge. This works fine for the most part until I add jersey-bean-validation however.

On instantiating the InjectingConstraintValidatorFactory.java, the Guice injector is used instead of the internal Jersey injector, therefor the ResourceContext property is not set, leading to an NPE later on.

Just removing the Guice bridge makes the injection go as expected.

java.lang.NullPointerException: null
	at org.glassfish.jersey.server.validation.internal.InjectingConstraintValidatorFactory.getInstance(InjectingConstraintValidatorFactory.java:61)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.createAndInitializeValidator(ConstraintValidatorManager.java:141)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:101)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:125)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:83)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:547)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:487)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:451)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:403)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedConstraint(ValidatorImpl.java:723)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedConstraints(ValidatorImpl.java:601)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateParametersInContext(ValidatorImpl.java:992)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateParameters(ValidatorImpl.java:300)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateParameters(ValidatorImpl.java:254)
	at org.glassfish.jersey.server.validation.internal.DefaultConfiguredValidator.onValidate(DefaultConfiguredValidator.java:175)
	at org.glassfish.jersey.server.validation.internal.ValidationInterceptorExecutor.proceed(ValidationInterceptorExecutor.java:113)
	at org.glassfish.jersey.server.validation.internal.DefaultConfiguredValidator.validateResourceAndInputParams(DefaultConfiguredValidator.java:146)
	at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:134)


 Comments   
Comment by pvanassen [ 09/Mar/16 ]

As a workaround, I now initialise the offending class InjectingConstraintValidatorFactory through the service locator

serviceLocator.createAndInitialize(InjectingConstraintValidatorFactory.class)

This initialised class I provide to Guice which later on is queried for this class.

Comment by pvanassen [ 09/Mar/16 ]

Example of the bug can be found at: https://github.com/synedge/jersey-guice-validation-bug

This is the Jersey validation example, with Guice added.

Comment by jschalanda [ 10/Aug/16 ]

The problem still exists with Jersey 2.23.2 and HK2 2.5.0-b05.





[JERSEY-3126] Spring AOP proxied resources don't inject @Context Created: 22/Jun/16  Updated: 08/Aug/16

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

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


 Description   

Similar to problems reported in JERSEY-2112 and JERSEY-2301, but this is specific to @Context. When using Spring AOP it won't inject fields annotated with a @Context. Pull request with patch and unit test coming shortly via github.

Running project with example here: https://github.com/max-norris/jersey-fix-example (you have to change to a snapshot to see it fixed).






[JERSEY-3150] Injecting HttpServletRequest into ContainerRequestFilter causes exception Created: 03/Aug/16  Updated: 04/Aug/16

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

Type: Bug Priority: Major
Reporter: fpanovski Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: exceptions, hk2, jdk8
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JAX-RS 3.0.18.Final
Jersey Servlet Container 2.23.1
Jetty 9.3.11.v20160721
JDK 8
Debian 8.5 Jessie



 Description   

I have the following JAX-RS Filter which implements the `ContainerRequestFilter`:

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Context
    HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

      // ...
    }
}

Upon trying to run the Jetty server where the Servlet is deployed, I receive the following MultiException:

...
Caused by: A MultiException has 4 exceptions. They are:
1. java.lang.IllegalArgumentException: interface org.glassfish.hk2.api.ProxyCtl is not visible from class loader
2. java.lang.IllegalArgumentException: While attempting to create a Proxy for javax.servlet.http.HttpServletRequest in scope org.glassfish.jersey.process.internal.RequestScoped an error occured while creating the proxy
3. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of resteasy.AuthenticationFilter errors were found
4. java.lang.IllegalStateException: Unable to perform operation: resolve on resteasy.AuthenticationFilter

As far as I have been able to tell, this used to be a bug in Jersey <2.4, which should have been fixed. However, every newer Jersey version I have tried has yielded the same result, and I cannot implement a token-based authentication method as a result (i.e. no request.login() ).

Additional details:

pom.xml entry:

<dependency>
  <groupId>org.glassfish.jersey.containers<groupId>
  <artifactId>jersey-container-servlet</artifactId>
  <version>2.23.1</version>
</dependency>

Server start up and deployment:

public class JettyServer {

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

                WebAppContext webapp = new WebAppContext();
                webapp.setDescriptor("./src/webapp/WEB-INF/web.xml");
                webapp.setWar("/tmp/resteasy.war");
                webapp.setSessionHandler(new SessionHandler());
                Server server = new Server(20080);

                HashLoginService loginService = new HashLoginService("DefaultRealm");
                loginService.setConfig("./src/webapp/default-realm.txt");

                server.addBean(loginService);

                server.setHandler(webapp);

                ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/v1/*");
                jerseyServlet.setInitOrder(0);

                Map<String, String> params = new HashMap<String, String>();
                params.put("jersey.config.server.provider.packages", "resteasy");
                jerseyServlet.setInitParameters(params);


                try {
                        server.start();
                        server.join();
                }
                catch (Exception e) {
                        e.printStackTrace();
                }
                finally {
                        server.destroy();
                }

        }
}


 Comments   
Comment by fpanovski [ 03/Aug/16 ]

Update: I found a very similar situation outlined in a SO question and answer here: http://stackoverflow.com/questions/29974887/jersey-containerrequestfilter-does-not-get-context-servletrequest

However, delegating the injection to a Provider implementing DynamicFeature, registering the Filter to featureContext, and passing the request to the AuthenticationFilter still yields the exact same exception.

Comment by Pavel Bucek [ 03/Aug/16 ]

What do you mean by "JAX-RS 3.0.18.Final"? Aren't you by any chance using RESTEasy?

Comment by fpanovski [ 03/Aug/16 ]

Hello Pavel,

Thanks for the response and for fixing the tags. Yes, I am in fact using RESTEasy together with Swagger (with my server resource stubs having been generated using Swagger Codegen for JAX-RS/RESTEasy). If it is of any help, here is my full pom.xml (I am using the latest non-milestone versions of every dependency, as far as I know):

<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>resteasy</groupId>
  <artifactId>resteasy</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>

    <properties>
      <jersey.version>2.23.1</jersey.version>
      <jetty.version>9.3.11.v20160721</jetty.version>
    </properties>

  <dependencies>

    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>jaxrs-api</artifactId>
      <version>3.0.12.Final</version>
    </dependency>
        <!-- RESTEasy Servlet Initializer -->
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-servlet-initializer</artifactId>
      <version>3.0.18.Final</version>
    </dependency>

    <!-- Jersey Servlet Container -->
    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet</artifactId>
      <version>${jersey.version}</version>
    </dependency>

    <!-- Swagger -->
    <dependency>
      <groupId>com.wordnik</groupId>
      <artifactId>swagger-jaxrs_2.10</artifactId>
      <version>1.3.13</version>
    </dependency>
    <!-- Swagger core -->
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-jaxrs</artifactId>
      <version>1.5.9</version>
    </dependency>

        <!-- Jetty Server core -->
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <version>${jetty.version}</version>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-servlet</artifactId>
      <version>${jetty.version}</version>
    </dependency>
    <!-- Jetty Web app plugin-->
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-webapp</artifactId>
      <version>${jetty.version}</version>
    </dependency>
    <!-- Jetty JMX -->
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-jmx</artifactId>
      <version>${jetty.version}</version>
    </dependency>

    <!-- Logging  -->
        <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!-- Google Gson -->
        <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.7</version>
      <scope>compile</scope>
    </dependency>

    <!-- memcached client -->
        <dependency>
      <groupId>com.whalin</groupId>
      <artifactId>Memcached-Java-Client</artifactId>
      <version>3.0.2</version>
    </dependency>

    <!-- genson JSON converter -->
        <dependency>
      <groupId>com.owlike</groupId>
      <artifactId>genson</artifactId>
      <version>1.4</version>
    </dependency>

        <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
    </dependency>


  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <modules>
        <module>?</module>
  </modules>
</project>

Comment by fpanovski [ 04/Aug/16 ]

Update: In case anyone is following this report and looking for a solution as well, I have found a workaround in the meantime that accomplishes the exact same thing that I wanted to do by injecting the HttpServletRequest. It works by implementing the javax.servlet.Filter interface:

public class AuthenticationFilter implements Filter {

    public void init(...) {...}
    public void destroy(...) {...}

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        // Get request and response objects, we will need to pass them down the filter chain later on
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if(!request.getRequestURI().equals("/auth")) {
                // Check Authorization header and return a 401 if invalid
                String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

                try {
                        if(authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                                response.setStatus(401);
                                return;
                            }
                                // Get username, either from custom header or elsewhere...

                                validateToken(username, authToken);

                                request.login(username, password);
                                chain.doFilter(req, res);

                        } catch (Exception e) {
                                response.setStatus(401);
                                return;
                        }
        }

        chain.doFilter(req, res);

    }
}

The filter also needs to be declared in web.xml, but there are already many examples for that. I hope this helps others in the meantime until there is a solution for the original issue.





[JERSEY-2754] JERSEY-2736: Impossible to define ConnectionReuseStrategy using ApacheConnector Created: 13/Jan/15  Updated: 03/Aug/16

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

Type: Bug Priority: Major
Reporter: Jakub Podlesak Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: ahc, apache
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to JERSEY-2583 Reuse of HttpClientContext in ApacheC... Open

 Description   

There is no way to define ConnectionReuseStrategy for Apache client (using ApacheConnector) through client config, and the fact that ApacheConnector is creating HttpClientBuilder with default value for boolean "systemProperties" (which is "false"), makes it impossible to use "http.keepAlive" system property.



 Comments   
Comment by nkoterba [ 03/Aug/16 ]

I second this issue. If the ApacheConnector is only going go provide limited configuration options via Jersey Configuration object, then it would be nice to have other means to access the HttpClientBuilder either through a filter, listener, callback, etc.





[JERSEY-2583] Reuse of HttpClientContext in ApacheConnector Created: 11/Jul/14  Updated: 03/Aug/16

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

Type: Bug Priority: Major
Reporter: Herr-Herner Assignee: Unassigned
Resolution: Unresolved Votes: 4
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to JERSEY-2754 JERSEY-2736: Impossible to define Con... Open
Tags: connector, connectors
Sprint: Triaged

 Description   

I am using two-way SSL authentication in combination with the ApacheConnector. To get things properly working, I had to modify the sources so that the created HttpClientContext (line 458) is reused, otherwise a new SSL handshake is initiated which causes a lot of overhead.

Is it possible to add that behavior?



 Comments   
Comment by Herr-Herner [ 11/Jul/14 ]

Just for clarification: Every call to the ApacheConnector in the ssl scenario causes a new handshake!

Comment by Herr-Herner [ 14/Jul/14 ]

Just thought about a proper solution... The reusement of the HttpClientContext does not work when different target hosts are addressed because we cannot share the connection information between different hosts. Different target hosts require each their own ssl connection. We can reuse HttpClientContext only when the same host is addressed. Have a look here: http://hc.apache.org/httpcomponents-client-4.4.x/tutorial/html/advanced.html. What we can do is to offer the capability to pass an instance of UserTokenHandler to the HttpClientBuilder. An implementation could extend the default implementation by holding a HashMap mapping the target host, extracted from the HttpClientContext, to the user token received from the extended default implementation if the table does not contain a mapping. But we get a memory leak... How can be ensure that mappings are removed when the connection is closed. What are your thoughts? Is there a better solution?

Comment by Michal Gajdos [ 21/Jul/14 ]

I guess we can use rather some kind of cache instead of a map where token would expire after a certain amount of time (which would lead to a new handshake). Moving to backlog.

Comment by rognor [ 12/Sep/14 ]

The default setting is to maintain a pool per route, so why can't the default be to reuse a connection based on a userType in the context?
I found no way to control this from the outside but by changing this I could force reuse of SSL connections in a nicely manner.

Comment by Herr-Herner [ 24/Sep/14 ]

That sounds interesting... Could you please provide a more detailed description of your idea.

Comment by rognor [ 24/Sep/14 ]

Assuming that reuse of connection should be the default I'd say that the userType in the HttpClientContext should be set from the connector. This way the pool will be able to pick up any already existing connection that isn't leased.
But I suppose this also needs to be configurable so that the userType is taken from the principal as it looks like it is meant to be. Not sure though on how to inject this in the connector but Im sure we can find a good way
This configuration wont be available if you replace the connection manager with lets say the Basic one. But that can probably be clearly documented so users wont run into such problems.

Comment by Herr-Herner [ 26/Sep/14 ]

I am a little bit confused... With 'userType' you actually mean 'userToken', right? I t think with the help of 'UserTokenHandler' offered by the Apache HttpClient, we are able to bind a HttpContext to a specific token, but the question is: How should the API look like? The JerseyClient is not bound to a specific remote endpoint and so there must be something given from the outside that tells an implementation of 'UserTokenHandler' to use which token in combination with which remote endpoint. I think, the best and most flexible way would be to extend the current Apache Connector API in the form that it allows to pass an implementation of 'UserTokenHandler' to the Apache HttpClient. What do you think?

Comment by rognor [ 26/Sep/14 ]

Yeah, my bad. It is userToken.
When looking in the MainClientExec I think it looks like the UserTokenHandler is used later than the actual connection request is done. At request time userToken still is null.
When you say that you will bind the HttpContext to the token, where can that be done?

I'm not sure that the flexibility we're looking at really is needed. As I understand it userToken is supposed to be connected to a user Principal so that should perhaps be configurable. The default can use any value, just to enable connection reuse.

I think the current issue is as in the default jersey connector, where the implementation results in a cache miss when trying to adhere to the keep-alive header.
That code is very different but the pool lookup fails in a similar way there as well.

Comment by ok2c [ 16/Feb/15 ]

According to the HTTP/1.1 protocol spec persistent connections are expected to be state-less and therefore re-usable by different HTTP sessions. In two cases (two way SSL and NTLM) however persistent connections acquire a particular security context and become associated with a particular user identity. HttpClient 4.x intentionally treats such connections differently for security reasons. By default HttpClient chooses to not re-use a state-full connection instead of handing it out to the wrong user by mistake. HttpClient expects the caller to inform it that requests are logically related and are to be executed on behalf of the same user or within the same security context. This is usually accomplished by simply passing the same HttpContext instance to the HttpClient#execute call. So, ideally the caller should be able to pass an HttpContext instance along with the HttpRequest. If that is not possible due to API restrictions an alternative solution could be to always pre-populate HttpContext with a token representing a particular user based on the security context maintained by ApacheConnector. if ApacheConnector does not support different user identities one could also choose to disable connection state tracking altogether.

Oleg

Comment by Herr-Herner [ 16/Feb/15 ]

Is it right, that a stateful HttpClientContext can only be reused when you talk to the same endpoint (host and port)? Would you say, that a cache mapping the endpoint (host and port) to a HttpClientContext is a feasible soultion?

Comment by ok2c [ 16/Feb/15 ]

Not necessarily. It think it is perfectly valid for a HTTP session to span across multiple hosts (via a redirect, for instance).

One also needs to be careful about thread-safely here and to make sure that HttpClientContext instances do not end up used concurrently by multiple threads. While HttpContext classes are perfectly thread-safe they may contain attributes that are not. A cache of immutable user tokens per endpoint may actually work quite well.

Oleg

Comment by Herr-Herner [ 16/Feb/15 ]

Ok.. That sounds interesting. I think the most flexible solution would be to offer the possibility to pass into the ApacheProvider an implementation of e.g. UserTokenRequestHandler, that is used to associate a UserToken to a HttpContext and a HttpUriRequest. A CachedUserTokenRequestHandler could then use a cache of immutable user tokens per endpoint. A default implementation like DefaultUserTokenRequestHandler could return null as it is stated in the Apache docs to indicate that the HttpUriRequest is not user-specific.

Comment by Herr-Herner [ 21/Dec/15 ]

There was already a pull request started for fixing this issue. Maybe it is an adequate solution. Have a look here: https://github.com/jersey/jersey/pull/157

Comment by nkoterba [ 03/Aug/16 ]

I'm chiming in here...because I've just encountered the same issue. In our case, the same CLIENT will always be talking to the same Host/Port.

Sadly, the ApacheConnector doesn't expose any way to get access to its internal ClientBuilder to either call

disableConnectionState

or

setUserTokenHandler

.

Based on the Apache Client documentation here (http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html#stateful_conn), having the ability to set or call those two functions is necessary.

It seems to me that the best solution would be to enable users to pass additional properties into the ApacheConnector (so add things to ApacheClientProperties) or to expose hooks/registers/callbacks to allow users to customize the client that ApacheConnector ultimately creates.

Thus, it's impossible to use the same Apache HTTP connection because we can't verify that the SSL context and principal is identical across all the requests (and it really is). Thus, the pool is Apache HTTP client pool is almost useless as a new request will ALWAYS be created for every request.

@Herr-Herner: Did you ever figure out a way around this?





[JERSEY-3149] Apache Connector connection pooling is not supported properly Created: 02/Aug/16  Updated: 03/Aug/16

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

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

Mac OSX 10.11.4; DropWizard 0.9.2;


Tags: ApacheConnector, Jersey-core

 Description   

This issue has the same result as: https://java.net/jira/browse/JERSEY-2157
but the source cause is different.

In Jersey Client's JerseyInvocation.java (https://github.com/jersey/jersey/blob/927b4d0605aeb119d15e9623dab65c8aec2c8e20/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L943-L953), if the callbackParamClass is of type Response.class, the resulting logic fails to consume or read the entity. It simply casts the response as an InboundJaxrsResponse.

This causes connection-pool starvation when using certain connectors (such as the ApacheConnector), which rely on the entity being "consumed" to release the connection back into the pool, and hitting JERSEY-based servers that return Response objects instead of actual entities.

I included the other "bug" to show how it was resolved: https://github.com/jersey/jersey/blob/927b4d0605aeb119d15e9623dab65c8aec2c8e20/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L995-L999

In essence, on a non-200 response, response.bufferEntity() is called to notify connectors, such as the ApacheConnector, that the entity has been "consumed" and that it should release the current connection back into the Apache ConnectionManager pool (if being used).

I think a similar code-fix needs to be implemented for a successful 200 response that returns a Response object.

I have resorted to calling response.bufferEntity() in all my callbacks and response-handling code to prevent my ApacheConnector pool from suffering from connection starvation because connections are never released.

This issue doesn't affect JERSEY Server REST endpoints that return anything other than Response (unfortunately the JERSEY Server returns Response objects for all "async" server REST handlers...which in our case is quite a few).



 Comments   
Comment by Pavel Bucek [ 02/Aug/16 ]

Response has #close() method - have you tried calling that instead of #bufferEntity()?

BTW, the javadoc explicitly mentions that #close() should be called whenever you are getting a Response instance:

     * The {@code close()} method should be invoked on all instances that
     * contain an un-consumed entity input stream to ensure the resources associated
     * with the instance are properly cleaned-up and prevent potential memory leaks.
     * This is typical for client-side scenarios where application layer code
     * processes only the response headers and ignores the response entity.
Comment by nkoterba [ 03/Aug/16 ]

I agree that calling

bufferEntity

is not ideal. If the entity is being "streamed" this causes the entire entity to be fetched which may defeat the whole purpose of streaming.

However, calling

close

closes the underlying connection which completely defeats the purpose of using Apache HttpClient's PoolingHttpClientConnectionManager.

When I close the connection, this is the log:

DEBUG [2016-08-03 13:54:45,053] org.apache.http.impl.conn.DefaultManagedHttpClientConnection: http-outgoing-15: Close connection
DEBUG [2016-08-03 13:54:45,053] org.apache.http.impl.execchain.MainClientExec: Connection discarded
DEBUG [2016-08-03 13:54:45,053] org.apache.http.impl.conn.PoolingHttpClientConnectionManager: Connection released: [id: 15][route: {s}->https://localhost:8443][total kept alive: 2; route allocated: 2 of 100; total allocated: 2 of 50]
DEBUG [2016-08-03 13:54:45,053] org.apache.http.wire: http-outgoing-15 << "[read] I/O error: Socket is closed"

When I call

bufferEntity

, here is the log:

DEBUG [2016-08-03 13:59:30,928] org.apache.http.impl.execchain.MainClientExec: Connection can be kept alive indefinitely
DEBUG [2016-08-03 13:59:30,929] org.apache.http.client.protocol.ResponseProcessCookies: Cookie accepted [rememberMe="deleteMe", version:0, domain:localhost, path:/xxx, expiry:Tue Aug 02 09:59:30 EDT 2016]
DEBUG [2016-08-03 13:59:30,929] org.apache.http.impl.conn.PoolingHttpClientConnectionManager: Connection [id: 4][route: {s}->https://localhost:8443] can be kept alive indefinitely
DEBUG [2016-08-03 13:59:30,929] org.apache.http.impl.conn.PoolingHttpClientConnectionManager: Connection released: [id: 4][route: {s}->https://localhost:8443][total kept alive: 5; route allocated: 5 of 100; total allocated: 5 of 50]

It seems to me that calling

close

forces the underlying socket connection to close, whereas calling

bufferEntity

just releases the connection/socket back to the Apache ConnectionManager pool (performance gain).

I also don't like that print statement "[read] I/O error: Socket is closed".

If you trace the code in ConnectionHolder.java: https://github.com/apache/httpclient/blob/52c68d6a4f1a14e88f9817270580bb384138040d/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java#L153-L156

You can see that when

close

is called it calls

releaseConnection(false)

. The false parameter is used in the relaseConnection method to determine whether to re-use or permanently close the connection. See: https://github.com/apache/httpclient/blob/52c68d6a4f1a14e88f9817270580bb384138040d/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java#L94-L115

The ultimate crux of the issue is that:
1) Apache HTTPClient wraps entities in a proxy and uses the End-Of-Stream event on that entity to know when to "release" the used connection back to the pool.
2) When the JerseyInvocation sees a Response object it just casts it (instead of reading it) and End-Of-Stream is never called.
3) Response object has

close

and

bufferEntity

methods. The latter "triggers" the Apache HTTPClient to "release" the connection, whereas the former, causes the the Apache HTTPClient lib to "destroy/close" the actual connection/socket.
4) When using ASYNC capability of JERSEY Server (e.g.

@POST
  @Path("/batch")
  public void createObjects(@Suspended AsyncResponse asyncResponse, List<T> objects) {
    ...
  }

), all REST responses are sent as Response objects. Thus, the situation arises.

https://java.net/jira/browse/JERSEY-2157 was resolved by just adding a

response.bufferEntity()

to the error handling code. I get where this makes sense since in an error situation, who cares necessarily if the whole entity is buffered or not.

Ultimately, the best solution would be for Jersey's ApacheConnector to manually "release" the associated connection when an error occurs or a Response object is retrieved vs relying on the "wrapped-entity-proxy, end-of-stream event occurred" in the Apache HttpClient to "release" connections back to the pool but I imagine this would require some re-work of the ApacheConnector and/or Jersey Client (particularly the JerseyInvocation.java class).

Looking at this another way, is it correct logic that a "streaming" response should force a true connection close versus releasing the connection back to the pool? In that case, physically closing the connection may be the "correct" implementation and only those requests which return complete entities should be "recycled"? Without knowing the intent of Jersey and Apache HTTPClient developers, I'm not sure I can correctly answer this question.

But some logic or fix needs to be implemented. For right now, I've just added a ResponseContextFilter to my client that calls bufferEntity on all responses:

config.register(new ClientResponseFilter() {
	@Override
	public void filter(ClientRequestContext clientRequestContext,
	                   ClientResponseContext clientResponseContext) throws IOException
	{
		// Ideally, I would like to get the connection object out of either the request or
		// response context and then use the connection manager we create above to call
		// connectionMgr.releaseConnection(connection).  But I couldn't find any connection
		// object on any of the objects we have here.  I'm also not sure if releasing the connection
		// might cause errors in the processing pipeline b/c the entity (if being streamed) will
		// not have its underlying connection.  So perhaps bufferEntity (as below) is best.

		// Buffer the entity so that Apache HttpClient will release the connection back to the
		// pool and prevent pool starvation for any response with "Response" object
		if (clientResponseContext instanceof ClientResponse) {
			ClientResponse response = (ClientResponse) clientResponseContext;
			response.bufferEntity();
		}
	}
});
Comment by Pavel Bucek [ 03/Aug/16 ]

To sum that up:

You are violating JAX-RS client contract by not calling Response#close(), because Apache connector doesn't have connection pooling correctly implemented. Can you confirm?

If thats the case, I'm inclined to change this to Enhancement and set title to "Apache Connector connection pooling support".

Comment by nkoterba [ 03/Aug/16 ]

@Pavel -

1) I'm not sure where Response#close() should actually be called. Is the burden:
a) on the user who retrieves the Response object? If I call #close(), then I get the error message above and lose the connection re-use performance of the HttpClientConnection pool
b) in JerseyInvocation.java (which is independent of Apache Connector): https://github.com/jersey/jersey/blob/927b4d0605aeb119d15e9623dab65c8aec2c8e20/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L943-L953
c) in ApacheConnector (which is probably the best place since it knows about both Apache HTTPClient and the Response pipeline and I think what you meant in your last comment. Interestingly, at the top of this class, there's a statement that specifically says that if the entity is not read from the response then ClientResponse#close() must be called: https://github.com/jersey/jersey/blob/927b4d0605aeb119d15e9623dab65c8aec2c8e20/connectors/apache-connector/src/main/java/org/glassfish/jersey/apache/connector/ApacheConnector.java#L160-L163.

If ApacheConnector is fixed to call #close() would this then negate the benefits of using the Apache HttpPoolingConnectionManager?

Finally, I'm not sure I would change this to Enhancement vs an Issue/Bug. Without a user knowing they have to explicitly call Response#close() OR Response#entityBuffer(), when using ApacheConnector, they will get connection pool starvation with default connection and socket timeout values (which happen to be infinite by default).

Since most of Jersey now relies on Autocloseable to automatically close or properly handle responses for the Jersey Client API user, it would seem odd to me to force the end API user to have to call either of these methods, but only when using ApacheConnector. Thus, I think this should remain an Issue.

Comment by Pavel Bucek [ 03/Aug/16 ]

Response#close() needs to be called when you have Response with an entity which was not fully consumed. (see the pasted javadoc above). This user of the API is required to call that, since Jersey shouldn't close the entity stream "arbitrarily", and in this case (I assume you have the HTTP 200 OK response), we cannot really do much. Please note that Jersey doesn't want to buffer any entity unless really required.

Apache connector is just a single connector we currently have and it is not the "primary" one, so there are for sure things which could be improved. This issue seems to fall into that category.

It would help if you'd share minimal reproducible testcase.

And the last thing - user needs always call #close, per javadoc (if there is unprocessed entity), so I don't see that as something, which needs to be done only for this connector.





[JERSEY-3021] HttpUrlConnector.secureConnection not always setting custom SSL socket factory Created: 11/Dec/15  Updated: 02/Aug/16

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

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

Ubuntu 14.04, JDK 1.8.0_45



 Description   

To be more precise, due to changes introduced by JERSEY-2899 (https://github.com/jersey/jersey/commit/57f5dafed38d27fcb70e7f4ee5051554118d305a#diff-2af8c9e0f0f9963b8b1ce356cf17ecb7), a custom SSL socket factory is not set on an HttpsURLConnection 'suc' in HttpUrlConnector unless HttpsURLConnection.getDefaultSSLSocketFactory returns the exact same object as suc.getSSLSocketFactory(). This is not a robust way of determining if the custom socket factory has already been set because HttpsURLConnection.getDefaultSSLSocketFactory() can be called simultaneously by multiple threads, returning a different object for each invocation, thus resulting in up to n-1 threads getting a mismatch in HttpUrlConnector.secureConnection, even though suc.getSSLSocketFactory() is actually returning a default SSL socket factory (just not necessarily the exact instance we expected, which is ultimately irrelevant).

This is fairly easy to reproduce, given an HTTPS server with a self-signed certificate. The following code is not a self-contained unit test, but will demonstrate the issue nevertheless, by spitting out at least one SSLHandshakeException (caused by the custom SSLContext not being used). If numThreads is set to 1, then it will never fail due to a certificate validation error. The code will also run without error on Jersey 2.21 or earlier.

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsTest {

    private static SSLContext sslContext = null;

    private static synchronized SSLContext getSslContext() {

        if (sslContext == null) {
            try {
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }

                }}, new SecureRandom());

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return sslContext;
    }

    private Client client;

    public HttpsTest() {

        // Create a Client instance that won't complain about self-signed SSL certs
        client = ClientBuilder.newBuilder().sslContext(getSslContext()).hostnameVerifier(new LenientHostnameVerifier())
                .build();
    }

    private void runTest() {

        try {
            client.target("https://lists.gno.org/self-signed.html").request().get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String... args) throws InterruptedException {

        final int numThreads = 4;

        for (int i = 1; i <= numThreads; i++) {

            new Thread(() -> new HttpsTest().runTest()).start();
        }

        Thread.sleep(10000L);
    }

    /**
     * A HostnameVerifier that always returns true
     */
    private class LenientHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    }
}

I would suggest that the change to HttpUrlConnector.secureConnection could be reverted, or at least if the purpose of it was to avoid redundant calls to setSSLSocketFactory (the cost of which is arguably insignificant), that comparing suc.getSSLSocketFactory to sslSocketFactory.get() might be more appropriate than comparing it to HttpsUrlConnection.getDefaultSSLSocketFactory().



 Comments   
Comment by nkoterba [ 28/Jul/16 ]

Issue is still present on Version 2.23.1.

I spent 2+ days trying to understand why simultaneous JERSEY client SSL REST requests to our server were failing. As mentioned, out of N requests, N-1 would ALWAYS fail, 1 request would always succeed. If I added a delay between REST requests of around 100-200 ms, all requests would succeed indicating to me a threading/deadlock/resource competition in the JERSEY client logic.

On the recommendation of a colleague, I switched from using the default JERSEY REST client connector (Based on HttpUrlConnector) to the Apache REST client connector (maven: org.apache.httpcomponents:httpclient:4.5.2), and immediately all N requests were successfully sent and received.

This seems like a *MASSIVE* bug and it sounds like the OP has isolated the exact location and cause of this issue.

I am commenting here versus opening up a new ticket because I'm hoping this will get addressed very soon in future Jersey versions. Until then, we will be using the Apache Connector.

Comment by nkoterba [ 28/Jul/16 ]

I think this issue is entirely related: https://java.net/jira/browse/JERSEY-3124

Comment by nkoterba [ 02/Aug/16 ]

I switched to using the ApacheConnector and found since that doesn't use HttpUrlConnector, multi-threaded requests once again started working.

However, I did encounter two additional issues that I'm posting here for others:
(if using SSL): https://java.net/jira/browse/JERSEY-3051
(if using JERSEY Server and it sends Response objects back): https://java.net/jira/browse/JERSEY-3149





[JERSEY-3051] SSLContext not propagated to PoolingHttpClientConnectionManager Created: 10/Feb/16  Updated: 02/Aug/16

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

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


 Description   

I'm migrating Jersey 1.x to 2.0 and I found that with had some issues with SSL.

I'm not using keystore in the client, instead I used : TrustManager and HostnameVerifier. If I use that, I'll obtain a javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:...

I trace the code, and found that PoolingHttpClientConnectionManager was using a default SSLFactory instead of the SSLContext that I used for the client.

When I recreate PoolingHttpClientConnectionManager with my settings, it works. (the SSL handshake).



 Comments   
Comment by survivant [ 10/Feb/16 ]

I wanted to post a .zip for my demo project, but I don't see the option. I'll post the file manually instead

here my 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>com.demo</groupId>
    <artifactId>jerseyssldemo</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <jersey.version>2.22.1</jersey.version>
    </properties>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.connectors</groupId>
            <artifactId>jersey-apache-connector</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-jaxb</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.fastinfoset</groupId>
            <artifactId>FastInfoset</artifactId>
            <version>1.2.13</version>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

My DEMO

package com.demo;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.client.filter.EncodingFeature;
import org.glassfish.jersey.message.GZipEncoder;

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author Sebastien Dionne
 */
public class Jersey2SSLClient {

    public static final int defaultMaxPerRoute = 5;
    public static final int maxPool = 20;
    public static final int timeout = 30000;

    public static final boolean sslEnabled = true;

    public static final String username = "admin";
    public static final String password = "password";

    public static final String host = "https://xx.xx.xx.xx";
    public static final String path = "/demossl";

    public static final String acceptType = "application/fastinfoset";

    private static WebTarget webTarget = null;


    public static Client createClientForcePoolingHttpClientConnectionManagerWithSSL() throws Exception {
        return createClient(true);
    }

    /**
     * Creates the Jersey Client Configuration
     * @return
     */
    public static Client createClient() throws Exception {
        return createClient(false);
    }

    /**
     * Creates the Jersey Client Configuration
     * @return
     */
    public static Client createClient(boolean forceSSLFactory) throws Exception {

        Client client = null;

        ClientConfig clientConfig = new ClientConfig();

        clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, maxPool);
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, timeout);
        clientConfig.property(ClientProperties.READ_TIMEOUT, timeout);

        clientConfig.register(MyBeanMessageBodyReader.class);

        // ApacheConnectorProvider configuration
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, makeConnectionManager(defaultMaxPerRoute, maxPool));
        clientConfig.connectorProvider(new ApacheConnectorProvider());

        // requires authentication, have the client automatically send the credentials
        clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);

        HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basicBuilder().nonPreemptive().credentials(username, password).build();
        clientConfig.register(authenticationFeature);

        clientConfig.register(new EncodingFeature("gzip", GZipEncoder.class));


        // SSL configuration
        if (sslEnabled)  {
            TrustManager[ ] certs = new TrustManager[ ] {
                    new X509TrustManager() {
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType)
                                throws CertificateException {
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType)
                                throws CertificateException {
                        }
                    }
            };

            HostnameVerifier allHostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };

            SSLContext sslContext = null;

            try {
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, certs, new SecureRandom());

                // HACK..why !
                if(forceSSLFactory){
                    Registry r = RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", new SSLConnectionSocketFactory(sslContext, allHostnameVerifier)) // force
                            .build();

                    PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(r);
                    pool.setMaxTotal(maxPool);
                    pool.setDefaultMaxPerRoute(defaultMaxPerRoute);

                    clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, pool);
                }
            } catch (GeneralSecurityException ex) {
                System.err.println("Could not configure Jersey to accept all SSL Certificates.");
                throw ex;
            }

            client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(allHostnameVerifier).withConfig(clientConfig).build();

        } else {
            // no SSL
            client = ClientBuilder.newClient(clientConfig);
        }

        return client;
    }

    private static HttpClientConnectionManager makeConnectionManager(int defaultMaxPerRoute, int maxConnections) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxConnections);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return connectionManager;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Starting demo");

        String value = null;

        Client client = createClient();

        WebTarget webTarget = client.target(host).path(path);

        // GET
        try {
            value = webTarget.request(acceptType).method("GET", String.class);
        } catch (Exception e){
            e.printStackTrace();


            /*
        I'll obtain this error

        Exception in thread "main" javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:481)
	at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:255)
	at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
	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:696)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
	at com.demo.Jersey2SSLClient.main(Jersey2SSLClient.java:155)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

         */
        }

        System.out.println("");
        System.out.println("");
        System.out.println(" FORCE SSLFACTORY");

        client = createClientForcePoolingHttpClientConnectionManagerWithSSL();

        webTarget = client.target(host).path(path);

        // GET
        try {
            value = webTarget.request(acceptType).method("GET", String.class);
        } catch (Exception e) {
            e.printStackTrace();

            /*
            Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: org.apache.http.MalformedChunkCodingException: Unexpected content at the end of chunk
	at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:806)
	at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
	at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
	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:696)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
	at com.demo.Jersey2SSLClient.main(Jersey2SSLClient.java:162)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.apache.http.MalformedChunkCodingException: Unexpected content at the end of chunk
	at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:259)
	at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:227)
	at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:186)
	at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
	at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:238)
	at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
	at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)
	at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:73)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
	at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
	at java.io.FilterInputStream.read(FilterInputStream.java:133)
	at org.glassfish.jersey.message.internal.EntityInputStream.read(EntityInputStream.java:102)
	at org.glassfish.jersey.message.internal.EntityInputStream.read(EntityInputStream.java:102)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream.read(ReaderInterceptorExecutor.java:296)
	at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.Reader.read(Reader.java:140)
	at org.glassfish.jersey.message.internal.ReaderWriter.readFromAsString(ReaderWriter.java:175)
	at org.glassfish.jersey.message.internal.ReaderWriter.readFromAsString(ReaderWriter.java:160)
	at org.glassfish.jersey.message.internal.AbstractMessageReaderWriterProvider.readFromAsString(AbstractMessageReaderWriterProvider.java:117)
	at org.glassfish.jersey.message.internal.StringMessageProvider.readFrom(StringMessageProvider.java:77)
	at org.glassfish.jersey.message.internal.StringMessageProvider.readFrom(StringMessageProvider.java:59)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
	at org.glassfish.jersey.spi.ContentEncoder.aroundReadFrom(ContentEncoder.java:127)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:808)
	at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
	at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:803)
	... 14 more

             */
        }

        System.out.println("Value = " + value);


    }

}


My MessageReader

package com.demo;

import com.sun.xml.fastinfoset.stax.StAXDocumentParser;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @author Sebastien Dionne
 */
@Provider
@Consumes("application/fastinfoset")
public class MyBeanMessageBodyReader implements MessageBodyReader<Object> {

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        if(!this.supportsMediaType(mediaType)) {
            return false;
        }
        return true;
    }

    protected boolean supportsMediaType(MediaType mediaType) {
        if(null == mediaType) {
            return true;
        }
        String subtype = mediaType.getSubtype();
        return subtype.equals("fastinfoset");
    }

    @Override
    public Object readFrom(Class<Object> type,
                           Type genericType,
                           Annotation[] annotations, MediaType mediaType,
                           MultivaluedMap<String, String> httpHeaders,
                           InputStream entityStream) throws IOException, WebApplicationException {

        try {
            // It is assumed that it should be a Status OK if we are here
            JAXBContext jaxbContext = JAXBContext.newInstance(String.class, type);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            StAXDocumentParser p = new StAXDocumentParser(entityStream);
            return type.isAnnotationPresent(XmlRootElement.class) ? unmarshaller.unmarshal(p) : unmarshaller.unmarshal(p, type).getValue();
        } catch(Exception e){
            e.printStackTrace();
        }

        return null;
    }

}

Comment by nkoterba [ 02/Aug/16 ]

I have noticed something very similar that may be the same issue.

When I was creating a Jersey Client with the default ApacheConnectorProvider, I was able to configure my SSLContext by setting it directly with the clientBuilder:

ClientBuilder clientBuilder = ClientBuilder.newBuilder();
ClientConfig config = new ClientConfig();

// Use the ApacheConnectorProvider with default PoolingHttpClientConnectionManager
config.connectorProvider(new ApacheConnectorProvider());

clientBuilder.withConfig(config);

if (settings.getTls() != null) {
	SslConfigurator sslConfig = SslConfigurator.newInstance()
			.trustStorePassword(settings.getTls().getTrustStorePassword())
			.keyPassword(settings.getTls().getKeystorePassword());

	sslConfig.keyStoreFile(settings.getTls().getKeystore());
	sslConfig.trustStoreFile(settings.getTls().getTrustStore());

	clientBuilder.sslContext(sslConfig.createSSLContext());
}

return clientBuilder.build();

However, as soon as I tried to provide my own PoolingHttpClientConnectionManager to my clientBuilder, my SSLContext settings were no longer being applied:

ClientBuilder clientBuilder = ClientBuilder.newBuilder();
ClientConfig config = new ClientConfig();

// Use the ApacheConnectorProvider
config.connectorProvider(new ApacheConnectorProvider());

// But provide a *CUSTOM* PoolingHttpClientConnectionManager -- THIS SEEMS TO NOT RESPECT THE SSLCONTEXT set below.
PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
manager.setDefaultMaxPerRoute(40);
manager.setMaxTotal(200);
config.property(ApacheClientProperties.CONNECTION_MANAGER, manager);

clientBuilder.withConfig(config)

if (settings.getTls() != null) {
	SslConfigurator sslConfig = SslConfigurator.newInstance()
			.trustStorePassword(settings.getTls().getTrustStorePassword())
			.keyPassword(settings.getTls().getKeystorePassword());

	sslConfig.keyStoreFile(settings.getTls().getKeystore());
	sslConfig.trustStoreFile(settings.getTls().getTrustStore());

        // SETTING the SSL Context on the client builder seems to have NO AFFECT when setting a custom CONNECTION_MANAGER
	clientBuilder.sslContext(sslConfig.createSSLContext());
}

return clientBuilder.build();

My guess is the ApacheConnectionProvider is not correctly propagating the SSLContext set on the clientBuilder to the instantiated PoolingHttpClientConnectionManager.

Is this expected behavior? If so, it would be nice if it was documented. If not, then it would be nice if the bug was fixed.

Comment by nkoterba [ 02/Aug/16 ]

The relevant source code in the ApacheConnector that creates the ConnectionManager if one isn't specifically provided is available here: https://github.com/jersey/jersey/blob/master/connectors/apache-connector/src/main/java/org/glassfish/jersey/apache/connector/ApacheConnector.java#L331-L382

As one can see, the internal logic is very similar to that shared by the OP.

The logic that "bypasses" using anything configured on the Client (SSLContext, hostname, etc.) if a "CUSTOM" ConnectionManager is provided can be found here: https://github.com/jersey/jersey/blob/master/connectors/apache-connector/src/main/java/org/glassfish/jersey/apache/connector/ApacheConnector.java#L303-L312

We see that if we explicitly provide a ConnectionManager during our Client "builder" stages, that ConnectionManager must be entirely setup similar to the code in Lines 331-382. An explicit ConnectionManager is not decorated with *any* properties specified by the ClientConfig or Client itself (e.g. SSLContext on the client is not added/set to the explicit ConnectionManager).





[JERSEY-3148] basic authenticator ignores sslContext in repeatRequest() Created: 02/Aug/16  Updated: 02/Aug/16

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

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

any



 Description   

In a basic authentication scenario, the custom trustStore or sslContext configured in a jersey Client, is droped/ignored/not-cloned/not-copied by the HttpAuthenticationFilter.repeatRequest() method - and as a result repatRequest() creates a new client with a default trustStore, which causes the second basic authentication request to fail with an SSLHandshakeException (i.e. in the case the server side uses a self-signed certificate).

The repeatRequest() method creates a new client by calling ClientBuilder.newClient(request.getConfiguration()). However the JerseyClientBuilder.newClient() implementation does not copy the SSLContext from the original configuration.

A simple workaround, by specifying a custom factory under META-INF/services/javax.ws.rs.client.ClientBuilder might look like this:

    public class JerseyClientBuilderFix extends JerseyClientBuilder {
	@Override
	public JerseyClientBuilder withConfig(Configuration config) {
		JerseyClientBuilder res = super.withConfig(config);
		if(config instanceof ClientConfig) {
			JerseyClient client = ((ClientConfig)config).getClient();
			if(client != null){
				SSLContext sslContext = client.getSslContext();
				res.sslContext(sslContext);
			}
		}
		return res;
	}
    }

however I wonder if it wouldn't be better to:

  • let JerseyClientBuilder.withConfig() also copy the SSL relevant settings
  • let repeatRequest() reuse the existing Client





[JERSEY-3147] NullPointerException in ServerProcessingBinder.java:154 when using jersey-media-json-jackson Created: 28/Jul/16  Updated: 29/Jul/16

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

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

Tested on windows and ubuntu (with java build 1.8.0_101-b13)


Tags: NullPointerException

 Description   

When adding jersey-media-json-jackson as a mvn dependency, a NPE is triggered when using a custom injected context.

I have marked it as minor as it is possible to just ignore the crash as it does not seem to have any effect on the functionally of the server.

A minimal repro case is available at https://github.com/PhroZenOne/jersey-json-bug

For stacktrace see: https://github.com/PhroZenOne/jersey-json-bug/blob/master/stacktrace.txt

To reproduce this issue run:

git clone git@github.com:PhroZenOne/jersey-json-bug.git
cd jersey-json-bug/
mvn -Dtest=BugTrigger test



 Comments   
Comment by phrozen [ 29/Jul/16 ]

Seems like I was a bit hasty when said that it is just to ignore the crash. Sometimes it does trigger an internal server error, sometimes it does not. I have still not been able to see a pattern as to what does it but I suspect timing issues.





[JERSEY-3120] WADL documentation has syntax and semantic errors Created: 06/Jun/16  Updated: 28/Jul/16

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

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


 Description   

There is a documentation problem: 2 paragraphs have missing/wrong text which makes it not understandable.
in: https://jersey.java.net/documentation/latest/wadl.html
section 17.1. "WADL introduction"
after the code example "Example 17.2."

This is the copied/pasted text referred:

Second resource with a path "application.wadl" has, again, similar OPTIONS methods and one GET method which return this WADL. There is also a sub-resource with a path defined by path param

Unknown macro: {path}

. This means that you can request a resource on the URI http://localhost:9998/application.wadl/something. This is used only to return an external grammar if there is any attached. Such a external grammar can be for example an XSD schema of the response entity which if the response entity is a JAXB bean. An external grammar support via Jersey extended WADL support is described in sections below.

All resource that were added in this second example into the WADL contains element extended. This means that this resource is not a part of a core RESTful API and is rather a helper resource. If you need to mark any your own resource are extended, annotate is with @ExtendedResource. Note that there might be methods visible in the default simple WADL even the user has not added them. This is for example the case of MVC added methods which were added byModelProcessor but are still intended to be used by the client to achieve their primary use case of getting formatted data.



 Comments   
Comment by Pavel Bucek [ 28/Jul/16 ]

are you referring to "Unknown macro"? I don't see that in my browser, maybe you have some customisation on your end?





[JERSEY-3145] Client return wrong content, if content is EMPTY on 200 OK Created: 27/Jul/16  Updated: 27/Jul/16

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

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

Jersey, Jackson



 Description   

We have a Webserivce:

    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public String getSomeValue( .... ) {

    }

Sometimes this Webservice returns an empty String. In this case, the Client side does strange things. The packet will be parsed two times (at least it will be printed 2 times by the LoggingFilter.

At first correctly:

Jul 27, 2016 12:02:40 PM org.glassfish.jersey.filter.LoggingFilter log
INFORMATION: 8 * Client response received on thread main
8 < 200
8 < Cache-Control: private
8 < Content-Length: 0
8 < Content-Type: application/xml
8 < Date: Wed, 27 Jul 2016 10:02:39 GMT
8 < Expires: Thu, 01 Jan 1970 01:00:00 CET
8 < Server: Apache-Coyote/1.1
8 < Set-Cookie: JSESSIONID=A1DAA8CB4B949BC6219B58CDD19EB949; Path=/; HttpOnly

Second wrong:

Jul 27, 2016 12:02:40 PM org.glassfish.jersey.filter.LoggingFilter log
INFORMATION: 7 * Client response received on thread main
7 < 200
7 < Cache-Control: private
7 < Content-Length: 0
7 < Content-Type: application/xml
7 < Date: Wed, 27 Jul 2016 10:02:39 GMT
7 < Expires: Thu, 01 Jan 1970 01:00:00 CET
7 < Server: Apache-Coyote/1.1
7 < Set-Cookie: JSESSIONID=A1DAA8CB4B949BC6219B58CDD19EB949; Path=/; HttpOnly
<html><head><title>OpenPDM Server - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>This request requires HTTP authentication.</u></p><HR size="1" noshade="noshade"><h3>OpenPDM Server</h3></body></html>

The error seems to be either the first or last (cannot be verified) occured error for this client instance.
We use digest authentication, but this is not or at least should not be the root cause.






[JERSEY-2085] nested jar can't find class path resource. Created: 07/Sep/13  Updated: 26/Jul/16

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

Type: Bug Priority: Minor
Reporter: otkmnb2783 Assignee: Pavel Bucek
Resolution: Unresolved Votes: 8
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Sprint: Triaged

 Description   

nested jar files structured in the following way:

 
  nested.jar
    ||-- lib
       ||--jersey-server2.2.jar
       ||--
       ||-- jersey-spring3-2.2.jar
          ||-- org.glassfish..... 

 
ResourceFinderException occurs.
This is exception stacktrace.

 
  org.glassfish.jersey.server.internal.scanning.ResourceFinderException: java.io.FileNotFoundException: .../boot-jetty.jar!/lib/jersey-spring3-2.2.jar (No such file or directory)
	at org.glassfish.jersey.server.internal.scanning.JarZipSchemeResourceFinderFactory.create(JarZipSchemeResourceFinderFactory.java:86)
	at org.glassfish.jersey.server.internal.scanning.JarZipSchemeResourceFinderFactory.create(JarZipSchemeResourceFinderFactory.java:64)
	at org.glassfish.jersey.server.internal.scanning.PackageNamesScanner.addResourceFinder(PackageNamesScanner.java:280)
	at org.glassfish.jersey.server.internal.scanning.PackageNamesScanner.init(PackageNamesScanner.java:196)
	at org.glassfish.jersey.server.internal.scanning.PackageNamesScanner.&lt;init&gt;(PackageNamesScanner.java:153)
	at org.glassfish.jersey.server.internal.scanning.PackageNamesScanner.&lt;init&gt;(PackageNamesScanner.java:110)
	at org.glassfish.jersey.server.ResourceConfig.packages(ResourceConfig.java:665)

This exception happends because JarZipSchemeResourceFinderFactory is one time split(! last index only).



 Comments   
Comment by Jakub Podlesak [ 12/Sep/13 ]

What is the runtime container? Could you please provide a reproducible test case? Thanks in advance!

Comment by Libor Kramolis [ 24/Oct/13 ]

Kind reminder - questions by Jakub Podlesak.

Comment by Marek Potociar [ 30/Oct/13 ]

Linking the related pull request.

Comment by otkmnb2783 [ 04/Nov/13 ]

Runtime Continar is Spring-boot.

It can start jersey from a embedded server(Jetty or Tomcat).

Comment by d0lphin [ 25/Feb/14 ]

I am experiencing the same problem with Spring Boot 1.0.0.RC3 and Jersey 2.6.
I think I can create a reproducible test case if it's still needed.

Comment by linusf [ 20/Mar/14 ]

Spring Boot 1.0.0.RC4 and Jersey 2.7 has the very same issue. Probably introduced somewhere between Jersey 2.5.1 and 2.6.

Comment by hay_dave [ 01/Oct/14 ]

There is a work around, but it would be nice not to have to enumerate each JAR file that has packages we want to scan.

https://github.com/spring-projects/spring-boot/issues/1345#issuecomment-51502294

Comment by cowwoc [ 25/Jun/15 ]

According to https://github.com/spring-projects/spring-boot/issues/1468#issuecomment-84110173 this bug affects JAR files embedded in normal WAR files. Consider increasing the priority of this bug.

Comment by qunfei [ 14/Sep/15 ]

I have fix this problem on my person jersey verison clone from jersery tag 2.14.(git checkout -b JERSEY-2085 2.14)

https://github.com/wuqunfei/jersey/commit/2effce3fea521dee026a9d7103ee4e7099d9dbf9
But I don't which jersery branch I could pull request. @cowwoc @hay_dave linusf @d0lphin @Marek Potociar

Comment by Stepan Vavra [ 11/Jan/16 ]

We'll take a look at it (hopefully soon).
If possible, create a pull request against the master branch (and possibly 2.x).

Comment by qunfei [ 25/Jan/16 ]

the bug was fixed, please merge it.
https://github.com/jersey/jersey/pull/196

Comment by afranken [ 25/Jul/16 ]

the fix has been available for months now, what's the holdup here?

Comment by cowwoc [ 25/Jul/16 ]

This has been going on for a while now. See https://javaee-guardians.io/lack-of-java-ee-8-progress/

Comment by Pavel Bucek [ 26/Jul/16 ]

@cowwoc: this has nothing to do with Java EE 8.

Comment by cowwoc [ 26/Jul/16 ]

@pavel My point is that ever since Oracle bought Sun (around the time Jersey 2.x was released) there has been a major drop in activity and transparency by Sun/Oracle staff.

I would like nothing more than to have you prove me wrong by increasing the development rate and community support. I'm sure that @afranken would love to know when this pull request will get merged.

Comment by Pavel Bucek [ 26/Jul/16 ]

@cowwoc

ad 1) this is not the place to discuss that issue, please don't pollute our issue tracker with non-related stuff.
ad 2) I'm no there to "prove you wrong". Honestly, if you are going to give us this kind of attitude, it won't help anything.

OP & pull author:

this issue (including pull request) is on my TODO list now, it should be processed "soon" (read: when I have time). I already assigned it to myself. The pull request itself does not contain any test, I guess that was an issue, but nobody indicated that to the pull request author. Also, providing a test for this issue might be difficult, so I'll see if I can do the test or at least test it manually so I am somehow sure that it won't break anything.





[JERSEY-3143] Maven ArtifactId=jersey-quickstart-webapp seems to miss Dependency to javax.servlet Created: 26/Jul/16  Updated: 26/Jul/16

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

Type: Bug Priority: Trivial
Reporter: Londane Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 1 minute
Time Spent: Not Specified
Original Estimate: 1 minute


 Description   

I go trough the Tutorial: https://jersey.java.net/documentation/latest/getting-started.html#new-webapp

After generating the WebApp project with Maven, and importing into Eclipse i have a similar error to : http://stackoverflow.com/questions/22756153/the-superclass-javax-servlet-http-httpservlet-was-not-found-on-the-java-build

After adding javax.servlet to dependencies my errors disappeared.
See http://stackoverflow.com/a/22756202/1528488

Is the javax.servlet missing in the Archetype?

--------------------------------------------------------------------------------------------
I also have the following Exceptions, do they also Warnings, are they to be expected? If yes can the Tutorial pls mention that?

Broken single-root rule: Only one <wb-resource> element with a deploy path of "/" is allowed for a web project or an EAR project
Broken single-root rule: The output folder for a web project must be <root folder>/WEB-INF/classes



 Comments   
Comment by Londane [ 26/Jul/16 ]

Error:
"I also have the following Exceptions, do they also Warnings, are they to be expected?"
should be
"I also have the following Warnings, are they to be expected?"





[JERSEY-3142] Maven Generate command in Getting Started Documentation needs Hint for Windows user Created: 26/Jul/16  Updated: 26/Jul/16

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

Type: Improvement Priority: Trivial
Reporter: Londane Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: 30 minutes
Time Spent: Not Specified
Original Estimate: 30 minutes


 Description   

The mvn commands in the Getting stared documentation don't work for Windows users. In Windows you have to add ".." around the Options.
(see http://stackoverflow.com/a/31237376/1528488 )

If you write a Hint on how to use it, that would help newbies like me.

Windows version of Maven commands in Getting-Started tutorial:
---------------------------------------------------------------------------------------------
mvn archetype:generate
"-DarchetypeArtifactId=jersey-quickstart-grizzly2"
"-DarchetypeGroupId=org.glassfish.jersey.archetypes" "-DinteractiveMode=false"
"-DgroupId=com.example -DartifactId=simple-service" "-Dpackage=com.example"
"-DarchetypeVersion=2.23.1"
---------------------------------------------------------------------------------------------
mvn archetype:generate
"-DarchetypeArtifactId=jersey-quickstart-webapp"
"-DarchetypeGroupId=org.glassfish.jersey.archetypes"
"-DinteractiveMode=false"
"-DgroupId=com.example"
"-DartifactId=simple-service-webapp"
"-Dpackage=com.example"
"-DarchetypeVersion=2.23.1"






[JERSEY-3141] HK2 failure has been detected in a code that does not run in an active Jersey Error scope Created: 25/Jul/16  Updated: 25/Jul/16

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

Type: Bug Priority: Major
Reporter: sfrey Assignee: Unassigned
Resolution: Unresolved Votes: 2
Labels: exceptions, hk2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7, Java 1.8.0_91, Tomcat 8.5.3.


Tags: dependency-injection, hk2

 Description   

Currently I am developing a jersey based RESTful application and would like to use DPI in my resources. (Note: Version of jersey is 2.23.1 and the servlet container is tomcat 8.5.3.)

Therefore I followed the tutorial Chapter 23. Custom Injection and Lifecycle Management in the jersey docs and created a resource, a factory and bind the factory to a class like this:

Resource:

@Path("/

{project}

/catalogs")
public class ProjectsResource

{ @Inject Project project; ... }

Factory:

public class ProjectFactory extends Factory<Project> {

private final Cache cache = cache.getInstance();

@PathParam("project")
private String project;

private HttpServletRequest request;

@Inject
public ProjectFactory(HttpServletRequest request)

{ this.request = request; }

@Override
public Project provide()

{ return cache.get(project, Project.class); }

@Override
public void dispose(Project instance) {}

}
Also I have a feature, which registers an AbstractBinder, which binds my ProjectFactory to my Project class.

@Provider
public class ProjectFeature implements Feature {

@Override
public boolean configure(FeatureContext context) {

context.register(new AbstractBinder() {
@Override
protected void configure()

{ bindFactory(de.moss.ems.rest.factory.ProjectFactory.class) .to(de.moss.ems.entities.catalog.Project.class) .proxy(false) .proxyForSameScope(true) .in(RequestScoped.class); }

);

return true;
}

}
The actually problem is, when I call my Resource everything is fine and i can access my project instance, but in my tomcat catalina logs i am getting the following stacke trace:

22-Jul-2016 16:29:46.510 WARNING [pool-24-thread-1] org.glassfish.jersey.internal.Errors.logErrors The following warnings have been detected: WARNING: HK2 failure has been detected in a code that does not run in an active Jersey Error scope.
WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 3
java.lang.IllegalStateException: Not inside a request scope.
at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:173)
at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:233)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:158)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:765)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getUnqualifiedService(ServiceLocatorImpl.java:772)
at org.jvnet.hk2.internal.IterableProviderImpl.get(IterableProviderImpl.java:111)
at org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory.getContainerRequest(AbstractContainerRequestValueFactory.java:71)
at org.glassfish.jersey.server.internal.inject.PathParamValueFactoryProvider$PathParamValueFactory.provide(PathParamValueFactoryProvider.java:93)
at org.glassfish.jersey.server.internal.inject.ParamInjectionResolver.resolve(ParamInjectionResolver.java:134)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:211)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:234)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:357)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:70)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.jvnet.hk2.internal.FactoryCreator.dispose(FactoryCreator.java:175)
at org.jvnet.hk2.internal.SystemDescriptor.dispose(SystemDescriptor.java:526)
at org.glassfish.jersey.process.internal.RequestScope$Instance.remove(RequestScope.java:532)
at org.glassfish.jersey.process.internal.RequestScope$Instance.release(RequestScope.java:549)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:968)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:922)
at de.moss.ems.rest.resource.AbstractBaseResource.send(AbstractBaseResource.java:118)
at de.moss.ems.rest.resource.AbstractBaseResource.resume(AbstractBaseResource.java:165)
at de.moss.ems.rest.resource.catalog.CatalogsResource.handleGet(CatalogsResource.java:49)
at de.moss.ems.rest.resource.catalog.AbstractCatalogResource.lambda$asyncGetRequest$0(AbstractCatalogResource.java:44)
at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)
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)
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of de.moss.ems.rest.factory.ProjectFactory errors were found
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:246)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:357)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:70)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.jvnet.hk2.internal.FactoryCreator.dispose(FactoryCreator.java:175)
at org.jvnet.hk2.internal.SystemDescriptor.dispose(SystemDescriptor.java:526)
at org.glassfish.jersey.process.internal.RequestScope$Instance.remove(RequestScope.java:532)
at org.glassfish.jersey.process.internal.RequestScope$Instance.release(RequestScope.java:549)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:968)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:922)
at de.moss.ems.rest.resource.AbstractBaseResource.send(AbstractBaseResource.java:118)
at de.moss.ems.rest.resource.AbstractBaseResource.resume(AbstractBaseResource.java:165)
at de.moss.ems.rest.resource.catalog.CatalogsResource.handleGet(CatalogsResource.java:49)
at de.moss.ems.rest.resource.catalog.AbstractCatalogResource.lambda$asyncGetRequest$0(AbstractCatalogResource.java:44)
at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)
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)
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on de.moss.ems.rest.factory.ProjectFactory
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:386)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:70)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.jvnet.hk2.internal.FactoryCreator.dispose(FactoryCreator.java:175)
at org.jvnet.hk2.internal.SystemDescriptor.dispose(SystemDescriptor.java:526)
at org.glassfish.jersey.process.internal.RequestScope$Instance.remove(RequestScope.java:532)
at org.glassfish.jersey.process.internal.RequestScope$Instance.release(RequestScope.java:549)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:968)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:922)
at de.moss.ems.rest.resource.AbstractBaseResource.send(AbstractBaseResource.java:118)
at de.moss.ems.rest.resource.AbstractBaseResource.resume(AbstractBaseResource.java:165)
at de.moss.ems.rest.resource.catalog.CatalogsResource.handleGet(CatalogsResource.java:49)
at de.moss.ems.rest.resource.catalog.AbstractCatalogResource.lambda$asyncGetRequest$0(AbstractCatalogResource.java:44)
at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)
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)
Any ideas how I can solve this warnings?

I also shared this post on stackoverflow:
http://stackoverflow.com/questions/38530282/hk2-failure-has-been-detected-in-a-code-that-does-not-run-in-an-active-jersey-er






[JERSEY-3140] org.glassfish.jersey.server.internal.process.MappableException: org.eclipse.jetty.io.EofException Created: 22/Jul/16  Updated: 22/Jul/16

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

Type: Bug Priority: Major
Reporter: carlspring Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:
  1. mvn --version
    Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
    Maven home: /java/apache/maven-3.3.9
    Java version: 1.8.0_65, vendor: Oracle Corporation
    Java home: /java/jdk1.8.0_65/jre
    Default locale: en_US, platform encoding: UTF-8
    OS name: "linux", version: "4.6.4-2.gcf6e186-default", arch: "amd64", family: "unix"

Jersey version: 2.23



 Description   

I keep seeing this in my logs with no apparent link to any of my code, so its it's hard understand when it's happening:

org.glassfish.jersey.server.internal.process.MappableException: org.eclipse.jetty.io.EofException
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:92)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.filter.LoggingFilter.aroundWriteTo(LoggingFilter.java:313)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
	at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711)
	at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
	at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
	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:305)
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
	at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
	at org.glassfish.jersey.servlet.ServletContainer.serviceImpl(ServletContainer.java:408)
	at org.glassfish.jersey.servlet.ServletContainer.doFilter(ServletContainer.java:583)
	at org.glassfish.jersey.servlet.ServletContainer.doFilter(ServletContainer.java:524)
	at org.glassfish.jersey.servlet.ServletContainer.doFilter(ServletContainer.java:461)
	at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1668)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:215)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:206)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:106)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
	at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1668)
	at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
	at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
	at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
	at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1158)
	at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
	at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
	at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1090)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
	at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
	at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
	at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
	at org.eclipse.jetty.server.Server.handle(Server.java:517)
	at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
	at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
	at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
	at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
	at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
	at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
	at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
	at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
	at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.eclipse.jetty.io.EofException
	at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:197)
	at org.eclipse.jetty.io.WriteFlusher.flush(WriteFlusher.java:419)
	at org.eclipse.jetty.io.WriteFlusher.write(WriteFlusher.java:313)
	at org.eclipse.jetty.io.AbstractEndPoint.write(AbstractEndPoint.java:141)
	at org.eclipse.jetty.server.HttpConnection$SendCallback.process(HttpConnection.java:726)
	at org.eclipse.jetty.util.IteratingCallback.processing(IteratingCallback.java:241)
	at org.eclipse.jetty.util.IteratingCallback.iterate(IteratingCallback.java:224)
	at org.eclipse.jetty.server.HttpConnection.send(HttpConnection.java:509)
	at org.eclipse.jetty.server.HttpChannel.sendResponse(HttpChannel.java:673)
	at org.eclipse.jetty.server.HttpChannel.write(HttpChannel.java:722)
	at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:177)
	at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:163)
	at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:413)
	at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.write(OnCommittedResponseWrapper.java:638)
	at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.write(OnCommittedResponseWrapper.java:638)
	at org.glassfish.jersey.servlet.internal.ResponseWriter$NonCloseableOutputStreamWrapper.write(ResponseWriter.java:325)
	at org.glassfish.jersey.message.internal.CommittingOutputStream.write(CommittingOutputStream.java:229)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$UnCloseableOutputStream.write(WriterInterceptorExecutor.java:299)
	at org.glassfish.jersey.message.internal.ReaderWriter.writeTo(ReaderWriter.java:116)
	at org.glassfish.jersey.message.internal.AbstractMessageReaderWriterProvider.writeTo(AbstractMessageReaderWriterProvider.java:79)
	at org.glassfish.jersey.message.internal.InputStreamProvider.writeTo(InputStreamProvider.java:105)
	at org.glassfish.jersey.message.internal.InputStreamProvider.writeTo(InputStreamProvider.java:60)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
	... 79 more
Caused by: java.io.IOException: Connection reset by peer
	at sun.nio.ch.FileDispatcherImpl.writev0(Native Method)
	at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:51)
	at sun.nio.ch.IOUtil.write(IOUtil.java:148)
	at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:504)
	at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:177)
	... 106 more





[JERSEY-3138] LoggingFeature doesn't increment the sequence number Created: 18/Jul/16  Updated: 19/Jul/16

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

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


 Description   

It's always 1 < or 1 >



 Comments   
Comment by adrianboimvaser [ 18/Jul/16 ]

A new LoggingInterceptor is created for every log entry.

Comment by Pavel Bucek [ 18/Jul/16 ]

Can you please provide reproducible testcase?

I just tested that by modifying HelloWorldTest#testConnection to:

    @Test
    public void testConnection() {
        Invocation.Builder request = target().register(LoggingFeature.class).path(ROOT_PATH).request("text/plain");
        Response response = request.get();
        response = request.get();
        assertEquals(200, response.getStatus());
    }

and it produced

Jul 19, 2016 12:10:35 AM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 19, 2016 12:10:37 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 19, 2016 12:10:37 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
Jul 19, 2016 12:10:38 AM org.glassfish.jersey.logging.LoggingInterceptor log
INFO: 1 * Server has received a request on thread grizzly-http-server-0
1 > GET http://localhost:9998/helloworld
1 > accept: text/plain
1 > accept-encoding: gzip,deflate
1 > connection: Keep-Alive
1 > host: localhost:9998
1 > user-agent: Jersey/2.24-SNAPSHOT (Apache HttpClient 4.5)

Jul 19, 2016 12:10:38 AM org.glassfish.jersey.logging.LoggingInterceptor log
INFO: 1 * Server responded with a response on thread grizzly-http-server-0
1 < 200
1 < Content-Type: text/plain
Hello World!

Jul 19, 2016 12:10:38 AM org.glassfish.jersey.logging.LoggingInterceptor log
INFO: 2 * Server has received a request on thread grizzly-http-server-1
2 > GET http://localhost:9998/helloworld
2 > accept: text/plain
2 > accept-encoding: gzip,deflate
2 > connection: Keep-Alive
2 > host: localhost:9998
2 > user-agent: Jersey/2.24-SNAPSHOT (Apache HttpClient 4.5)

Jul 19, 2016 12:10:38 AM org.glassfish.jersey.logging.LoggingInterceptor log
INFO: 2 * Server responded with a response on thread grizzly-http-server-1
2 < 200
2 < Content-Type: text/plain
Hello World!

Jul 19, 2016 12:10:38 AM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]

which seems to be OK..

Comment by adrianboimvaser [ 19/Jul/16 ]

Happened with client in a multi-threaded environment. Where can I find HelloWorldTest?

Comment by adrianboimvaser [ 19/Jul/16 ]

Should I stop using a shared Client and create a new one for each request in a new thread? That's clearly against the recommendations in the docs:

 * Clients are heavy-weight objects that manage the client-side communication
 * infrastructure. Initialization as well as disposal of a {@code Client} instance
 * may be a rather expensive operation. It is therefore advised to construct only
 * a small number of {@code Client} instances in the application. Client instances
 * must be {@link #close() properly closed} before being disposed to avoid leaking
 * resources.
Comment by Pavel Bucek [ 19/Jul/16 ]

Have I suggested that somewhere? (I don't really see where did you came to a conclusion that not using shared client will resolve the issue. I used it for my testing..).

HelloWorldTest is located in HelloWorld example:

https://github.com/jersey/jersey/blob/master/examples/helloworld/src/test/java/org/glassfish/jersey/examples/helloworld/HelloWorldTest.java

Comment by adrianboimvaser [ 19/Jul/16 ]

No, sorry, I didn't mean to offend you.

Comment by Pavel Bucek [ 19/Jul/16 ]

no need for apologies, nothing happened.

If you could construct reproducible testcase, it would help greatly, since I don't see what you see. I even tried to execute second request in other thread and it still works as expected.

(for the reference:

    @Test
    public void testConnection() throws InterruptedException {
        final Invocation.Builder request = target().register(
                new LoggingFeature(Logger.getAnonymousLogger(), Level.INFO, LoggingFeature.DEFAULT_VERBOSITY,
                                   LoggingFeature.DEFAULT_MAX_ENTITY_SIZE)).path(ROOT_PATH).request("text/plain");
        Response response = request.get();
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread() {
            @Override
            public void run() {
                System.out.println("test!");
                System.out.println("status: " + request.get().getStatus());
                countDownLatch.countDown();
            }
        }.start();

        countDownLatch.await();
        assertEquals(200, response.getStatus());
    }

)





[JERSEY-3135] Use of Accept-Encoding header does not follow HTTP spec Created: 13/Jul/16  Updated: 13/Jul/16

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

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

N/A



 Description   

When an encoder is not registered to a client, Jersey does not add an Accept-Encoding header. But, according to RFC 7231, section 5.3.4 "If no Accept-Encoding field is in the request, any content-coding is considered acceptable by the user agent."

But, clearly, Jersey CANNOT accept any content-coding (unless the proper encoders have been registered with the client).

Therefore, Jersey should specifically exclude "by the Accept-Encoding field stating either "identity;q=0" or "*;q=0" without a more specific entry for "identity"."






[JERSEY-3102] Remove warning for void GET methods Created: 24/Apr/16  Updated: 12/Jul/16

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

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


 Description   

Jersey logs following WARNING for void GET methods:

WARNING: The following warnings have been detected:  HINT: A HTTP GET method, public void SomeResource.get(java.lang.String), returns a void type. It can be intentional and perfectly fine, but it is a little uncommon that GET method returns always "204 No Content".

Is this really necessary? As the message states a 204 can be perfectly fine for a GET method so I wouldn't classify this as WARNING.

The MVC-Specification (JSR-371) defines a @View annotation which can be used for void methods so this warning will confuse a lot of developers.



 Comments   
Comment by yuliyal [ 12/Jul/16 ]

We have also have these messages in our logs.
As far as we can see in org.glassfish.jersey.internal.Errors:

    StringBuilder fatals = new StringBuilder("\n");
    StringBuilder warnings = new StringBuilder();
    StringBuilder hints = new StringBuilder();

    for(final ErrorMessage error: errors) {
        switch (error.getSeverity()) {
            case FATAL:
                isFatal = true;
                fatals.append(LocalizationMessages.ERROR_MSG(error.getMessage())).append('\n');
                break;
            case WARNING:
                warnings.append(LocalizationMessages.WARNING_MSG(error.getMessage())).append('\n');
                break;
            case HINT:
                warnings.append(LocalizationMessages.HINT_MSG(error.getMessage())).append('\n');
                break;
        }
    }

hint messages are added to warnings StringBuilder. Can they be added to hints instead? Then we can set log level of org.glassfish.jersey.internal.Errors to INFO to get rid of them.





[JERSEY-3111] jersey-container-jdk-http ignores host and always binds to wildcard address Created: 07/May/16  Updated: 08/Jul/16

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

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


 Description   

When using the jersey-container-jdk-http to create a HttpServer, the configuration is passed via an URI, from which protocol, port and path is extracted and used.
Yet, it is not possible to bind the server to the localhost/loopback interface. The HttpServer is always bound to the wildcard address via HttpServer.create(new InetSocketAddress(port), 0)

I would prefer to be able to manually bind the HttpServer at a later time, there should be no need to bind the HttpServer at construction. For the constructor, isHttps and path should be sufficient.

If this change is too complicated, it would help to actually use the host part of the URI for the InetSocketAddress



 Comments   
Comment by dmitri.priimak [ 08/Jul/16 ]

Similar issue affects SimpleContainerFactory.create(...) method. And it can be solved easily by changes in method

SimpleContainerFactory#_create(URI, SSLContext, SimpleContainer, UnsafeValue<Server, IOException>)

in line 277 where InetSocketAddress is created ignoring hostname part of the URL.





[JERSEY-3127] jersey-media-json-jackson: Usage of newest Jackson (or at least 2.6.X) Created: 24/Jun/16  Updated: 07/Jul/16

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

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


 Description   

Please use the newest Jackson (2.7.5) or at least Version 2.6.0 for jersey-media-json-jackson. Currently Jackson 2.5.4 is used. TIA!



 Comments   
Comment by VingeF [ 07/Jul/16 ]

This issue with deserialization is fixed in 2.6.4
https://github.com/FasterXML/jackson-databind/issues/1036





[JERSEY-3134] Improve OAuth2-client support by providing design for additional flows. Add client credentials grant workflow Created: 04/Jul/16  Updated: 04/Jul/16

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

Type: Improvement Priority: Major
Reporter: deepakpol Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: client, pull-request, security
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Mac OS X


Tags: oauth2-client, secuirty

 Description   

Jersey as of 2.23.1 only supports authorization code grant flow. The current design cannot be easily extended to implement other flows - client credentials, implicit, password.



 Comments   
Comment by deepakpol [ 04/Jul/16 ]

Created pull request being tracked at https://github.com/jersey/jersey/pull/227





[JERSEY-3093] Improve current implementation of RolesAllowedDynamicFeature to support query of roles on current resource Created: 13/Apr/16  Updated: 04/Jul/16

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

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


 Description   

Hi,

for the current release and as far as I can see also for the upcoming 3.0 release I cannot see a convenient way to access the roles allowed on the current resource

https://github.com/jersey/jersey/blob/2.21.x/core-server/src/main/java/org/glassfish/jersey/server/filter/RolesAllowedDynamicFeature.java

Since the inner class is private, there's no way to override what message is thrown with the ForbiddenException. For example if I want to put the missing role(s) into that message to be more informative for the caller.

For that scenario I would have to copy basically the whole file and always make sure, that my checked in code is still aligned to the current jersey release I'm using.

Another way would be to add another filter per resource, that basically does the same thing as the RolesAllowedDynamicFeature class but store the roles per resource, for example in the SecurityContext for me to use later.

Is there a way you could provide a function for me to retrieve the current resource's roles and act based on what is responded, or even let us change the behaviour, as by design that's not possible without having duplicate, resulting in possibly outdated, code.

Maybe there's even a way to solve this, that I cannot see.



 Comments   
Comment by Pavel Bucek [ 13/Apr/16 ]

Hi Tehcyx,

have you tried register ExceptionMapper for ForbiddenException? That way you can catch it and modify the message or whatever is returned to the client.

See https://jersey.java.net/apidocs/latest/jersey/javax/ws/rs/ext/ExceptionMapper.html

Regards,
Pavel

Comment by tehcyx [ 13/Apr/16 ]

Hi Pavel,

Yes I have, but from within the ExceptionMapper there's no way of accessing the current resources RolesAllowed, right?

Best,
Daniel Roth

Comment by tehcyx [ 04/Jul/16 ]

Hi,

Is there an update regarding this ticket?

Best,
Daniel





[JERSEY-3133] Suppress Warn Log when using a GET method request with a message-body. Created: 02/Jul/16  Updated: 02/Jul/16

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

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


 Description   

I'm troubled by WARN log outputted by JerseyClient when using a GET
method request with a message-body.
The WARN log is outputted by following codes below.
https://github.com/jersey/jersey/blob/master/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L147

HTTP GET methods with a message-body are used by APIs such as
Elasticsearch search API.
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html

The HTTP spec doesn't prevent us from sending a message-body with GET
explicitly.
http://stackoverflow.com/questions/5216567/is-this-statement-correct-http-get-method-always-has-no-message-body

Though these kind of requests are not recommended, I think that
outputting WARN log by every requests is inconvenient because a large
amount of WARN are outputted.



 Comments   
Comment by ken57 [ 02/Jul/16 ]

I think that a warn log of a POST method is unnecessary in the same way.
https://github.com/jersey/jersey/blob/master/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L153





[JERSEY-3132] LoggingFeature breaks JSON content Created: 01/Jul/16  Updated: 01/Jul/16

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

Type: Bug Priority: Major
Reporter: mscheepers Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: client, jdk8, logging
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

win7 64-bit, java 8, jersey client



 Description   

Registered the LoggingFeature for client side request and response logging.
After configuring to perfom logging (setting log level to info, verbosity to PAYLOAD_TEXT) the logged JSON response is missing the first brace and deserialization of the JSON object is not possible (due to the missing brace) on client side.
After changing the log level to finest (which is not logged) or removing the LoggingFeature the deserialization of JSON objects on client side is possible.
This does happen occasionally (84 of 100 tests failed).
The server side transfer encoding is chunked.
This also happens with 2.22.1 and LoggingFilter.






[JERSEY-2933] ClassCastException with SelectableEntityFilteringFeature Created: 05/Aug/15  Updated: 30/Jun/16

Status: Reopened
Project: jersey
Component/s: extensions
Affects Version/s: 2.19
Fix Version/s: None

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

Glassfish 4.1


Attachments: Zip Archive jersey-selectable-filtering-master.zip    
Issue Links:
Duplicate
is duplicated by JERSEY-2932 ClassCastException with SelectableEnt... Resolved
Sprint: Triaged

 Description   

When registering org.glassfish.jersey.message.filtering.SelectableEntityFilteringFeature to select fields to be marshalled in the response, objects with nested List fields (I suppose) throw a ClassCastException.

java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
	at org.glassfish.jersey.message.filtering.spi.FilteringHelper._getEntityClass(FilteringHelper.java:140)
	at org.glassfish.jersey.message.filtering.spi.FilteringHelper.getEntityClass(FilteringHelper.java:98)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspectEntityProperties(EntityInspectorImpl.java:163)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:103)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:89)
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:83)
	at org.glassfish.jersey.moxy.json.internal.FilteringMoxyJsonProvider.preWriteTo(FilteringMoxyJsonProvider.java:80)
	at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:941)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1128)
	at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:677)
	at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
	at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:311)
	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:291)
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
	at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
	at java.lang.Thread.run(Thread.java:745)


 Comments   
Comment by heruan [ 05/Aug/15 ]

Here's the application code:

Application.java
package org.example;

import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.message.filtering.SelectableEntityFilteringFeature;
import org.glassfish.jersey.server.ResourceConfig;

@ApplicationPath("/api")
public class Application extends ResourceConfig {
    public Application() {
        this.packages("org.example.resource");
        this.register(SelectableEntityFilteringFeature.class);
        this.property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "fields");
    }
}
HostResource.java
package org.example.resource;

import org.example.entity.Host;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hosts")
public class HostResource {
    @PersistenceContext
    EntityManager em;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Host> get() {
        return em.createNamedQuery("Host.findAll").getResultList();
    }
}
Host.java
package org.example.entity;

import java.util.List;

public class Host {
    long id;
    String host;
    List<Interface> interfaces;

    // getters and setters
}
Interface.java
package org.example.entity;

import java.util.List;

public class Interface {
    long id;
    boolean main;
    int type;
    String ip;
    String dns;
    List<Item> items;

    // getters and setters
}
Item.java
package org.example.entity;

import java.util.List;

public class Item {
    long id;
    String name;
    String key;
    List<Function> functions;

    // getters and setters
}
Function.java
package org.example.entity;

import java.util.List;

public class Function {
    long id;
    String function;
    Trigger trigger;

    // getters and setters
}
Trigger.java
package org.example.entity;

import java.util.List;

public class Trigger {
    long id;
    String expression;
    String description;
    int status;

    // getters and setters
}

And this is an unfiltered JSON response:

{
  "host": "10.26.5.158",
  "id": 12345,
  "interfaces": [
    {
      "dns": "",
      "id": 2615,
      "ip": "10.26.5.158",
      "items": [
        {
          "functions": [
            {
              "function": "max",
              "id": 32002,
              "trigger": {
                "description": "{HOST.NAME} is unavailable by ICMP",
                "expression": "{32002}=0",
                "id": 24961,
                "status": 0
              }
            }
          ],
          "id": 67019,
          "key": "icmpping",
          "name": "ICMP ping"
        },
        {
          "functions": [
            {
              "function": "min",
              "id": 24613,
              "trigger": {
                "description": "Ping loss is too high on {HOST.NAME}",
                "expression": "{24613}>20",
                "id": 24962,
                "status": 0
              }
            }
          ],
          "id": 67020,
          "key": "icmppingloss",
          "name": "ICMP loss"
        },
        {
          "functions": [
            {
              "function": "avg",
              "id": 46426,
              "trigger": {
                "description": "Response time is too high on {HOST.NAME}",
                "expression": "({TRIGGER.VALUE}=0&{46426}>0.5)|({TRIGGER.VALUE}=1&{46426}>0.25)",
                "id": 24963,
                "status": 0
              }
            }
          ],
          "id": 67021,
          "key": "icmppingsec",
          "name": "ICMP response time"
        }
      ],
      "main": true,
      "type": 2
    }
  ]
}

The exception reported is thrown on the first request with or without the query fields parameter, when the feature is registered; all is well when the feature isn't registered.

Comment by Adam Lindenthal [ 12/Aug/15 ]

Hi and thanks for creating the issue.
I just spent some time trying to reproduce the problem with no success.
Would you mind sharing a complete minimalistic ready-to-go app? E.g. maven-buildable and -runnable demo app or test case.

I just tried the selectable entity filtering feature with jackson using the code you provided (with minimal changes - I didn't want to configure the persistence, so I changed the querying the entity manager into returning sample test object right from the resource, but I left the rest of your code intact) and everything worked with the feature off and on, with or without the fields parameter.

it would be very helpful, if you could minimize your usecase into something standalone and share it with us.

Thanks,
Adam

Comment by Marek Potociar [ 03/Sep/15 ]

Closing as incomplete - no response from the filer.

Comment by heruan [ 07/Oct/15 ]

Sorry for the delay, it was not simple to reproduce the problem in a ready-to-go app since I've found the issue arises only when injection occurs in the resource (e.g. the EntityManager with @PersistenceContext, but also injecting a DAO with @Inject where the DAO has on its side an EntityManager injected with @PersistenceContext). I think this is why Adam couldn't reproduce the problem, since he didn't configure persistence.

I'm using MOXy and EclipseLink 2.6.

(Should I open a new bug or this can be reopened? Thank you!)

Comment by heruan [ 07/Oct/15 ]

Here's the ready-to-go app https://github.com/heruan/jersey-selectable-filtering which breaks when deployed.

Comment by heruan [ 06/Nov/15 ]

Did anyone besides me successfully replicated this?

Comment by csolem [ 26/Nov/15 ]

I'm seeing a similar stack trace in my application with Jersey Entity Filtering. It appears on the first request only. Jersey is not configured with the SelectableEntityFilteringFeature, but with the EntityFilteringFeature.

The application is built using spring boot (1.3.0.RELEASE), spring-boot-starter-data-jpa, jackson (not Moxy) and jersey-entity-filtering (2.22.1).

java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
	at org.glassfish.jersey.message.filtering.spi.FilteringHelper._getEntityClass(FilteringHelper.java:140) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.spi.FilteringHelper.getEntityClass(FilteringHelper.java:98) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.spi.AbstractEntityProcessor.process(AbstractEntityProcessor.java:89) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityFilteringProcessor.process(EntityFilteringProcessor.java:76) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspectStandaloneAccessors(EntityInspectorImpl.java:204) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:106) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:91) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:85) ~[jersey-entity-filtering-2.22.1.jar:na]
	at org.glassfish.jersey.jackson.internal.FilteringJacksonJaxbJsonProvider.writeTo(FilteringJacksonJaxbJsonProvider.java:130) ~[jersey-media-json-jackson-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.internal.Errors.process(Errors.java:267) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) ~[jersey-common-2.22.1.jar:na]
	at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) ~[jersey-server-2.22.1.jar:na]
	at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471) ~[jersey-container-servlet-core-2.22.1.jar:na]
	at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425) ~[jersey-container-servlet-core-2.22.1.jar:na]
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383) ~[jersey-container-servlet-core-2.22.1.jar:na]
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336) ~[jersey-container-servlet-core-2.22.1.jar:na]
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223) ~[jersey-container-servlet-core-2.22.1.jar:na]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217) ~[tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.28.jar:8.0.28]
	at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Comment by Marek Potociar [ 25/Jan/16 ]

Reducing issue priority, which means that we may not be fixing this soon, depending on available resources.

Comment by mamghari [ 17/Feb/16 ]

Hi,

Please reopen the issue. The SelectableEntityFiltering introduce some issues even when the "select" query param is not specified!

From my point of view, the filtering should be activated only when the "select" query param is specified in the URL. Furthermore, the serialization of collections is not well working when the filtering is activated. I mean I got a lot of JsonMappingExceptionMapper. What I understand is that the filtering is applied when sending the payload to the client, during the serialization. I am using Jersey 2.22.1 + Jackson.

ERROR JsonMappingExceptionMapper:29 [http-bio-8080-exec-3] Malformed Json!
com.fasterxml.jackson.databind.JsonMappingException: Can not resolve PropertyFilter with id 'java.util.HashMap'; no FilterProvider configured

The work around I found is http://stackoverflow.com/questions/35437298/jersey-jackson-data-entity-filtering-jsonmappingexception-on-collection
But it works only if the root object is a Collection, not when it is included in a Pojo.

The new issue I got today is the following one when executing Cucumber tests:

java.lang.RuntimeException: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
at org.glassfish.jersey.jetty.JettyHttpContainer.handle(JettyHttpContainer.java:197)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:459)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:281)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232)
at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
at org.glassfish.jersey.message.filtering.spi.FilteringHelper._getEntityClass(FilteringHelper.java:140)
at org.glassfish.jersey.message.filtering.spi.FilteringHelper.getEntityClass(FilteringHelper.java:98)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspectEntityProperties(EntityInspectorImpl.java:163)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:103)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:91)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:85)
at org.glassfish.jersey.jackson.internal.FilteringJacksonJaxbJsonProvider.writeTo(FilteringJacksonJaxbJsonProvider.java:130)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)

Thank you very much to help and to fix this issue,
Mohamed

Comment by mamghari [ 22/Feb/16 ]

Hi,

Do you have any news regarding this issue ?

Thank you

Comment by ftaleman [ 25/Apr/16 ]

Hi,

Getting this for every one of our requests that is serializing a JPA entity from the moment the SelectableEntityFilteringFeature or EntityFilteringFeature is enabled.

On Glassfish 4.1.1

property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "select");
register(SelectableEntityFilteringFeature.class);

Stack trace:

Severe: Exception: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
at org.glassfish.jersey.message.filtering.spi.FilteringHelper._getEntityClass(FilteringHelper.java:140)
at org.glassfish.jersey.message.filtering.spi.FilteringHelper.getEntityClass(FilteringHelper.java:98)
at org.glassfish.jersey.message.filtering.spi.AbstractEntityProcessor.process(AbstractEntityProcessor.java:89)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspectStandaloneAccessors(EntityInspectorImpl.java:204)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:106)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
at org.glassfish.jersey.message.filtering.EntityInspectorImpl.inspect(EntityInspectorImpl.java:110)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:91)
at org.glassfish.jersey.message.filtering.spi.AbstractObjectProvider.getFilteringObject(AbstractObjectProvider.java:85)
at org.glassfish.jersey.moxy.json.internal.FilteringMoxyJsonProvider.preWriteTo(FilteringMoxyJsonProvider.java:80)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
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:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)

Is there a way to work around this error?

Thanks in advance!

Best regards
Frederik

Comment by dansiviter [ 29/Jun/16 ]

Filtering is basically not fit for purpose as no Collection types can be serialised. Any update on when a fix will be available? FYI this affects 2.23.1 also including both 2.5.4 and 2.7.5 versions of Jackson.

Comment by dansiviter [ 30/Jun/16 ]

Here's a test that throws com.fasterxml.jackson.databind.JsonMappingException: Can not resolve PropertyFilter with id 'java.util.Map'; no FilterProvider configured:

public class EntityFilteringTest extends JerseyTest {
	private static final GenericType<Map<String, String>> STRING_MAP = new GenericType<Map<String, String>>() { };

	@Override
	protected Application configure() {
		return new ResourceConfig(
				Resource.class,
				EntityFilteringFeature.class,
				JacksonFeature.class)
			.property(
				ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
	}

	@Override
	protected DeploymentContext configureDeployment() {
		SLF4JBridgeHandler.uninstall();
		SLF4JBridgeHandler.install();

		enable(TestProperties.LOG_TRAFFIC);
		enable(TestProperties.DUMP_ENTITY);
		set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
		return super.configureDeployment();
	}

	@Test
	public void get() {
		final Map<String, String> response = target().request().get(STRING_MAP);
		assertEquals(1,  response.size());
		assertEquals("World!", response.get("Hello"));
	}


	// --- Inner Classes ---

	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	public static class Resource {
		@GET
		public Map<String, String> get() {
			return Collections.singletonMap("Hello", "World!");
		}
	}
}

I've tried List and Set and primitives and they're OK, it just seems to be Maps and implementations of.

Update: digging further, it appears Collection types do not perform BasicSerializerFactory#findFilterId where Map types do. As FilteringJacksonJaxbJsonProvider[line:112] returns the AnnotatedClass#getName (even though it's not annotated with a filter). I question if this is valid.





[JERSEY-3125] AsyncContext.complete() called multiple times when using @Suspend and AsyncResponse Created: 21/Jun/16  Updated: 28/Jun/16

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

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


 Description   

We’ve run into a bug with @Suspend and AsyncResponse in Jersey. It seems that in some cases the underlying response is resumed multiple times, which causes problems for servers like Jetty which recycle response objects. Please see the test case (https://github.com/cberner/presto/blob/jetty_ise/presto-tests/src/main/java/com/facebook/presto/tests/TestJettyISE.java) which results in the following error, and often a 500 being returned to the client, after running for a few minutes:

2016-06-22 00:13:50 WARNING Attempt to release request processing resources has failed for a request.
java.lang.IllegalStateException: AsyncContext completed and/or Request lifecycle recycled
at org.eclipse.jetty.server.AsyncContextState.state(AsyncContextState.java:54)
at org.eclipse.jetty.server.AsyncContextState.complete(AsyncContextState.java:99)
at org.glassfish.jersey.servlet.async.AsyncContextDelegateProviderImpl$ExtensionImpl.complete(AsyncContextDelegateProviderImpl.java:125)
at org.glassfish.jersey.servlet.internal.ResponseWriter.commit(ResponseWriter.java:197)
at org.glassfish.jersey.server.ContainerResponse.close(ContainerResponse.java:413)
at org.glassfish.jersey.server.ServerRuntime$Responder.release(ServerRuntime.java:810)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:435)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder$3.run(ServerRuntime.java:934)
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$AsyncResponder.resume(ServerRuntime.java:966)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.resume(ServerRuntime.java:922)
at com.facebook.presto.tests.TestJettyISE$MyTestResource.lambda$getResults$0(TestJettyISE.java:144)
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 csliu.java [ 27/Jun/16 ]

This blocks us to expand Presto cluster to a reasonable size, can someone help to take a look? Thanks a lot.

Thanks,
Changshu

Comment by Pavel Bucek [ 28/Jun/16 ]

Hi Changshu,

have you seen this in previous versions? (I mean, is this something which happened because of Jersey update or is this new functionality on your side?)

Regards,
Pavel

Comment by Pavel Bucek [ 28/Jun/16 ]

+ could you please provide minimal reproducer? (I don't want to checkout and build "presto")





[JERSEY-3129] JspTemplateProcessor should support *.jspx extension. Created: 28/Jun/16  Updated: 28/Jun/16

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

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


 Description   

*.jspx is a common extension for XML compliant variation of the JSP files. The JspTemplateProcessor should support it together with *.jsp.

Extremely simple fix is possible:

@Inject
public JspTemplateProcessor(final Configuration config, final ServletContext servletContext) {
    super(config, servletContext, "jsp", "jsp");
}

should be replaced with:

@Inject
public JspTemplateProcessor(final Configuration config, final ServletContext servletContext) {
    super(config, servletContext, "jsp", "jsp", "jspx");
}





[JERSEY-3054] Memory-leak after jersey upgrade from 2.17 to 2.22.1 Created: 10/Feb/16  Updated: 27/Jun/16

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

Type: Bug Priority: Critical
Reporter: bruge Assignee: Unassigned
Resolution: Unresolved Votes: 2
Labels: memory-leak
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)



 Description   

After upgrading Jersey from 2.17 to 2.22.1 we have been observing a memory leak in our application that forces us to restart the production servers regularly. After inspecting a heap dump we found out so far, that the hk2 library might be the problem for that (see attached files).



 Comments   
Comment by bruge [ 10/Feb/16 ]

Since i can't attach files, I have to provide links instead:
http://pltzchn.de/heapdump1.png
http://pltzchn.de/heapdump2.png

Comment by bruge [ 14/Mar/16 ]

After the upgrade to 2.22.2 the problem became even worse.
http://pltzchn.de/heap_usage_after_upgrade_720.png

Comment by svileng [ 19/Apr/16 ]

We are currently looking into migrating jersey 1 (1.16) to jersey 2 (2.22.2), but all those memory leaks in the past (e.g. JERSEY-2830) and now this very new issue got us worried.

So we tried running soak tests with migrated to jersey 2 test build of our project... In general it looks fine, but from time to time the memory dump analyzed by MAT shows the following:

Problem Suspect 2

101 instances of "org.jvnet.hk2.internal.ServiceLocatorImpl", loaded by "org.glassfish.hk2.locator" occupy 43,127,760 (19.16%) bytes.

Biggest instances:

org.jvnet.hk2.internal.ServiceLocatorImpl @ 0xe1fd4a80 - 12,772,592 (5.67%) bytes.

Keywords
org.jvnet.hk2.internal.ServiceLocatorImpl
org.glassfish.hk2.locator

While there weren't actual OOME (or similar Errors) this is very troubling and we are unsure now whether we can trust Jersey 2 or if it going to blow into our face in production.

Is there a memory leak in jersey client or is it just that we are not using the client properly? Are you safe from memory leaks if using jersey 2? No one seems to be able (or is willing to) to answer those questions directly.

Comment by bruge [ 19/Apr/16 ]

In our case it's just one instance of "org.jvnet.hk2.internal.ServiceLocatorImpl", loaded by "org.springframework.boot.loader.LaunchedUrlClassLoader".
Looking into the dominator tree tells us, that the memory is accumulated in a single WeakHashMap instance holding >16k nodes (which is seemingly a highly rated candidate for potential memory leaks) located in PerLocatorUtilities.

With 2.22.1 our servers need around 12 days to run into an OOM under normal load, which is quite a long time. Upgrading to 2.22.2 shortened the duration to 3-4 days.

Comment by svileng [ 19/Apr/16 ]

Do you observe this on the client or on the server?
We are using not only jersey server but also jersey client extensively as well in our application.
In the past there were reported Memory leaks in the client i believe, related to HK2 which jersey uses, which prevented us from switching to jersey 2 back then.
But according to you now there is possible a leak in the server (as well as in the client)?!

Comment by bruge [ 19/Apr/16 ]

We are using Jersey only as server.

Comment by svileng [ 19/Apr/16 ]

This is really bad news then. I was looking for/expecting Memory leak on the client only...

Btw, i guess you can link JERSEY-2830 and JERSEY-2463 to this if you like.

Also, I am currently playing with the attached to JERSEY-2463 (jersey-2463.zip) simple test application. it is very easy to run and it is supposed to reveal memory leak. You can try it out yourself...

Comment by svileng [ 03/May/16 ]

After running our soak tests for 8 days ServiceLocatorImpl shows as a memory leak suspect:

One instance of "org.jvnet.hk2.internal.ServiceLocatorImpl" loaded by "org.glassfish.hk2.locator" occupies 33 979 816 (20,14%) bytes. The memory is accumulated in one instance of "java.util.HashMap$Node[]" loaded by "<system class loader>".

Keywords
org.jvnet.hk2.internal.ServiceLocatorImpl
org.glassfish.hk2.locator
java.util.HashMap$Node[]

path2gc of ServiceLocatorImpl instance:

Class Name | Shallow Heap | Retained Heap
---------------------------------------------------------------------------------------------------------------------------------------------
org.jvnet.hk2.internal.ServiceLocatorImpl @ 0xe1f9dac0 | 136 | 33 979 816
'- locator org.glassfish.jersey.server.ApplicationHandler @ 0xe1f9db60 | 40 | 3 024 920
'- containerListener org.glassfish.jersey.servlet.ServletContainer @ 0xe1de4bf8 | 48 | 1 128
'- filter org.apache.catalina.core.ApplicationFilterConfig @ 0xe1de4c28 | 32 | 1 160
'- value java.util.HashMap$Node @ 0xe275d278 | 32 | 32
'- [11] java.util.HashMap$Node[16] @ 0xe1e1fab8 | 80 | 240
'- table java.util.HashMap @ 0xe1de4c90 | 48 | 288
'- filterConfigs org.eclipse.gemini.web.tomcat.internal.ExtendedStandardContext @ 0xe1d05130| 544 | 242 528
'- value java.util.Hashtable$Entry @ 0xe1f5db28 | 32 | 32
'- [37] java.util.Hashtable$Entry[47] @ 0xe2ef1780 | 208 | 848
'- table java.util.Hashtable @ 0xe1f5daf8 | 48 | 896
---------------------------------------------------------------------------------------------------------------------------------------------

More info:

Accumulated Objects by Class in Dominator Tree

Label | Number of Objects | Used Heap Size |Retained Heap Size
java.util.HashMap$Node | 115 666 | 3 701 312 | 32 489 696
First 10 of 115 666 objects

Accumulated Objects in Dominator Tree

Class Name | Shallow Heap | Retained Heap | Percentage
org.jvnet.hk2.internal.ServiceLocatorImpl @ 0xe1f9dac0
136 | 33 979 816 | 20,14%
\org.jvnet.hk2.internal.PerLocatorUtilities @ 0xe1fe2bf8
32 | 33 635 304 | 19,94%
.\org.jvnet.hk2.internal.PerLocatorUtilities$1 @ 0xe1fe2c18
32 | 33 538 488 | 19,88%
..\java.util.HashMap @ 0xe1fe2cb0
48 | 33 538 336 | 19,88%
...\java.util.HashMap$Node[262144] @ 0xe579dfe8
1 048 592 | 33 538 288 | 19,88%

Comment by svileng [ 12/May/16 ]

This issue has been around for several months now and yet there isn't any kind of statement from the Jersey team.
So many questions left unanswered, has anyone on the Jersey team even noticed this issue?

Another thing that would really surprise me is if it really is just the two of us experiencing the memory leak? Jersey is supposed to be one of the most popular REST frameworks out there.
Could it be that everyone is using a Jersey 2 + HK2 version that does not have the leak? Or is the leak caused by improper usage of Jersey 2 , although I can't really see how this is possible especially on the server side.
Can we hope that the next version of HK2 (2.5.0?) could possibly solve the memory leak? Or is it the usage of HK2 by Jersey 2 where in lies the problem?

Comment by bruge [ 08/Jun/16 ]

Digged a bit deeper into this and there is one thing I don't get. There is this Hk2ThreadLocal construct which holds an hashmap using the ids of accessing threads as keys. I only see this hashmap growing but I never see an entry is actually removed for example if a thread dies. This is the issue causing the leak as you can see in this picture, where the map holds >16k nodes. http://pltzchn.de/heapdump2.png

I'm not really into those things, but might this be a lifecycle problem caused by the spring bridge?
Can anybody (dis-)prove this behavior?

PS: With 2.23 the problem is like in 2.22.2, even worse.

Comment by bruge [ 20/Jun/16 ]

One last thing: Downgrading to 2.20 seems to "solve" the issues, at least there is no sign for a leak after several days in production.

Comment by svileng [ 20/Jun/16 ]

This is very good to know bruge, thank you.
We are currently using 2.22.2 in OSGi runtime Equinox i.e. as opposed to the Spring runtime you are running. That being said looking at the dominator tree I posted previously and your heap screenshot it looks like exactly the same Class hierarchy.

Comment by mikksoone [ 27/Jun/16 ]

Same here:

One instance of "org.jvnet.hk2.internal.ServiceLocatorImpl" loaded by "org.springframework.boot.loader.LaunchedURLClassLoader @ 0xc0009c18" occupies 640,052,512 (79.74%) bytes. The memory is accumulated in one instance of "org.jvnet.hk2.internal.ServiceLocatorImpl" loaded by "org.springframework.boot.loader.LaunchedURLClassLoader @ 0xc0009c18".

Upgraded old spring application to use spring-boot with spring-boot-starter-jersey that uses jersey 2.22 by default and hit this leak.

Luckily downgrading to 2.20 worked, thank you bruge.





[JERSEY-3128] encoding bug in jersey-mvc Created: 26/Jun/16  Updated: 26/Jun/16

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

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

windows7,java



 Description   

missing parameter "encoding" in servletContext and classloader. show as below:

// ServletContext.
if (servletContext != null)

{ //"The path must begin with a "/"". final String path = template.startsWith("/") ? template : "/" + template; final InputStream stream = servletContext.getResourceAsStream(path); reader = stream != null ? new InputStreamReader(stream) : null; }

// Classloader.
if (reader == null) {
InputStream stream = getClass().getResourceAsStream(template);
if (stream == null)

{ stream = getClass().getClassLoader().getResourceAsStream(template); }

reader = stream != null ? new InputStreamReader(stream) : null;
}

// File-system path.
if (reader == null) {
try

{ reader = new InputStreamReader(new FileInputStream(template), encoding); }

catch (final FileNotFoundException fnfe)

{ // NOOP. }

}






[JERSEY-3108] Allow apache connector to specify dns resolver. Created: 04/May/16  Updated: 20/Jun/16

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

Type: New Feature Priority: Minor
Reporter: acidaris Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Apache HttpClient has the ability to specify a DNS resolver, but it must be specified as part of the construction of the ConnectionManager.

Allowing for the DNS Resolver to be defined on it's own can make use of the existing code within ApacheConnector.createConnectionManager() which ensures the correct configuration of the ConnectionManager.






[JERSEY-3008] Combination of ContainerResponseFilter and SSE EventOutput/OutboundEvent Created: 21/Nov/15  Updated: 20/Jun/16

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

Type: Bug Priority: Major
Reporter: brcolow Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: pull-request
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Sprint: Triaged

 Description   

Here's the scenario that will illustrate the general problem:

We want to allow a user to "link" his website account with a mobile device. To do so, user logs in to website account and requests QR code. User scans QR code on mobile device. On doing so, the Jersey server is notified thusly:

    @POST
    @Path("/notify-linked")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response broadcastAccountLinked(ObjectNode accountLinkedJson)
    {
        // if QR code matches ...

        OutboundEvent event = new OutboundEvent.Builder().name("message")
                .mediaType(MediaType.APPLICATION_JSON_TYPE)
                .data(ObjectNode.class, new ObjectNode(JsonNodeFactory.instance).put("userId", user.getId())).build();

        broadcaster.broadcast(event);

        return Response.ok(new ObjectNode(JsonNodeFactory.instance).put("success", true)).build();
    }

This informs the Jersey server of a successful linkage, which is then broadcasted via server sent events (SSE) thusly:

    @GET
    @CORS
    @Path("/link-events")
    @Produces(SseFeature.SERVER_SENT_EVENTS)
    public EventOutput listenToAccountLinkedBroadcasts()
    {
        final EventOutput eventOutput = new EventOutput();
        broadcaster.add(eventOutput);
        return eventOutput;
    }

The website which provided the initial QR code is listening to these events (via a javascript EventSource pointed at the /link-events resource). You will notice the above method is annotated with a @CORS annotation. This is a ContainerResponseFilter that adds an "Access-Control-Allow-Origin" header so that the above scenario is possible (as the Jersey server runs on say port 4633 but the website runs on port 80. Without this header, the browser will report an error and the EventSource can't be constructed.

All of this would be fine if the @CORS annotated method actually added the header to the /link-events resource, but so far I have had no luck in getting it to do so.

Here is the response filter:

@CORS
public class CORSResponseFilter implements ContainerResponseFilter
{
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

The CORS interface:

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface CORS
{

}

I have also tried using a dynamic binding instead of a static one but no luck. I should mention that in the same project I have a working filter that uses the above method (e.g. static binding).

tl;dr: How can one add a ContainerResponseFIlter on an SSE resource?

Thanks!



 Comments   
Comment by brcolow [ 21/Nov/15 ]

The formatting came out absolutely horribly...trying to find the edit button...

Comment by brcolow [ 22/Nov/15 ]

Thank you very much Pavel Bucek for formatting it. Much appreciated!

Comment by brcolow [ 14/Jan/16 ]

Is there anything I can personally do to make progress on this issue? It is a major blocker for me and I do not know any workarounds. Thanks.

Comment by Stepan Vavra [ 25/Jan/16 ]

Hi, we're planning on looking at this.
Unfortunately, we're short on resources so if you had time to find the cause of the problem, fix it and submit a pull request on Github it would definitely help!

Thanks!
Stepan

Comment by sclemens [ 21/Mar/16 ]

Hi brcolow, did you make some progress on this? Just ran into the same problem.

Comment by sclemens [ 22/Apr/16 ]

Hey guys, happy to pay for a proper fix. Anyone interested? Please reply to zgwcuqra@trashmail.com

Comment by sclemens [ 28/Apr/16 ]

Really? No one?

Comment by brcolow [ 08/May/16 ]

I looked at the Jersey source a bit but unfortunately it is very complex. I would be really happy even with a workaround. To simplify the problem further, is there a way to add a "custom" header to a server-sent event?

Comment by sclemens [ 14/May/16 ]

Thanks brcolow. Seems that there is no great need for fixing this asap.

Comment by brcolow [ 23/May/16 ]

I was able to put together a pull request (https://github.com/jersey/jersey/pull/223) as an attempt at fixing this issue.





[JERSEY-3123] RolesAllowedDynamicFeature should return 401 when user can not be authenticated Created: 17/Jun/16  Updated: 17/Jun/16

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

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


 Description   

It was fixed before (see https://java.net/jira/browse/JERSEY-2818) but now again RolesAllowedDynamicFeature throws only 403 which breaks some basic functionality.






[JERSEY-3121] Can't inject generic type by HK2 to CDI Created: 09/Jun/16  Updated: 09/Jun/16

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

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

Running WLS 12.2.1.



 Description   

Let's say I have

    @Contract
    public class MyContract<T>

    @Service
    public class MyService implements MyContract<String>

I'm trying to make this injectable by HK2 into CDI using Hk2CustomBoundTypesProvider.

The CDI bean has

    @Inject
    MyContract<String> beanByHk2;

In the custom bound types provider, if I do something like

    @Override
    public Set<Type> getHk2Types() {
        Set<Type> set = new HashSet<>();
        set.add(MyContract.class);
        return set;
    }

I get

org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type MyContract<String> with qualifiers @Default

This is probably fine. But if I do something like

    @Override
    public Set<Type> getHk2Types() {
        Set<Type> set = new HashSet<>();
        set.add(new ParameterizedTypeImpl(MyContract.class, String.class));
        return set;
    }

I get

java.lang.ClassCastException: org.jboss.weld.util.reflection.ParameterizedTypeImpl cannot be cast to java.lang.Class
at org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider$Hk2Bean.getBeanClass(CdiComponentProvider.java:951)
at org.jboss.weld.bootstrap.events.AfterBeanDiscoveryImpl.validateBean(AfterBeanDiscoveryImpl.java:98)
at org.jboss.weld.bootstrap.events.AfterBeanDiscoveryImpl.addBean(AfterBeanDiscoveryImpl.java:81)
at org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.afterDiscoveryObserver(CdiComponentProvider.java:753)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
at org.jboss.weld.injection.MethodInvocationStrategy$SimpleMethodInvocationStrategy.invoke(MethodInvocationStrategy.java:129)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:306)
at org.jboss.weld.event.ExtensionObserverMethodImpl.sendEvent(ExtensionObserverMethodImpl.java:121)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:284)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:262)
at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:271)
at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:260)
at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:154)
at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:148)
at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:54)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:42)
at org.jboss.weld.bootstrap.events.AfterBeanDiscoveryImpl.fire(AfterBeanDiscoveryImpl.java:61)
at org.jboss.weld.bootstrap.WeldStartup.deployBeans(WeldStartup.java:420)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:83)
at com.oracle.injection.provider.weld.WeldInjectionContainer.deploy(WeldInjectionContainer.java:143)
at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:66)
at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:41)
at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:39)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:753)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:263)
at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:67)
at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:601)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:171)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:121)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:343)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:895)
at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1422)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:454)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:181)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:643)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)

I think this is the bug here. The getHk2Types returns Set<Type>, but the returned members seem to be cast to Class, failing to accept any other Type implementations.






[JERSEY-3118] JdkHttpServerFactory always binds server to 0.0.0.0 Created: 02/Jun/16  Updated: 02/Jun/16

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

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

Any



 Description   

Observed:
The JdkHttpServerFactory ignores the host name/IP address in the provided URI and constructs an HttpServer instance which is always bound to "0.0.0.0". We have a use case where this is not acceptable, however, the API provides no way to customize this behavior.

Expected:
The JdkHttpServerFactory should respect the host name/IP address in the provided URI and bind the constructed HttpServer instance accordingly.






[JERSEY-3004] Response is validated by JAXB (MOXy) Created: 13/Nov/15  Updated: 02/Jun/16

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

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

Glassfish 4.1.1


Sprint: Triaged

 Description   

For convenience, I'm using the same representation for both requests and response, and only validating request parameters. E.g.:

@XmlRootElement
public class MyEntity {

	@XmlElement
	@Null
	public Integer id;
	
	@XmlElement
	@NotNull
	public String name;
}
@Produces(MediaType.APPLICATION_JSON)
public class MyEntityResource {

	@POST
	public MyEntity post(@Valid MyEntity req) {
		// story entity
		MyEntity resp = new MyEntity();
		resp.name = req.name;
		resp.id = newId;
		return resp;
	}
}

If I understand section 7.3 of JSR 339 correctly, the response entity shouldn't be validated in this case as the method is not annotated @Valid. And indeed this used to work fine, but now EclipseLink 2.6 has introduced Bean Validation support in MOXy, which is automatically enabled. Now I get the following exception when trying to return an entity with a not-null ID:

javax.validation.ConstraintViolationException
	at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:383)
	at org.eclipse.persistence.jaxb.JAXBBeanValidator.validate(JAXBBeanValidator.java:273)
	at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:588)
	at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
	at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
	at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
	at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
	at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
	at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
	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:292)
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
	at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
	at java.lang.Thread.run(Thread.java:745)

As a workaround I've disabled MOXy's bean validation feature thus:

try {
	Class<?> beanValidationMode = Class.forName("org.eclipse.persistence.jaxb.BeanValidationMode");

	register(new MoxyJsonConfig()
			.property("eclipselink.beanvalidation.mode", beanValidationMode.getField("NONE").get(null))
			.resolver());
} catch (ReflectiveOperationException e) {
}





[JERSEY-3005] javax.ws.rs.client.ResponseProcessingException is never thrown. Created: 18/Nov/15  Updated: 02/Jun/16

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

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

Issue Links:
Duplicate
is duplicated by JERSEY-2468 javax.ws.rs.client.ResponseProcessing... Resolved
Sprint: Triaged

 Description   

My analysis so far is as following:
AbstractRootElementJaxbProvider throws subclasses of WebApplicationException instead of an IOException:
https://jersey.java.net/project-info/2.22.1/jersey/project/jersey-media-jaxb/xref/org/glassfish/jersey/jaxb/internal/AbstractRootElementJaxbProvider.html

At least in the latest version this handled somewhat in JerseyInvocation, where WebApplicationException gets catched and wrapped by a ResponseProcessingException.

https://github.com/jersey/jersey/blob/master/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L858

This is wakwards since the nested exception provides a wrong HTTP status code (eg. "HTTP 400 Bad Request", where the request itself was succesful.

In the end the nested WebApplicationException gets unwrapped again:
https://github.com/jersey/jersey/blob/master/core-client/src/main/java/org/glassfish/jersey/client/JerseyInvocation.java#L690

So I think the best thing would be if the AbstractRootElementJaxbProvider class would throw IOException.

The case of a thrown WebApplicationException should never arise when calling response.readEntity (translate method). So the catch clause should be removed and it should be made sure this case never arises (otherwise it would still be catched by the Exception catch statement).

The unwrapping of the cause of the ProcessingException in the translate method also seems wrong in some cases (e.g. when there is no cause). Why not just set the ProcessingException itself as cause?

The IllegalStateException is not handled specially while ProcessingException is. Seems inconsistent.

And last but not least the WebApplicationException should not be unwrapped in the invoke method. Again, I think WebApplicationException should never be the cause of a ProcessingException anyway.



 Comments   
Comment by puce [ 18/Nov/15 ]

I don't seem to have enough rights to fix the typos...

Comment by puce [ 18/Nov/15 ]

OK, according to the Javadoc, the readFrom method of a MessageBodyReader may throw a WebApplicationException, which seems strange as this seems only to make sense on the server side when parsing request messages.

But the same classes are also used on client side to parse response messages, which happens after the webservice has been called (which might be successful or not) and thus readFrom method should not affect the HTTP status code in this case.

http://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/MessageBodyReader.html#readFrom-java.lang.Class-java.lang.reflect.Type-java.lang.annotation.Annotation:A-javax.ws.rs.core.MediaType-javax.ws.rs.core.MultivaluedMap-java.io.InputStream-

Comment by puce [ 19/Nov/15 ]

You should be able to reproduce this issue by writing a JAX-RS client which calls a GET request and tries to unmarshal the response with JAXB using:
https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/SyncInvoker.html#get-java.lang.Class-

and

                <dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-jaxb</artifactId>
			<version>${jersey.version}</version>
		</dependency>

where the response provided by the server does contain a different content than expected -> call was successful, but unmarshalling fails -> should throw a ResponseProcessingException not a WebApplicationException

Comment by puce [ 20/Nov/15 ]

The same issue also happens if you call: response.readEntity(MyJaxbClass.class)

javax.ws.rs.BadRequestException: HTTP 400 Bad Request
	at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:136)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:808)
	at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
	at org.glassfish.jersey.client.InboundJaxrsResponse$1.call(InboundJaxrsResponse.java:115)
	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:419)
	at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:267)
	at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:112)
	at <some class>
	at <some class>
	at <some class>
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
	at java.lang.reflect.Method.invoke(Method.java:619)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at com.github.tomakehurst.wiremock.junit.WireMockStaticRule$1.evaluate(WireMockStaticRule.java:55)
	at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:110)
	at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo was not found in the project]
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1072)
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:326)
	at org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:140)
	at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:134)
	... 41 more
Caused by: Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo was not found in the project
	at org.eclipse.persistence.exceptions.XMLMarshalException.noDescriptorWithMatchingRootElement(XMLMarshalException.java:162)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshallerHandler.startElement(SAXUnmarshallerHandler.java:305)
	at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
	at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
	at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
	at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
	at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
	at org.eclipse.persistence.internal.oxm.record.XMLReader.parse(XMLReader.java:243)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:401)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:654)
	at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:581)
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:323)
	... 43 more

A ProcessException would be expected in this case.

Comment by puce [ 20/Nov/15 ]

Here is the stack trace of the first case, where readEntity gets called by JerseyInvocation$Builder.get :

javax.ws.rs.BadRequestException: HTTP 400 Bad Request
	at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:136)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
	at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
	at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
	at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:808)
	at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
	at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:803)
	at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
	at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
	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:696)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
	at <some class>
	at <some class>
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
	at java.lang.reflect.Method.invoke(Method.java:619)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at com.github.tomakehurst.wiremock.junit.WireMockStaticRule$1.evaluate(WireMockStaticRule.java:55)
	at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:110)
	at com.intellij.junit4.JUnit4TestRunnerUtil$IgnoreIgnoredTestJUnit4ClassRunner.runChild(JUnit4TestRunnerUtil.java:341)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
	at java.lang.reflect.Method.invoke(Method.java:619)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo was not found in the project]
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1072)
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:326)
	at org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:140)
	at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:134)
	... 47 more
Caused by: Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo was not found in the project
	at org.eclipse.persistence.exceptions.XMLMarshalException.noDescriptorWithMatchingRootElement(XMLMarshalException.java:162)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshallerHandler.startElement(SAXUnmarshallerHandler.java:305)
	at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
	at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
	at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
	at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
	at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
	at org.eclipse.persistence.internal.oxm.record.XMLReader.parse(XMLReader.java:243)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:401)
	at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:654)
	at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:581)
	at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:323)
	... 49 more

In this case a ResponseProcessingException would be expected containing the response object with the correct status code.

Comment by puce [ 23/Nov/15 ]

Related issue: JERSEY-2468





[JERSEY-3117] jersey-client 2.0: response.readEntity leads to java.lang.ClassCastException in case of mediaType = application/xml Created: 01/Jun/16  Updated: 01/Jun/16

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

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

jersey version: 2.22.2
java 7 oracle jdk1.7.0_76
java 8 oracle jdk1.8.0_92



 Description   

We are using the jersey-client 2.0:
....
MyExt2Response myExt2Response = response.readEntity(MyExt2Response.class);
...

We are using 3 jaxb classes, the first class is service specific, the second and third class are common part.
We always want to return a json or xml structure beginning with "response":

1) MyExt2Response
@XmlRootElement(name = "response")
public class MyExt2Response extends MyExt1Response

{ .... }

2) MyExt1Response
@XmlRootElement(name = "collectionReturn")
public class MyExt1Response extends MyResponse

{ ... }

3) MyResponse
@XmlRootElement(name = "response")
public class MyResponse

{ .. }

This runs fine in case of mediaType="application/json". We are using moxy as JsonProvider.

in case of mediaType = "application/xml" we are getting:
java.lang.ClassCastException: common.lib.MyResponse cannot be cast to task.lib.MyExt2Response
at test.Test.main(TaskTest.java:201)

no further stacktrace available

The error seems to occur in: org.glassfish.jersey.message.internal.MessageBodyFactory
or org.glassfish.jersey.message.internal.ReaderInterceptorExecutor:
the call: final Object instance = executor.proceed(); returns a MyResponse instance instead of returning MyExt2Response instance.

In case of mediaType="application/json" the correct jaxb class is returned: MyExt2Response

The readEntity call is also OK if we change the @XmlRootElement(name = "response") from MyResponse to a name different from "response".

But we can't change the existing interface and need a solution that works with same @XmlRootElement names.






[JERSEY-473] Access client port and IP address from HttpRequestContext Created: 17/Feb/10  Updated: 31/May/16

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

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

Operating System: All
Platform: Macintosh


Issuezilla Id: 473

 Description   

Currently the only way to obtain the client IP address and port is by injecting
HttpServletRequest.

We need to support a method on HttpRequestContext implementations of which can
defer to Servlet or say the low-level Grizzly API.

Low-level Grizzly request has:

request.remoteAddr().toString();
request.getRemotePort();



 Comments   
Comment by sandoz [ 17/Feb/10 ]

Clarification use:

GrizzlyRequest.getRemoteAddr()

Comment by spektom [ 22/Aug/13 ]

For a while, I'm using this hack to get the remote IP information: http://stackoverflow.com/a/18378248/398309

Comment by mikaelstaldal [ 11/Sep/14 ]

In the context of JAX-RS 2 and Jersey 2, It would make sense to add a method for this to javax.ws.rs.core.Request. Perhaps something for JAX-RS 2.1?

In the meantime, it can be added to org.glassfish.jersey.server.ContainerRequest

Comment by mpierce [ 31/May/16 ]

For resources, it's possible to work around this by injecting HttpServletRequest or equivalent. However, I need to access the IP inside an event listener. Any thoughts on what workarounds are feasible there?





[JERSEY-3115] During startup java.lang.IllegalArgumentException: Comparison method violates its general contract! Created: 31/May/16  Updated: 31/May/16

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

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

Windows 7, OSGI Equinox 3.10



 Description   

During startup of our OSGI application the following exception is thrown from time to time.
This prevents our web application which hosts our Jersey/REST resources to not start.

I had a look at the code pointed by the stack trace -

org.glassfish.jersey.message.internal.MessageBodyFactory.processMessageBodyWritersForType(MessageBodyFactory.java:955). 

This is what I found there:

// Type -> Writer.
        Collections.sort(suitableWriters, WORKER_BY_TYPE_COMPARATOR);

The suitableWriters collection is:

final List<WriterModel> suitableWriters = Lists.newArrayList();
   | 2016/05/31 11:16:34 | May 31, 2016 11:16:34 AM org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/spm] filterStart
INFO   | jvm 1    | 2016/05/31 11:16:34 | SEVERE: Exception starting filter spmRemote
INFO   | jvm 1    | 2016/05/31 11:16:34 | java.lang.IllegalArgumentException: Comparison method violates its general contract!
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.TimSort.mergeHi(TimSort.java:899)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.TimSort.mergeAt(TimSort.java:516)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.TimSort.mergeCollapse(TimSort.java:441)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.TimSort.sort(TimSort.java:245)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.Arrays.sort(Arrays.java:1512)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.ArrayList.sort(ArrayList.java:1454)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.util.Collections.sort(Collections.java:175)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.message.internal.MessageBodyFactory.processMessageBodyWritersForType(MessageBodyFactory.java:955)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.message.internal.MessageBodyFactory.getMessageBodyWriterMediaTypesByType(MessageBodyFactory.java:967)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.fillOutputTypesFromWorkers(MethodSelectingRouter.java:436)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.fillMediaTypes(MethodSelectingRouter.java:417)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.addAllConsumesProducesCombinations(MethodSelectingRouter.java:383)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.<init>(MethodSelectingRouter.java:166)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.RuntimeModelBuilder.buildModel(RuntimeModelBuilder.java:202)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.internal.routing.Routing$Builder.buildStage(Routing.java:196)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:587)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:415)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4854)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5546)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.tomcat.internal.TomcatServletContainer.startWebApplication(TomcatServletContainer.java:125)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.internal.StandardWebApplication.start(StandardWebApplication.java:109)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.extender.WebContainerBundleCustomizer.addingBundle(WebContainerBundleCustomizer.java:49)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:469)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:415)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.trackInitial(AbstractTracked.java:183)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.BundleTracker.open(BundleTracker.java:156)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.extender.ExtenderActivator$ExtendedWebContainerTracker.addingService(ExtenderActivator.java:59)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.extender.ExtenderActivator$ExtendedWebContainerTracker.addingService(ExtenderActivator.java:43)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:941)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:870)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:901)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:914)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:862)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:801)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:225)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:464)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:482)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:998)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.internal.WebContainerActivator$ServletContainerTracker.addingService(WebContainerActivator.java:117)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.internal.WebContainerActivator$ServletContainerTracker.addingService(WebContainerActivator.java:98)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:941)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:870)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.osgi.util.tracker.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:901)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:914)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:862)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:801)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:225)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:464)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:482)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:998)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.gemini.web.tomcat.internal.Activator.start(Activator.java:61)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:771)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:764)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at java.security.AccessController.doPrivileged(Native Method)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:764)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:721)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:941)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:318)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.Module.doStart(Module.java:571)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.Module.start(Module.java:439)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1562)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1383)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
INFO   | jvm 1    | 2016/05/31 11:16:34 | 	at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)


 Comments   
Comment by svileng [ 31/May/16 ]

Jersey version is 2.22.2.
We are using Oracle Java 8.





[JERSEY-3116] jersey endpoint with method params created programmatically not working Created: 31/May/16  Updated: 31/May/16

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

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


 Description   

I am trying to create jersey end-point in runtime, all looks fine except for the method parameters. I use the code below:

public void add(Object object) {
Class<? extends Object> clazz = object.getClass();
final Resource.Builder resourceBuilder = Resource.builder().path(clazz.getSimpleName());

for (Method method: clazz.getDeclaredMethods()) {
Builder methodBuilder = resourceBuilder
.addChildResource(method.getName() + "/

{string}

")
.addMethod("GET")
.produces(MediaType.TEXT_PLAIN_TYPE)
.handledBy(object, method);

List<Parameter> parameters = new LinkedList<>();
int index = 1;
for(Class<?> type : method.getParameterTypes()) {
parameters.add(Parameter.create(clazz, clazz, true, type, type, new Annotation[]

{new MyPathParam(index++)}

));
}

methodBuilder
.handlerParameters(parameters);
}
final Resource resource = resourceBuilder.build();
registerResources(resource);
}

I expect that the first argument of the method will bear the @PathParam annotation, however getting the below warning in logs:

May 31, 2016 2:51:50 PM org.glassfish.jersey.internal.Errors logErrors
WARNING: The following warnings have been detected: WARNING: A HTTP GET method, public java.lang.String com.example.service.MyService.cool(java.lang.String), should not consume any entity.

I have debugged the code and found that even though the handler passed to the below method has all parameters with right annotations, the invocable instance is missing annotations because the parameters attribute is initialized based on handlerClass and not on the handler instance, resulting in parameters getting lost during the build stage.

private Invocable(MethodHandler handler, Method definitionMethod, Method handlingMethod, boolean encodedParameters,
Type routingResponseType)

{ … this.parameters = Collections.unmodifiableList(Parameter.create( handlerClass, definitionMethod.getDeclaringClass(), definitionMethod, encodedParameters)); }




[JERSEY-2139] The org.glassfish.jersey.apache.connector.ApacheConnector cannot be fully configured (e.g., retry handler) because the HttpClient is not accessible. Created: 11/Oct/13  Updated: 27/May/16

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

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

Issue Links:
Dependency
depends on JERSEY-2229 Upgrade ApacheConnector to use Apache... Closed
Related
is related to JERSEY-2835 Add new ApacheClientProperties.DISABL... Open

 Description   

The ApacheConnector API has a design omission in that it does not allow the user to create and provide a configured HttpClient. In Jersey 1.7.x we were able to create an HttpClient, assign a retry handler directly, and provide the HttpClient to the Jersey client to use.

In Jersey 2.3.1, the ApacheConnector creates the HttpClient (a deprecated version of it) that the user cannot modify. The user can retrieve said client, but the HttpClient interface does not expose a configure it, it's essentially immutable. To make matters worse, this version of Jersey depends on httpclient 4.2.5 rather than 4.3. There have been many important changes and deprecations in 4.3 which impact the ApacheConnector design.

A good fix would be to provide an additional constructor ApacheConnector(HttpClient httpclient, Configuration config). I would also strongly recommend upgrading to depend on httpclient 4.3, removing deprecations, and refactoring as necessary.



 Comments   
Comment by seanl [ 22/Oct/13 ]

I am confused about the downgrading of priority and the change from Bug to Improvement. According to Jira:
Bug: A problem which impairs or prevents the functions of the product.
Improvement: An improvement or enhancement to an existing feature or task.
Major: Major loss of function.
Minor: Minor loss of function, or other problem where easy workaround is present.

Using the retry capability of HttpClient is a core capability for building more reliable systems. We use it extensively in our infrastructure. This capability was available in Jersey 1.7 so arguably this is a regression.

By downgrading it, are you saying there is an easy workaround?

Comment by Michal Gajdos [ 23/Oct/13 ]

Fair point about the priority, changing back to Major, but the task as a whole seems to me more like an Improvement (and by this I don't mean to make this issue any less important).

Comment by seanl [ 23/Oct/13 ]

Thanks gentlemen!

Comment by seanl [ 04/Dec/13 ]

Team, I see this issue is in the backlog. Would it expedite if I contributed a solution? I don't want to duplicate work if it is already occurring. If contributing is ok, should I rewrite ApacheConnector using HttpClient 4.3 instead of 4.2.5?

Comment by Michal Gajdos [ 04/Dec/13 ]

Let me get back to you tomorrow regarding this issue. I am currently working on JERSEY-2123 how big changes I am going to make, I should be smarter tomorrow.

Comment by Michal Gajdos [ 06/Dec/13 ]

We're currently reviewing patch that'll bring HttpClient 4.3 into Jersey. Anyways the connector mechanism will go through some changes so even though nobody is working on this issue right now so, please, wait until situation is more stable (we'll be working on connectors probably in 2.6).

Comment by seanl [ 06/Dec/13 ]

Thanks for the update Michal.

Comment by saacharya [ 15/Jul/15 ]

What's the status of this issue? Thanks.

Comment by steez [ 27/May/16 ]

We really need this feature. Right now the Apache Connector is crippled due to the limited ways of configuring it through the Jersey API.





[JERSEY-3066] JettyHttpContainer URL handling broken Created: 01/Mar/16  Updated: 23/May/16

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

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


 Description   

I'm creating a JAX-RS server using the jetty http container. The resource
is annotated with @Path("/services") and the whole JAX-RS handler is put under context "/my/path" (see code snippet below for details)

So an HTTP GET on <server:port>/my/path/service should end up in my rest resource. However, it does not on 2.22.2.

After stepping through the code, it seems that the JettyHttpContainer.handle constructs a wrong requestUri:"http://localhost:52021/my/path/my/path/services"
(notice the duplication of /my/path)

It is related to fixed done in scope of https://github.com/jersey/jersey/commit/239d02fcc0792155eb5aaf51e5c2b68e61203c19#diff-1997febdf388bca1dd941929123602df

I have reverted back to 2.21.1, which works fine.

        ContextHandler context = new ContextHandler();
        final Handler endpoint = RuntimeDelegate.getInstance().createEndpoint(application, Handler.class);

        context.setHandler(endpoint);
        context.setContextPath("/my/path");


 Comments   
Comment by fholmqvist [ 23/May/16 ]

Seeing the same with an EmbeddedJetty:

        ContextHandler appContext = new ContextHandler("/path");
        appContext.setHandler(new HttpContainer(app));
        contexts.setHandlers(new Handler[] { rootContext, appContext });
        server.setHandler(contexts);

Any request to /path/resource will become /path/path/resource in JettyHttpContainer by getBaseURI() and getRequestURI()





[JERSEY-3114] JettyTestContainerFactory ignores ServletContextListener silently Created: 19/May/16  Updated: 19/May/16

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

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


 Description   

Given:

import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.junit.Test;

public final class TestHelloWorld extends JerseyTest
{
	@Override
	protected DeploymentContext configureDeployment()
	{
		return ServletDeploymentContext.builder(TestApplication.class).
			servletClass(ServletContainer.class).
			addListener(JulToSlf4j.class).
			build();
	}

	@Test
	public void getMessage()
	{
		String message = target("helloworld").request().get(String.class);
		System.out.println("response: " + message);
	}
}

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.bridge.SLF4JBridgeHandler;

/**
 * Redirects logging from java.util.logging to slf4j.
 *
 * @author Gili Tzabari
 */
public final class JulToSlf4j implements ServletContextListener
{
	@Override
	public void contextInitialized(ServletContextEvent sce)
	{
		SLF4JBridgeHandler.removeHandlersForRootLogger();
		SLF4JBridgeHandler.install();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce)
	{
	}
}

JettyTestContainerFactory creates a Jetty server but fails to register the ServletContextListener.






[JERSEY-2627] Resource Reload Throw Exception Created: 25/Aug/14  Updated: 19/May/16

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

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

Sprint: Triaged

 Description   

Container.reload(rc) at ContainerRequestFilter or MessageBodyWriter

19:23:53.964 [Grizzly-worker(10)] WARN o.g.grizzly.http.server.HttpHandler - GRIZZLY0200: Service exception
org.glassfish.hk2.api.MultiException: A MultiException has 1 exceptions. They are:
1. java.lang.IllegalStateException: ServiceLocatorImpl(__HK2_Generated_1,2,1706339275) has been shut down

at org.jvnet.hk2.internal.FactoryCreator.getFactoryHandle(FactoryCreator.java:80) ~[hk2-locator-2.3.0-b05.jar:na]
at org.jvnet.hk2.internal.FactoryCreator.dispose(FactoryCreator.java:110) ~[hk2-locator-2.3.0-b05.jar:na]
at org.jvnet.hk2.internal.SystemDescriptor.dispose(SystemDescriptor.java:481) ~[hk2-locator-2.3.0-b05.jar:na]
at org.glassfish.jersey.process.internal.RequestScope$Instance.remove(RequestScope.java:512) ~[jersey-common-2.11.jar:na]
at org.glassfish.jersey.process.internal.RequestScope$Instance.release(RequestScope.java:529) ~[jersey-common-2.11.jar:na]
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:299) ~[jersey-common-2.11.jar:na]
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) ~[jersey-server-2.11.jar:na]
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028) ~[jersey-server-2.11.jar:na]
at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:365) ~[jersey-container-grizzly2-http-2.10.1.jar:na]
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) ~[grizzly-http-server-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) ~[grizzly-http-server-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.http.server.HttpHandlerChain.doHandle(HttpHandlerChain.java:223) ~[grizzly-http-server-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) ~[grizzly-http-server-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) ~[grizzly-framework-2.3.16.jar:2.3.16]
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) ~[grizzly-framework-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:724) ~[na:1.7.0_25]
Caused by: java.lang.IllegalStateException: ServiceLocatorImpl(__HK2_Generated_1,2,1706339275) has been shut down
at org.jvnet.hk2.internal.ServiceLocatorImpl.checkState(ServiceLocatorImpl.java:2182) ~[hk2-locator-2.3.0-b05.jar:na]
at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetServiceHandle(ServiceLocatorImpl.java:580) ~[hk2-locator-2.3.0-b05.jar:na]
at org.jvnet.hk2.internal.ServiceLocatorImpl.getServiceHandle(ServiceLocatorImpl.java:573) ~[hk2-locator-2.3.0-b05.jar:na]
at org.jvnet.hk2.internal.FactoryCreator.getFactoryHandle(FactoryCreator.java:77) ~[hk2-locator-2.3.0-b05.jar:na]
... 26 common frames omitted



 Comments   
Comment by cowwoc [ 27/Aug/14 ]

The problem has to do with server shutdown, not reload. I am getting this while shutting down the server at the end of a unit test, reload() is never invoked.

We're not going to be able to reproduce/fix this issue without the help from Jersey committers. Please add as much information as possible about the incoming request when this exception occurs.

Comment by cowwoc [ 27/Aug/14 ]

Also, I believe this is a regression in version 2.11. I don't recall ever getting it in 2.09 (I upgraded from 2.09 to 2.11).

Comment by icode [ 28/Aug/14 ]
            resourceConfig.registerInstances(new ContainerRequestFilter() {

                @Override
                public void filter(ContainerRequestContext containerRequestContext) throws IOException {
                    container.reload();
                }
            });
Comment by icode [ 28/Aug/14 ]

all test code, pls set logger level to warn. all request get a 500 http status

package org.glassfish.jersey.examples.reload;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.Container;
import org.glassfish.jersey.server.spi.ContainerLifecycleListener;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import java.io.*;
import java.net.URI;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Reload example application.
 *
 * A {@link ContainerLifecycleListener container listener} gets registered
 * with the application. Upon application startup notification, the listener schedules
 * a new {@link TimerTask timer task} to check a text file called {@code resources}
 * every 2 seconds. When the text file change is detected, the application gets reloaded with
 * a new {@link ResourceConfig resource configuration} including all
 * resource classes listed in that file.
 *
 * @author Jakub Podlesak (jakub.podlesak at oracle.com)
 */
public class App {

    private static final Logger LOGGER = Logger.getLogger(App.class.getName());
    private static final URI BASE_URI = URI.create("http://localhost:8080/flights/");
    public static final String ROOT_PATH = "arrivals";

    static Container container;

    public static void main(final String[] args) {
        try {
            LOGGER.info("Resource Config Reload Jersey Example App");

            final ResourceConfig resourceConfig = new ResourceConfig(ArrivalsResource.class);
            resourceConfig.registerInstances(new ContainerLifecycleListener() {
                @Override
                public void onStartup(final Container container) {
                    App.container = container;
                }

                @Override
                public void onReload(final Container container) {
                    System.out.println("Application has been reloaded!");
                }

                @Override
                public void onShutdown(final Container container) {
                    // ignore
                }
            });

            resourceConfig.register(ReloadFilter.class);

            final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig);

            System.out.println(String.format("Application started.\nTry out %s%s\nHit enter to stop it...", BASE_URI, ROOT_PATH));
            System.in.read();
            server.shutdownNow();
        } catch (final IOException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    @PreMatching
    @Priority(0)
    public static class ReloadFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext containerRequestContext) throws IOException {
            container.reload();
        }
    }
}
Comment by icode [ 28/Aug/14 ]

jersey 2.9 not have this issuse

Comment by cowwoc [ 28/Aug/14 ]

@icode,

Thank you! So now we've established this is a regression relative to version 2.9 and provided a minimal testcase.

Comment by Adam Lindenthal [ 13/Oct/14 ]

Thanks, guys. Moving to backlog.

Comment by cowwoc [ 05/Nov/14 ]

I am running into JERSEY-2627 and JERSEY-2622 very frequently (multiple times per run of unit tests). Can you please increase the priority of these issues? It's very annoying trying to differentiate between stack-traces related to actual test failures and these false positives.

Comment by Stepan Vavra [ 21/Dec/15 ]

Triaged. Let's check if this problem still remains.
In case you feel strongly about the issue, please consider contributing a fix by submitting a Github pull request.

Comment by cowwoc [ 19/May/16 ]

Stepan,

The problem is still present in Jersey 2.23. If I could pinpoint the problem, I would contribute a fix.

Jersey committers, please let us know if you are able to reproduce the problem on your end as well.





[JERSEY-2987] memory leak in multipart uploads Created: 11/Oct/15  Updated: 17/May/16

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

Type: Bug Priority: Major
Reporter: phraktle2 Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: evaluation-needed
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Sprint: Triaged

 Description   

Requests with multipart uploads create temp files (MIMExxx.tmp) which are marked for deletion using the JVM hook deleteOnExit. For long-running server processes, this is not appropriate since it leads to a memory leak (tracking of an ever-increasing number of references in a LinkedHashSet in java.io.DeleteOnExitHook).

See related mimepull issue: https://java.net/jira/browse/MIMEPULL-13



 Comments   
Comment by phraktle2 [ 17/May/16 ]

Any plans on fixing this? This affects long running server-apps, resulting in OOM.





[JERSEY-3107] Wrong number of QueryParams in mutiple QueryParams Created: 02/May/16  Updated: 16/May/16

Status: Open
Project: jersey
Component/s: test-framework
Affects Version/s: 2.22.2
Fix Version/s: None

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


 Description   

API:

@GET
public Response getTrackingRequest(@QueryParam("ids") final List<String> ids)

{ .. }

When Testing this api with following snippet:

target().queryParam("ids", "1", "2", "3").get();

Jersey cannot get all of ids, just first one of queryParam will be passed to API.

Downgrading to 2.15 works properly.



 Comments   
Comment by khajavi [ 02/May/16 ]

Also for 2.22, 2.22.1 versions.

Comment by Adam Lindenthal [ 16/May/16 ]

Hi Khajavi,

would you mind sharing a full reproducer example with both the client and server part?
I just quickly tried to locally add a testcase into QueryParamTest and the truth is, that it did fail indeed, but only for one container - simple-http.

Here's the code I added...

into resource:

        @Path("list")
        @GET
        public int get(@QueryParam("values") final List<String> values) {
            return values.size();
        }

and a test method:

    @Test
    public void testListQueryParam() {
        assertThat(target()
                .path("list")
                .queryParam("values", "value1", "value2", "value3", "value4")
                .request()
                .get(Integer.class),
                is(4));
    }

Please let me know if this works for you or not...

Regards,
Adam





[JERSEY-3105] Implement JSR 370 NIO support Created: 26/Apr/16  Updated: 16/May/16

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

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


 Description   

JAX-RS 2.1 will support non-blocking I/O. Jersey as the RI will implement this feature for version 3.0.



 Comments   
Comment by Adam Lindenthal [ 16/May/16 ]

Hi, I am sorry, but I have to close again...

There's no need to create explicit issues for all the features in the draft of a new specs....

Cheers,
Adam

Comment by Pavel Bucek [ 16/May/16 ]

sorry, that shouldn't be closed, reopening.





[JERSEY-3106] Implement JSR 370 reactive client invocations Created: 26/Apr/16  Updated: 16/May/16

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

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


 Description   

JAX-RS 2.1 will standardize reactive programming models of client HTTP invocations. Jersey as the RI will implement these features in version 3.0.



 Comments   
Comment by Adam Lindenthal [ 16/May/16 ]

Hi daschner,

this is the same situation as with the other issue you've opened recently - and also same resolution - so please don't feel offended, but I will close this...
Once we are releasing a version, that is meant to be the RI of the JSR, we will make sure, that it implements all the features specified in the specs.

Regards,
Adam

Comment by Pavel Bucek [ 16/May/16 ]

sorry, that shouldn't be closed, reopening.





[JERSEY-3104] Implement JSR 370 SSE support Created: 26/Apr/16  Updated: 16/May/16

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

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


 Description   

JSR 370 will include SSE support in JAX-RS. Jersey as the RI will implement the changes made to the JAX-RS API.



 Comments   
Comment by Adam Lindenthal [ 16/May/16 ]

Hi Dashner,

... Jersey as the RI will implement the changes made to the JAX-RS API.

Exactly as you say. Jersey as RI will implement all the features defined by the specification - once we have a version that serves as JSR 370 RI.
But for now, there's no reason to open a JIRA ticket for it, so this is going to be closed...

Regards,
Adam

Comment by Pavel Bucek [ 16/May/16 ]

sorry, that shouldn't be closed, reopening.





[JERSEY-3113] Multipart form with optional non simple types throws a nullpointerexception Created: 12/May/16  Updated: 12/May/16

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

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


 Description   

The existing multipart form handling for null complex objects was broken with the correction on default parameter converter SingleValueExtractor.java needs to handle null objects that are not defaulted via a parameter.

This was broken in 2.13.

We do have a patch that we will be submitting to resolve this issue.






[JERSEY-3038] Declarative Linking: Support @InjectLinkNoFollow on class level Created: 19/Jan/16  Updated: 10/May/16

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

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


 Description   

When an entity (lets call it parent) in my application links to a collection of entities associated with the parent entity, the declarative linking follows all fields of parent, to check those entities for other links (that's how I understand it).

This causes all lazy loaded collections to get loaded, even if they are not serialized into json format. So I end up with a huge amount of DB queries.
I could avoid this scenario by annotating every field of an entity with @InjectLinkNoFollow but this is impracticable. In fact, all fields of all my models would need to be annotated.

It should be possible, at least, to annotate a class with this annotation to avoid the traversal of associated entities. Or, the traversal of related entities is turned off by default.

A rudimentary fix would be this: https://github.com/jersey/jersey/compare/master...weaselmetal:release-2.19



 Comments   
Comment by weaselmetal [ 10/May/16 ]

Did anyone even take note of that issue? Loading everything there is from the database makes the declarative linking feature pretty much unusable for a great amount of applications I suppose.





[JERSEY-3112] Guice Scope is LOCAL, preventing guice injection in Filter. Created: 10/May/16  Updated: 10/May/16

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

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


 Description   

GuiceScopeContext visibility was set to LOCAL instead of NORMAL.

https://github.com/hk2-project/hk2/commit/0ad31489bd8485ef152bf1e9f1a872f9d4383443

The affect of this is that i am now unable to obtain guice dependencies within ContainerRequestFilter.

Was there a reason that a NORMAL visibility caused memory leaks? Does the child service locator create a new Injector? I would imagine it was the application/module's fault if any memory leak was found.






[JERSEY-3110] Response committed prematurely in case of unsuccessful calls (4xx & 5xx responses) Created: 06/May/16  Updated: 06/May/16

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

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


 Description   

From the tests attached it is evident that in case of unsuccessful responses, such as 404s, the response is immediately committed before it passes back through any servlet filters.

This means that if a filter is responsible for altering the response in some way, it will fail in case of erroneous responses.



 Comments   
Comment by sarah.cassar [ 06/May/16 ]
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class PrematureResponseTest extends JerseyTest {

    private static TestService testService = Mockito.mock(TestService.class);

    @Before
    public void setup() {
        Mockito.reset(testService);
    }

    @Override
    protected TestContainerFactory getTestContainerFactory() {
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment() {
        return ServletDeploymentContext.forServlet(new ServletContainer(new ResourceConfig(Resource.class))).addFilter(TestFilter.class, "test").build();
    }

    @Test
    public void successfulCall_testServiceShouldBeInvokedAndTestHeaderShouldBeDefinedInResponse() {
        final Response response = target("resource").request(MediaType.APPLICATION_JSON).header("caller", "0").get();
        Assert.assertEquals(200, response.getStatus());

        Mockito.verify(testService).doSomething("0");
        Assert.assertEquals("test", response.getHeaderString("test"));

        // This test shows that the response only committed after it passes back through the filter chain and therefore the response can be modified by the filter.
    }

    @Test
    public void unsuccessfulCall_testServiceShouldBeInvoked() throws InterruptedException {
        final Response response = target("non-existent-resource").request(MediaType.APPLICATION_JSON).header("caller", "1").get();
        Assert.assertEquals(404, response.getStatus());

        Mockito.verify(testService).doSomething("1");

        // This shows that the response is committed before the filter is completely executed.
    }

    @Test
    public void unsuccessfulCall_responseTestHeaderShouldBeSet() {

        final Response response = target("non-existent-resource").request(MediaType.APPLICATION_JSON).get();
        Assert.assertEquals(404, response.getStatus());

        Assert.assertEquals("test", response.getHeaderString("test"));
    }

    @Test
    public void unsuccessfulCall_suspendMainThreadForLongerThanFilterSleeps_testServiceShouldBeInvoked() throws InterruptedException {

        final Response response = target("non-existent-resource").request(MediaType.APPLICATION_JSON).header("caller", "2").get();
        Thread.sleep(3000L);

        Assert.assertEquals(404, response.getStatus());
        Mockito.verify(testService).doSomething(Mockito.eq("2"));

        // This test proves that the filter is indeed executed in case of unsuccessful calls.
        // Therefore, it can be concluded that the response is committed prematurely, as shown by next test.
    }

    @Test
    public void unsuccessfulCall_suspendMainThreadForLongerThanFilterSleeps_testResponseHeaderShouldBeSet() throws InterruptedException {

        final Response response = target("non-existent-resource").request(MediaType.APPLICATION_JSON).get();
        Thread.sleep(3000L);

        Assert.assertEquals(404, response.getStatus());
        Assert.assertEquals("test", response.getHeaderString("test"));

        // This test proves that even though the filter is executed, the response is already committed.
    }

    @Path("resource")
    public static class Resource {

        @Produces("application/json")
        @GET
        public void get(@Suspended final AsyncResponse asyncResponse) {
            asyncResponse.resume(new Model("testing"));
        }
    }

    public interface TestService {
        void doSomething(String caller);
    }

    public static class TestFilter implements Filter {

        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            try {
                chain.doFilter(request, response);
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Do something and alter response.
                testService.doSomething(((HttpServletRequest) request).getHeader("caller"));
                ((HttpServletResponse) response).setHeader("test", "test");
            }
        }

        @Override
        public void destroy() {

        }
    }

    public static class Model {
        private String field;

        public Model(final String field) {
            this.field = field;
        }

        public String getField() {
            return field;
        }

        public void setField(final String field) {
            this.field = field;
        }
    }
}
Comment by sarah.cassar [ 06/May/16 ]

Please note that I am testing using version 2.22.2 and have the following maven dependencies:

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.22.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
            <version>2.22.2</version>
            <scope>test</scope>
        </dependency>
        <dependency> 
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.22.2</version>
            <scope>test</scope>
        </dependency>




[JERSEY-3109] rep23xxxx which is created for @FormDataParam("upload") File file is getting with 0kb Created: 05/May/16  Updated: 05/May/16

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

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


 Description   
@POST
	@Path("/files/content")
	@Consumes({MediaType.MULTIPART_FORM_DATA})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@SecurityLevel(value = "ADD_DOCUMENT_ACCESS{verifyDocumentModuleIsEnable=true,verifyActiveSite=true}")
	@AuditTypeAlias(value = "ADD_FILE")
	public Response insertDocument(@FormDataParam("file") File file, @FormDataParam("file") FormDataContentDisposition fileDetail,
// my stuff

i can see MIMExxxxx.tmp which jersey create for multipart request with the correct size in tocat temp but
Second rep23xxxx which is created for @FormDataParam("upload") File file is getting with 0kb
so i'm not able to upload.

I have trying with Jersey 2.2
It works fine for me with Jersey 1.7

can u please help me in this



 Comments   
Comment by prem.masarani [ 05/May/16 ]

here is the list of jars that i have used :
==============================
jersey-client-2.22.2
jersey-common-2.22.2
jersey-container-servlet-2.22.2
jersey-container-servlet-core-2.22.2
jersey-entity-filtering-2.22.2
jersey-media-jaxb-2.22.2
jersey-media-json-2.0-m05
jersey-media-json-jackson-2.22.2
jersey-media-multipart-2.22.2
jersey-server-2.22.2
jersey-guava-2.22.2





[JERSEY-2428] SslContext and HostVerifier not passed on nonPreemptive auth Created: 28/Feb/14  Updated: 28/Apr/16

Status: In Progress
Project: jersey
Component/s: core
Affects Version/s: 2.6
Fix Version/s: None

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

OS:
Linux 3.12-1-amd64 #1 SMP Debian 3.12.9-1 (2014-02-01) x86_64 GNU/Linux

JAVA:
java version "1.7.0_25"
OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1~deb7u1)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)



 Description   

The SslContext and the HostVerifier are not passed when the WS is using a BASIC authentication and nonPreemptive is used. The request is repeated (with authorization header) but both settings are not passed, so the second attempt with BASIC header can fail because security reasons (SSL certs or hostname verification).

This is a sample code for testing:

    static public void main(String[] args) throws Exception {
        ClientBuilder clientBuilder = ClientBuilder.newBuilder();
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = {new InsecureTrustManager()};
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
        Client client = clientBuilder.sslContext(sc).hostnameVerifier(allHostsValid).build();
        client.register(HttpAuthenticationFeature.basicBuilder()
                // comment this line or not to checl the bug
                .nonPreemptive()
                .credentials("ricky", "Kiosko_00").build());
        Response response = client.target("https://localhost:8181/jaxrs-sample")
                .path("webresources")
                .path("hellows")
                .path("sayhello")
                .queryParam("name", "ricky")
                .request()
                .get();
        if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
            System.out.println(response.readEntity(String.class));
        } else {
            throw new Exception(String.format("HTTP error (%d): %s", response.getStatus(), 
                    response.getStatusInfo().getReasonPhrase()));
        }
    }

I have check the code of version 2.6 and the issue is quite issue to fix. Here it is a tentative patch:

*** ./org/glassfish/jersey/client/authentication/HttpAuthenticationFilter.java.ORIG	2014-02-28 10:48:41.678462757 +0100
--- ./org/glassfish/jersey/client/authentication/HttpAuthenticationFilter.java	2014-02-28 10:48:13.322008734 +0100
*************** class HttpAuthenticationFilter implement
*** 296,302 ****
       *
       */
      static boolean repeatRequest(ClientRequestContext request, ClientResponseContext response, String newAuthorizationHeader) {
!         Client client = ClientBuilder.newClient(request.getConfiguration());
          String method = request.getMethod();
          MediaType mediaType = request.getMediaType();
          URI lUri = request.getUri();
--- 296,306 ----
       *
       */
      static boolean repeatRequest(ClientRequestContext request, ClientResponseContext response, String newAuthorizationHeader) {
!         Client client = ClientBuilder.newBuilder()
!             .hostnameVerifier(request.getClient().getHostnameVerifier())
!             .sslContext(request.getClient().getSslContext())
!             .withConfig(request.getConfiguration())
!             .build();
          String method = request.getMethod();
          MediaType mediaType = request.getMediaType();
          URI lUri = request.getUri();

As you see the repeatRequest method now uses SslContext, HostnameVerifier and the configuration of the original request. With this patch my simple testcase works no matter it is preemptive or not.



 Comments   
Comment by Miroslav Fuksa [ 04/Mar/14 ]

Hi,

thanks for the bug report and for the patch proposal. I am moving the issue to the backlog.

Mira

Comment by mirko.beine@arsinventionis.de [ 04/Feb/15 ]

This also applies to digest auth, obviously. If I'd create a PR, is there any chance this fix would make it into the next release?

Comment by granum41 [ 28/Apr/16 ]

I'd love to see a fix to this. Any updates on status? It looks like there's been some activity on github.
https://github.com/jersey/jersey/commit/4451b36d71b7b1629f7fca1e3faab5e6c1c4d007





[JERSEY-1950] Enable Jersey/Guice integration via HK2 Guice Bridge Created: 24/Jun/13  Updated: 27/Apr/16

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

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

Issue Links:
Dependency
blocks HK2-121 Guice-servlet integration Open
Related
is related to JERSEY-2184 Ability to inject ServletContext into... Closed
is related to JERSEY-1957 Implement Spring integration for Jers... Closed
is related to HK2-139 @Hk2Inject does not work on the const... Open

 Description   

The HK2 Guice Bridge is available, but there may be more work needed in Jersey in order to enable it.



 Comments   
Comment by cowwoc [ 24/Jun/13 ]

This issue is related to https://java.net/jira/browse/HK2-39 and https://java.net/jira/browse/HK2-121

To reiterate, here is what we had in Jersey 1.0:

Container
\-> GuiceFilter (Guice: initialize request scope)
  \-> GuiceServletContextListener (Guice: initialize the Guice injector)
    \-> JerseyServletModule (Jersey: bind Jersey types to Guice module)
      \-> GuiceContainer (Jersey: redirect incoming requests to resource classes)

In other words, we created a Guice injector first and initialized Jersey second.

In Jersey 2.0 we have a circular reference. We need to initialize Injector before ServletContainer (otherwise @RequestScoped isn't initialized), but we need to initialize ServletContainer before Injector (otherwise we can't get a reference to ServiceLocator).

Comment by vokiel [ 15/Aug/13 ]

I've been reading the various issues on Guice with Jersey 2.0 & HK2 and I have to say I'm a bit confused as to what the bridge allows currently and what it doesn't allow. I'm trying to get Guice-Persist to work with Jersey, but yes it just won't inject what the module defines (factories and such).

If I just use the bridge as is and install a JpaPersistModule into the HK2 bridge, shouldn't it be able to inject an EntityManager from the Guice definition in my resources afterward? All that without having to use GuiceFilter & the Servlet plumbing of Guice? Isn't this just adaptation?

What sm I missing or what's the status?

Comment by cowwoc [ 17/Aug/13 ]

Jersey 2.0 doesn't support Guice, period.

Development is being held up on the Jersey end of things, not HK2.

Anyone wishing to help should take a look at how Spring integration was added in JERSEY-1957 and try to replicate the technique for Guice.

Comment by cowwoc [ 27/Sep/13 ]

I finally figured out how to wedge Guice support into Jersey 2 (mostly through trial and error). Can someone from the Jersey team please review and publish the following documentation as part of the official user guide?


1. Add GuiceFilter and ServletContainer to web.xml:

    <filter>
        <filter-name>GuiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>GuiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>JerseyApplication</filter-name>
        <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.mycompany.MyApplication</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>JerseyApplication</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2. Note that GuiceFilter must show up before ServletContainer.
3. Define an application as follows:

public class MyApplication extends ResourceConfig {

    @Inject
    public MyApplication(ServiceLocator serviceLocator) {
        // Register root resources, then...
        
        // Instantiate Guice Bridge
        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);

        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        Injector injector = Guice.createInjector(new MyModule());
        guiceBridge.bridgeGuiceInjector(injector);
    }
}

4. Define a Guice module as follows:

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        // Configure Guice as you normally would, then...

        install(new ServletModule());
    }
}

5. ServletModule defines the "request" scope. GuiceFilter creates/destroys the scope on each incoming request.


Let's begin by amending the documentation, and then we can follow up by adding a sample application and unit tests that mirror the Spring module.

Comment by jwells [ 27/Sep/13 ]

That's a gr8 solution. I'd still like to see a more integrated solution though...

Comment by reinert [ 27/Sep/13 ]

It is not possible to just substitute H2K to Guice?

I don't like the idea of two DI containers working together. I would rather prefer just using Guice for managing every DI issue in my application.

Comment by cowwoc [ 27/Sep/13 ]

@jwells, what did you have in mind?
@reinert, I don't think Jersey gives us an option. I believe it forces the use of HK2.

Comment by