jersey,ehcache,dropwizard , EHCache and DropWizard: Returning no response

EHCache and DropWizard: Returning no response


Tag: jersey,ehcache,dropwizard

I have successfully integrated SimplePageCachingFilter with DropWizard.

However, there is one thing standing in my way. Whenever an exception in my application is thrown, instead of being routed to my ExceptionMapper I get "Response contains no data" in my API Browser. I also happen to see this pass by in the log. WARN [2015-02-12 04:06:21,768] net.sf.ehcache.constructs.web.GenericResponseWrapper: Discarding message because this method is deprecated.

Traditionally my ExceptionMapper returns the appropriate Json Responses.

Has anyone else seen anything similar?


After attaching a debugger to DropWizard (per @CAB's advice) I discovered that the CachingFilter does not write out a response unless the status code is 200.

I extended CachingFilter and overrode the doFilter method and ignored the status check. This appears to have solved my problem.

protected void doFilter(final HttpServletRequest request,
                        final HttpServletResponse response, final FilterChain chain) throws Exception {
    if (response.isCommitted()) {
        throw new AlreadyCommittedException("Response already committed before doing buildPage.");
    PageInfo pageInfo = buildPageInfo(request, response, chain);

    writeResponse(request, response, pageInfo);


Cache inconsistency - Entity not always persisted in cached Collection

I'm having an issue where a Validation instance is added to a Collection on a Step instance. Declaration is as follows: Step class: @Entity @Table @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Step extends AbstractEntity implements ValidatableStep { @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "step_id", nullable...

How to get @interface parameter in jersey WriterInterceptor Implementation

I have an interface, for example @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface AutoLogged { boolean query() default false; } How can I get query parameter in interceptor implementation? @Provider @AutoLogged public class AutoLoggedInterceptor implements WriterInterceptor { @Context private ResourceInfo resourceInfo; @Override public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException { try {...

REST Jersey server JAX-RS 500 Internal Server Error

I'm calling this method and getting a 500 back from it. In the debugger I'm able to step though it all the way to the return statement at the end. No problem, r is populated as expected after is called, the status says 200 OK. But that's not what...

Jersey version issue: MessageBodyReader not found for media type=application/xml

While writing a simple Jersey client that was consuming XML data, I came across this exception "MessageBodyReader not found for media type=application/xml". All of my settings, including the jersey-client as maven dependencies was just fine. The version that I was using was 2.17. Once I degraded the version to 2.15...

Jersey Client - Variable types are ignored

I am using the Jersey Client of Sun Version 1.19... When I send a put request with JSON (but every other request type probably as well) it serializes Number-typed variables with quotes, instead of as plain numbers. Example: package; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public...

Tomcat 7.0 + Chrome dont show JSON

Iam using Dynamic Web Project 2.5, Jersey and Tomcat 7.0 to create a Java Restful Webservice. I want to response JSON if someone request data. But i always get the following error from Tomcat: That my configurations in relation to web.xml and annotations are ok is demonstrated by using xml...

Whenever I try to run Tomcat with Jersey, it refuses to load

Basically I am trying to create a simple Hello World program using Rational Software Architect. To create the server I use Tomcat and Jersey. I found that when I create the server without putting the jersey jar files into WEB-INF/lib but rather I create a custom user library with all...

Jersey Viewable resulting in 404

I am attempting to create a RESTful web service in Java using Jersey and Tomcat. The problem I am having is that after authenticating a user, I try to return a Response with a Viewable containing the path to my file and I receive a 404 resource not found error....

Jersey Client, memory leak, static and concurrency

I am using Jersey Client (v2.17) to make external calls from my app. I found out this memory leak bug (the CPU consumption was very high) which made me re-write my code to make the client static like this: public class GeneralUtil { private static final Client client = ClientBuilder.newClient()...

Swagger is not generating @Api resources

I'm trying to integrate Swagger to document my REST API. I have followed this tutorial verbatim: and it works peroperly. I see: { apiVersion: "1.0", swaggerVersion: "1.2" } Now, I want to register one endpoint: @Path("endpoint") @Api(value = "/endpoint", description = "My first documented endpoint") public class MyEndpoint {...

Is it possible to construct an object partially with Spring DI and partially with Jersey DI?

I have a class JerseyWebService which uses Jersey DI to inject dependency @Path("/baskets") public class JerseyWebService { @Inject ExternalApiServiceInterface api; ... } The dependency is specified in the binder public class CustomBinder extends AbstractBinder { @Override protected void configure() { bind(ExternalApiService.class).to(ExternalApiServiceInterface.class); ... } But the problem here is that ExternalApiService...

How to return RSS with REST service?

I'm using ROME for RSS feed generating and Jersey as REST service. Here is my RSS feed generation. public SyndFeed generate() { SyndFeed feed = new SyndFeedImpl(); feed.setFeedType( "rss_2.0" ); feed.setTitle( "My Site" ); feed.setLink(""); feed.setDescription("Test Site."); List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndEntry entry = null; SyndContent description = null;...

can't inject Providers mock in JerseyTest

I'm getting Providers from context in my filter to get defined ObjectMapper public class Filter implements ContainerRequestFilter, ContainerResponseFilter { @Context private Providers providers; @Context private HttpServletRequest request; private ObjectMapper getObjectMapper() { ContextResolver<ObjectMapper> contextResolver = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE); if (contextResolver == null) { return new ObjectMapper(); } return contextResolver.getContext(null); } } but...

Intertwining resources in Jersey in a mutual way

I'm trying to get my head around this RESTful scenario in Jersey: I have two resources, User and Item, and i want to retrieve all the items connected to a certain user and all the users connected to a certain item. In short, there exists a many-to-many relationship between User...

Using GetHttpConnection in MFC

I have a rest Server written in java and I am trying to call a GET method from an MFC client. The server URL is http://localhost:8080/com.test.simpleServlet/api/customers and this returns me the proper value when I run through the crome postman plugin. I have implemented Java Restful WebService as the Server,...

Jersey - JerseyTest: Error reading entity from input stream

I have created a test project in order to learn Jersey. I have created the following classes (Model),, and so far everything works just fine. My problem is with a JerseyTest i am trying to run ( I am using Jackson for JSON serialization. When i run...

Getting application/json back from a Solr query

I'm calling the Solr REST api using a Jersey client: final ClientResponse resp = client().path(queryPath()) .queryParam("q", query.getQuery()) .queryParam("wt", "json") .accept(MediaType.APPLICATION_JSON_TYPE) .get(ClientResponse.class); resp.getEntity(HttpResponse.class) and when I run it I get: A message body reader for Java class challenger.HttpResponse, and Java type class challenger.HttpResponse, and MIME media type text/plain; charset=UTF-8 was not...

PDF file empty after outputting with Jersey

I am trying to send a PDF file I generated in my server to my client in my Jersey application. The generation goes just fine, I created the file on my local machine and there is no problem with it. Problem arises when I try to send it by a...

Post request to jersey Java RS web service showing media unsupported 415. I am using PostMAN to send the request

I have been trying since hours to correct this thing but it is still showing media unsupported page. I am adding headers application/json in postman. Here is my Java Code package lostLove; import; import; import; import; import; import; import; import; import org.json.JSONObject;...

How to make Jersey Unit test for Post method

Questions How do create a Jersey Unit Test for a POST? How do I add post parameters? What I tried For a GET it is easy ( @Test public void test() { final String hello = target("hello").request().get(String.class); assertEquals("Hello World!", hello); } For a post it is more diffuse. I managed...

Jersy 2 Client + JAXB (MessageBodyWriter not found)

I'm trying to use Jersy 2 in client mode to post XML to a server but i always get an exception. I have got only one dependency in my pom file: <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.18</version> </dependency> My Java code: public static void main(String... args) { Client client = ClientBuilder.newClient(); WebTarget...


I am trying to deploy my first rest application using jersey 2.17. I am using Maven, GlassFish for deployment. Application runs in eclipse (tomcat), but gives following error when deploying through glassfish admin console. Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException:...

No object available for injection error when using bindFactory

I have the following implementation for a Jersey (2.18) application: public class RootApplication extends ResourceConfig { public RootApplication() { packages(""); register(new AbstractBinder() { @Override protected void configure() { bindFactory(RepositoryFactory.class).to(Repository.class); // if I use following line instead of bindFactory it works // bind(OracleRepository.class).to(Repository.class); } }); } public class RepositoryFactory implements Factory<Repository>...

Java Restful Service eclipse tomcat HTTP Error 404

i try to keep up with a java rest service. So i found some tutorials, which explain always the same way. But i cant get this running :(. I made Dynamic Web Project in Version 2.5 and Tomcat 7.0 in eclipse. Then i load following jars to WEB-INF/lib My Projectname...

Include null field values in Jersey REST Response

I'm including Instance of Following class in one of my REST Resource Response. public class GenericResponse<T> implements Serializable { private String message; private String errorMessage; private String errorCode = "0"; .... } There are other fields in this class but, when a field is null or "0" (as a String),...

Read the JSON file in the Jersey sources folder

I have Jersey project glassfish 2.18 and I am trying to read the JSON file routes.txt in this folder scr-main-sources with the Jackson 2.x . How can I get The InputStream of the text document file to get the data from it? I appreciate any help Code: FileReader fileReader =...

Jersy Rest service to accept java.util.Map for MediaType.APPLICATION_JSON

I have written a Jersey rest service which accepts java.util.Map as input for example @POST @Path("validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String validate(Map<String,String> data) throws Exception And from UI post Response structure is: {"data":{"abcd":"5210","two":"5173"}} Server gives an issue "SEVERE: MessageBodyReader not found for media type=application/json; charset=UTF-8, type=class java.util.HashMap, genericType=java.util.HashMap<java.lang.String, java.lang.String>."...

Jersey, @QueryParam List

I want to take a list as a parameter, but the value of the list does not correspond to java version list. For example @QueryParam("orderBy") List orderBy) This list has the value of [age, name] as an element. Is it possible to have the value separately. Like 1st element age...

Is it possible to use Jersey CDI in any JavaSE application?

I have a interface here interface Idemo{ public int getDemo(int i); } And it's one implementation class DemoImpl implements Idemo{ @Override public int getDemo(int i){ return i+10; } } And there is a class which has a dependency on Idemo class Sample{ @Inject Idemo demo; public int getSample(int i){ return...

Runtime error in Codenvy Java execution

I am newbie with Codenvy and I am developing a RESTful service using Jersey based on this code. When I build and run the code, the console returns this error. [STDERR] Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/jersey/api/container/grizzly/GrizzlyWebContainerFactory [STDERR] at com.apiconnect.Main.main( [STDERR] Caused by: java.lang.ClassNotFoundException: com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory [STDERR] at$ [STDERR] at...

Liferay 6.2 clustering issue with multicast

I am trying to cluster ehcache and lucene with Liferay 6.2 EE sp2 bundle on 2 servers with mutlicast enabled. WE have Apache HTTPD servers fronting tomcat servers using reverse proxy. A valid 6.2 license is deployed on both the nodes. We user the following properties in the

Routing all Jersey REST requests through a method prior to execution

What I would like to do is define a method at the root resource level that is called prior to any sub resources of that class. Looking through the API I see nothing like this. Jersey 1.6...

Pass parameter data from JQuery/Ajax call to Jersey web service

$.ajax({url:"http://localhost:8080/TestApp/resources/Test", type:"GET", data:userName :"userName", cache: false, success:function(result){ alert(result); }, }); Above is the JQuery code I'm using to call the service. How can I get the userName parameter to the @GET @Produces("text/html") public String getHtml() { return "Hello "; } Similar to a request.getParameter("") in servlet. In my understating...

ehCache Statistics with spring boot

I have spring boot application with ehcache as below @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); //ehCacheManagerFactoryBean.setCacheManagerName("messageCache"); ehCacheManagerFactoryBean.setShared(true); return ehCacheManagerFactoryBean; } @Bean public EhCacheCacheManager cacheManager() { return new...

How to send a JsonObject in JerseyClient POST call?

I have a POJO class, in which one element is of type JSONObject : public static class TestRequest { org.json.JSONObject data; } I want to send it over a POST call using JerseyClient. I tried this : Client client = new Client(); TestRequest request = new TestRequest(); Map<Long, String> data...

How to remove duplicate XML declaration

I am receiving following XML response via Jersey client <?xml version="1.0" encoding="UTF-8" standalone="yes"?><aaa><bbb key="Data"><?xml version="1.0" encoding="UTF-8" standalone="yes"?> <my-data xsi:noNamespaceSchemaLocation="MyData.xsd" xmlns:xsi=""> <data name="abc" uniqueId="4fe95637-a381-4e0c-bf7f-49f794df5f23"> <variable var1="xyz" value="44"/> </data> </my-data> </bbb></aaa> I am saving this as an XML file and getting...

Jersey JUnit Test: @WebListener ServletContextListener not invoked

I created this test in Jersey (from the docs), which works fine, with one problem: the @WebListener ServletContextListener is not being invoked. The Resource classes that I need to test rely on an attribute set on the ServletContext by the ServletContextListener. Can I make sure it is invoked, or can...

Python Requests: POST JSON and file (multiform data) in 1 single request

From client side (using python) I want to send both json data and file as part of single request using multiform-data but not able to achieve this. On server side I have Jersey which is working fine if I send the request using curl but if the same request is...

Handling managed Hibernate DAO exceptions in Dropwizard

I'm having a problem with Dropwizard where I can't catch the exception thrown by the Hibernate DAO object within my resource. I have the following DAO object public class ApplicantDAO extends AbstractDAO<Applicant> { public ApplicantDAO(SessionFactory factory) { super(factory); } public long create(Applicant person) { return persist(person).getApplicantId(); } } I am...

How to disable common name check in SSLContext in java?

I am using SSLContext so set up Jersey client, and need to disable the common name check in order to avoid unnecessary issues. However, I can find no documentation as to how we can do it correctly. So is the common name check disabled by default in SSLContext (assuming using...

How to define vonstraint validation order across multiple fields/properties

How to get validation error messages according to the order of field declaration ie. in sequence. Ex: @EmptyCheck(message = "{contactName.empty}") private String contactName; @EmptyCheck(message = "{personal.empty}") private String personalNo; For this in first request am getting contactName cant be null and followed by second message But for second request am...

Jersey Recieve List of Files

I want to receive a List of Files (just the names on a Nexus Server). Here is my current Code: ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter(nexusUser, nexusPassword)); WebResource service = client.resource("http://localhost:8081/nexus/content/repositories/linkToRepo ClientResponse response = service.accept("application/json").get(ClientResponse.class); String output = response.getEntity(String.class); But i just receive the html...

uriBuilder returns http:/ instead of http://

I use this code: UriBuilder builder = UriBuilder .fromPath(Constants.LIVEMAP_BASE_URL_US) .scheme("http"); return; how can it be that it has generated "http:/" instead of "http://" ? returned value = http:/

Input data-validation in a restful web service (to use null-object or not to)

Below is a web service which gives the latest version among all books with a given Id. //Resource controller @Path("latestVersionBook/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionBook(long id){ bookList=service.getLatestVersionBook(id) return Response.ok(bookList).build(); //backend Service Below is the service method that uses jpa to get the books public getLatestVersionBook(long id){ Query query = entityManager.createQuery("from...

Ehcache cache .data files have escaped unicode characters

My caches' data filenames seem to contain escaped unicode characters in the data store. Strangely only capital letters in the cache names are replaced. Eg: Should be: Why is this the case? How can I fix it? Environment: Windows 7 x64...

Find Jersey Parent Path

I have a Jersey 2.x endpoint that a user can POST to to update a specific property on a parent resource. On success, I would like to return a 303 status and specify the path to the parent resource in the Location header. eg. if the user POSTed to:

How to struggle dependencies problems in maven

I have this error for maven-jetty-plugin. I think that this problem happens because of transit dependencies from plugin, which conflict with new libraries. This error appeared after I changed jersey1 to jersey2 and changed all dependencies from com.sun to org.glassfish for server client/core/rs-ws, etc. [ERROR] Failed to execute goal org.eclipse.jetty:jetty-maven-plugin:9.3.0.M2:run...

EJB injection not working in different classes

I have tried to inject an Entity EJB(Facade and entity from MySQL database) but it doesn't work depending on the class it is in. I use a Rest webService and it work in the webService class. I use a multi layered architecture and I don't want my EJB to be...

JEE can't run JAX-RS WebService skeleton app

I'm using Windows, NetBeans 8.0.2, GlassFish 4.1. I can't make my example JAX-RS app running. This is pom.xml: <project xmlns="" xmlns:xsi="" xsi:schemaLocation=""> <modelVersion>4.0.0</modelVersion> <groupId>com.wld</groupId> <artifactId>HelloWebService</artifactId> <packaging>war</packaging>...

How to specify concrete type for abstract method param in Jersey/ Jackson?

I am using Jersey and have exposed a resource Resource which implements an Interface. One of the methods from Interface has a parameter a of type A which is an abstract class. Here is some code for explanation: // public interface Interface { public void setA(A a); } // @Path("/hello")...