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


EHCache and DropWizard: Returning no response

Question:

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?


Answer:

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.

@Override
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.");
    }
    logRequestHeaders(request);
    PageInfo pageInfo = buildPageInfo(request, response, chain);

    writeResponse(request, response, pageInfo);
}

Related:


How to struggle dependencies problems in maven


java,maven,jersey,jetty
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...

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


java,json,python-2.7,jersey
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...

No object available for injection error when using bindFactory


java,dependency-injection,jersey,jersey-2.0,hk2
I have the following implementation for a Jersey (2.18) application: public class RootApplication extends ResourceConfig { public RootApplication() { packages("com.foo.bar"); 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>...

How to get @interface parameter in jersey WriterInterceptor Implementation


java,annotations,jersey,jax-rs,interceptor
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 {...

Cache inconsistency - Entity not always persisted in cached Collection


java,hibernate,jpa,caching,ehcache
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...

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


java,jquery,ajax,jersey
$.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...

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


java,hibernate,jersey,jax-rs
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...

Jersey Viewable resulting in 404


java,spring,jsp,tomcat,jersey
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....

Intertwining resources in Jersey in a mutual way


java,rest,jersey
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...

Runtime error in Codenvy Java execution


java,maven,jersey
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(Main.java:22) [STDERR] Caused by: java.lang.ClassNotFoundException: com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory [STDERR] at java.net.URLClassLoader$1.run(URLClassLoader.java:366) [STDERR] at...

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


java,dependency-injection,jersey,jersey-2.0,hk2
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...

EJB injection not working in different classes


java-ee,netbeans,jersey,ejb,jax-rs
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...

How to return RSS with REST service?


java,rest,rss,jersey,rome
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("http://example.com"); feed.setDescription("Test Site."); List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndEntry entry = null; SyndContent description = null;...

Handling managed Hibernate DAO exceptions in Dropwizard


java,hibernate,jersey,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 send a JsonObject in JerseyClient POST call?


java,json,rest,jersey,jersey-client
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...

Find Jersey Parent Path


java,jersey,jax-rs
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: http://example.com/api/v1/resource/field...

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


java,json,rest,jersey
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>."...

Read the JSON file in the Jersey sources folder


java,json,jersey,jackson
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 =...

JEE can't run JAX-RS WebService skeleton app


java,maven,glassfish,jersey,jax-rs
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="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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wld</groupId> <artifactId>HelloWebService</artifactId> <packaging>war</packaging>...

Jersey Recieve List of Files


java,rest,jersey
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...

java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map


java,rest,deployment,glassfish,jersey
I am trying to deploy my first rest application using jersey 2.17. I am using Maven, GlassFish 3.1.2.2 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:...

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


spring,dependency-injection,jersey,jersey-2.0,hk2
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...

uriBuilder returns http:/ instead of http://


java,url,jersey,uri
I use this code: UriBuilder builder = UriBuilder .fromPath(Constants.LIVEMAP_BASE_URL_US) .scheme("http"); return builder.build().toString(); how can it be that it has generated "http:/" instead of "http://" ? returned value = http:/livemap-tiles1.waze.com/tiles/internal?lineGeom=......

can't inject Providers mock in JerseyTest


java,mocking,jersey,integration-testing,inject
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...

REST Jersey server JAX-RS 500 Internal Server Error


java,rest,jersey,jax-rs
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 Response.build() is called, the status says 200 OK. But that's not what...

How to remove duplicate XML declaration


java,xml,xsd,jersey,jersey-client
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="http://www.w3.org/2001/XMLSchema-instance"> <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 - JerseyTest: Error reading entity from input stream


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

Jersey, @QueryParam List


jersey,query-parameters
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...

Jersey JUnit Test: @WebListener ServletContextListener not invoked


java,rest,junit,jersey,jax-rs
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...

Tomcat 7.0 + Chrome dont show JSON


java,json,rest,tomcat,jersey
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...

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


java,jersey,jackson,jax-rs
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: //Interface.java public interface Interface { public void setA(A a); } //Resource.java @Path("/hello")...

How to disable common name check in SSLContext in java?


java,ssl,jersey,jax-rs,ssl-certificate
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...

Java Restful Service eclipse tomcat HTTP Error 404


java,rest,tomcat,jersey,jersey-2.0
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...

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


java,json,rest,jersey,jax-rs
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 javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONObject;...

Jersey Client - Variable types are ignored


java,json,jersey,jersey-client
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: User.java package de.topazmedia.component.api.rest.client.ressource; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public...

Include null field values in Jersey REST Response


rest,jersey
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),...

Jersey Client, memory leak, static and concurrency


java,concurrency,jersey,jersey-2.0,jersey-client
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()...

How to define vonstraint validation order across multiple fields/properties


jersey,hibernate-validator,spring-validator,jsr303
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...

PDF file empty after outputting with Jersey


java,pdf,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...

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


java,rest,tomcat,jersey
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...

ehCache Statistics with spring boot


statistics,spring-boot,ehcache
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...

Jersy 2 Client + JAXB (MessageBodyWriter not found)


java,jaxb,jersey
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...

Using GetHttpConnection in MFC


c++,mfc,jersey,wininet,winhttp
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,...

Getting application/json back from a Solr query


java,json,solr,jersey,jersey-client
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...

Routing all Jersey REST requests through a method prior to execution


jersey,java-ee-7
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...

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


jersey,jersey-2.0,jersey-client
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...

Ehcache cache .data files have escaped unicode characters


windows,ehcache,datastore
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: %004c%004f%0043%0041%004c%004dodifier%004cinking%004danager.data Should be: LOCALModifierLinkingManager.data Why is this the case? How can I fix it? Environment: Windows 7 x64...

How to make Jersey Unit test for Post method


java,rest,junit,jersey,jax-rs
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 (https://jersey.java.net/documentation/latest/test-framework.html): @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...

Liferay 6.2 clustering issue with multicast


lucene,cluster-computing,liferay-6,ehcache,jgroups
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 portal-ext.properties: cluster.link.enabled=true...

Swagger is not generating @Api resources


spring,jersey,swagger
I'm trying to integrate Swagger to document my REST API. I have followed this tutorial verbatim: http://jakubstas.com/spring-jersey-swagger-configuration/ 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 {...