FAQ Database Discussion Community


Jersey 2.x Custom Injection Annotation With Attributes

java,jersey,jersey-2.0,dropwizard,hk2
I am in the process of migrating from DropWizard 0.7.1 to 0.8.1. This includes migrating from Jersey 1.x to 2.x. In my implementation that uses Jersey 1.18.1, I had a MyProvider (changed all class names for simplicity's sake) that implements InjectableProvider. This class would create MyInjectable objects, containing the custom...

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

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...

Exception in the allocation for the servlet

java,angularjs,rest,jersey,jax-rs
I'm fighting the whole day with this: I want to call the connect service method from AuthentificationService I have this exception (the rest of the code at the bottom): 06-May-2015 14:29:45.986 SEVERE [http-nio-8082-exec-28] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable com.sun.jersey.spi.inject.Errors$ErrorMessagesException at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170) at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) at...

Dropwizard: Passing custom type query parameter

java,rest,jersey,jax-rs,dropwizard
How can I accept custom type query parameter? public String detail(@QueryParam("request") final MYRequest request) { Above line gives error while starting the server jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization. ...

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...

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...

Jersey: Can I add a cookie in ContainerResponseFilter?

cookies,jersey,jax-rs,servlet-filters
I have a ContainerResponseFilter and I tried to set a cookie in it as follows: @Override public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { String cookieName = "ExampleCookie"; String cookieValue = "SomeData"; logger.info("Setting cookie " + cookieName + " with value " + cookieValue + " into cookies "...

Where to add @XMLElement(name=“name”) annotation

java,jersey
Where do I use @XMLElement annotation in my class? URL:http://localhost:8080/GigstartServices/GET/Users/2/Orders I want it to be <Orders> <Order> </Order> </Orders> instead of <Orderss> <Orders> </Orders> </Orderss> I have following classes for Orders in my project. OrderResource.java : package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.xml.bind.annotation.XmlElement; import...

Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: “OPENSHIFT_MYSQL_DB_PORT”'

java,mysql,jersey,openshift
I am trying to deploy my Jersey project on openshift. I have implemented this apple class to test the error in the another class since I guess the problem is with the establishing the database connection. in the Tails log I found this error: Connecting to database… com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load...

Jersey: disable default JSON provider

java,jersey,jackson,jersey-2.0
i am using Jersey 2.17, JSON and automatic feature discovery. I have my custom JSON Provider extending JacksonJsonProvider. It's annotated with @Provider and automatically registerd, same as default one that comes with: <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> </dependency> I want to disable/exclude default one without giving up on feature scanning/manually registering everything....

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...

Jersey and HK2 - Injecting current user

java,rest,jersey,jersey-2.0,hk2
I'm working with jersey 2.17 and hk2 to create a simple rest app. I have a ContainerRequestFilter that rejects any request that doesn't have the "currentuser" cookie. I have something like this: @Path("/users") public class UserResource { private UserService userService; @GET @Path("/orders") @Produces("application/json") public List<Order> findOrdersOfCurrentUser() { // some ugly...

Jersey: ContainerRequestFilter does not get Context ServletRequest

java,jersey,jetty,ip-address,servlet-filters
To see the full code for this issue, please see this github https://github.com/mobiusinversion/web-application I also created this Jersey Jira https://java.net/jira/browse/JERSEY-2851 I am working on a ContainerRequestFilter using Jersey 2.15. This is an embedded Jetty app which is shaded into a single jar. In the Jetty starter (main class): public static...

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>...

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...

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...

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")...

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...

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...

Is it possible to Use Cache Control Option in my code

java,jersey,cache-control
I have got a Simple JERSEY WEBService which is responsible to return states present in our Database package com.services.regg; @Path("/getstates") public class FetchStates { @GET @Consumes("application/text") @Produces("application/json") public String getAllSates() throws JSONException { JSONArray jsonarray_allstates = new JSONArray(); Connection dbConnection = null; PreparedStatement getAllStatesPst = null ; ResultSet getAllStatesResltSet =...

Using custom JAXB context with Jersey client

java,json,jaxb,jersey,jersey-client
I'm using Jersey client 1.8 + JAXB. I want to post a JSON payload that looks like the following: { "transactions": [ { "amount": { "currency":"EUR","total":"1" } ... } ], } I have a DTO that looks like this: @XmlRootElement public class PaymentRequestDTO { @XmlElement(name="transactions") public List<TransactionDTO> getTransactions() { return...

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 approach this authentication mechanism in Jersey

java,rest,jersey
I am new to Jersey REST Framework , so please excuse if this is a dumb question . I am using Tomcat with Hibernate and Jersey REST Webservices. I have got set of HTML pages in my Web APP login.html dealer.html sales.html I dont want the User to access the...

Atmosphere, dropwizard and jersey injection error

compiler-errors,jersey,dropwizard,atmosphere
Here is my gradle file: compile group: 'io.dropwizard', name: 'dropwizard-core', version: '0.8.0' compile group: 'io.dropwizard', name: 'dropwizard-auth', version: '0.8.0' compile group: 'io.dropwizard', name: 'dropwizard-client', version: '0.8.0' compile group: 'org.glassfish.jersey.media', name: 'jersey-media-multipart', version: '2.16' compile group: 'org.glassfish.jersey.core', name: 'jersey-client', version: '2.16' compile group: 'org.atmosphere', name: 'atmosphere-jersey', version: '2.1.10' After adding atmosphere-jursey...

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...

Set the Http status code if it is not set

java,jersey,jackson
I am trying to build a JSON string as server response with the aid of the Jackson library. If the route is not 0 I am getting tis response {"status":201,"routes":null} but I have problem to set the status variable to 204 in the SDBean class if the routeD is 0...

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>...

Resource not found in Jersey (Error 404)

java,ajax,rest,maven,jersey
I am making an AJAX call to a Jersey resource through JavaScript where class is mapped to /books and a GET method to /allBooks. This is the code for AJAX call: function libBooks(){ alert("Inside js"); //The above alert is displayed var requestData = { "dataType": "application/json", "type": "GET", "url": "http://localhost:8080/library/rest/books/allBooks/"...

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;...

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...

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...

Maven dependency for testing using Jersey Test Framework

maven,jersey,jersey-2.0,jersey-client,jersey-1.0
I am trying to test a Restful service using Jersey Test Framework , I have the following code in place. import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URLEncoder; import javax.json.JsonException; import org.junit.Test; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.test.framework.*; import com.sun.jersey.test.framework.AppDescriptor; import com.sun.jersey.test.framework.JerseyTest; import com.sun.jersey.test.framework.WebAppDescriptor; public class MakeSureTest...

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...

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...

Receive the InputStream and get the values from json string in Jersey

java,jersey,inputstream
How can I received JSON string from the InputStream in Jersey, which was sent from HttpURlConenction in android, and how can I get the values of it to store them into database table? { "latitude":93.86898451, "longitude":30.66561387, "time":"24.04.2015 11:11:05", "route":4 } Jersey receiver class: @Path("data") public class Receiver { @POST @Consumes({MediaType.APPLICATION_JSON,...

Jersey Maven quickstart archetype in Eclipse

java,maven,jersey,jersey-2.0,maven-archetype
I am trying to create Jersey normally with the aid of maven but I am always getting this structure as in the scrennshoot and without error as normally?! It does not look as Jersey commonly layout. I am using this one: org.glassfish.jersey.archetypes jersey-quickstart-webapp 2.16 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/xsd/maven-4.0.0.xsd">...

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...

Please verify you invoked Maven from the correct directory

java,maven,jersey
I have installed maven : C:\Windows\System32>mvn --version Apache Maven 3.3.3 (7994120775791599e405a7528ec3e0dke21dja06; 2015-04-22T13:57:3 7+02:00) Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.3.3 Java version: 1.7.0_51, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.7.0_51\jre Default locale: de_DE, platform encoding: Cp1252 OS name: "windows 8", version: "6.2", arch: "amd64", family: "windows" I am trying to generate...

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...

405 error returned when using POST method in Jersey

java,jersey
I'm using Jersey and have had no problem with GET and PUT calls but for some reason POST refuses to work; I keep getting a 405 returned. I've tried multiple permutations for the signature on my method and I'm starting to wonder if there is something else I'm missing. Here's...

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...

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;...

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...

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

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...

HTTP Status 415 - Unsupported Media Type when doing POST

spring,rest,java-ee,jersey,jax-rs
So I was trying to do a POST using REST with Postman in Chrome, but after I hit send got error HTTP Status 415 - Unsupported Media Type My code and part of the screen shot is included, the pair for the hashmap I tried is duration and 150. I...

Caching in Jersey Implemented Web Service

java,rest,caching,jersey
Currently my Jersey Implemented Rest Web Service method is able to get a list of String from database table based on userId. Service will send only one string at a time to User Client calling. Remaining should be stored in cache for a certain period and for that userId. So...

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....

Can't get json from Swagger + Jersey

java,api,rest,jersey,swagger
I have RESTful service based on Jersey 1.18.1 and I want to show my API via Swagger. Firstly I have to get JSON. I read this instruction: Swagger Core Jersey 1.X Project Setup 1.5. Swagger allows to set up a configuration different methods and I decided to use custom Application...

Jersey Client/JAX-RS and optional (not default) @QueryParam

java,rest,jersey,jax-rs
I have a RESTful API who's document says that a certain query parameter is optional, and does not supply a default argument. So, I can either supply the value or not send it in the GET request as a parameter. Example: queryA is required queryB is optional (can send GET...

Using SelectableEntityFiltering in Jersey 2.17

java,filter,jersey,jackson,jersey-2.0
I am new in Jersey and i try to use the SelectableEntityFilteringFeature from the example: http://blog.dejavu.sk/2015/02/04/jerseys-entity-filtering-meets-jackson/#selectable I create a small service with the following classes/files: a resource file called PersonResource.java import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.message.filtering.SelectableEntityFilteringFeature; import org.glassfish.jersey.server.ResourceConfig;...

Resource query parameter validation on jersey-dropwizard

java,jersey,dropwizard
I have a dropwizard application and in one resource i would like to have a required query parameter. I know jersey supports bean validation so i tried to use @NotNull annotation but it didn't work. Here's the code to resource: @Path("/resource/{id}") @Produces(MediaType.APPLICATION_JSON) public class MyResource { //....constructor... @GET public String...

Why the session attribute is coming as null

jersey
A HTML5 UI is connected to the backend (REST Jersey to business logic to Hibernate and DB). I need to create and maintain a session for each user login until the user logs out. I am clueless on how to approach this problem. I followed this approach Initially when the...

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...

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...

Why am I getting a 500 response for my POST on my Jersey REST API?

java,jersey,dropwizard,postman
I have just begun implementing my first Drowizard project. Here's my first resource class: @Path("/bill") public class CommandResource { //... @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/createBillForStudy") public Response handleCreateBillForStudyCommand(CreateBillForStudyCommand cmd, @Context UriInfo uriInfo) { System.out.println("Creating bill for command: " + cmd); UUID newId = billCreator.handle(cmd); URI location = uriInfo.getBaseUriBuilder().path(CommandResource.class).path("/" + newId).build(); return...

Why does QueryParam return null

java,jersey,jax-rs
I hava a post method where I try and add the parameter "enc": protected void sendPost(String url, String encData) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("enc="+encData); wr.flush();...

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...

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...

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...

return just part of the bean with toJson()

java,json,jersey,jackson
I am trying to return {"status": its value}´in the case of routeD!=0 currently I am getting {"status":201,"routes":null} I would get the response in this form {"status":201} without "routes":null at the same time I dont want to lost the response of routeD==0 which is for example {"status":230,"routes":[1,9,3]} I appeciate any help....

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...

Getting 404 error with Jersey Tomcat service

java,web-services,rest,tomcat,jersey
I am getting a 404 page when trying to run a RESTful service in Java with Jersey and Tomcat. Here is my project: Here is the HelloWorld.java: package service; import javax.ws.rs.*; @Path("/hello") public class HelloWorld { @GET @Produces("text/plain") public String get() { return "Hello World"; } } Here is the...

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 can jersey check what was the requested data format?

java,web-services,api,rest,jersey
I wonder how to check what data client request from rest API for example I have api like: @POST @Consumes({ MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }){ ...some logic; } if client has header: Accept: application/xml than I want him to get different response than if he had application/json in header....

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=......

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...

How to deploy my RESTful application to Apache server?

java,eclipse,apache,rest,jersey
I built my java RESTful application in Eclipse with Jersey and a couple other libraries. My question is, how do I deploy this to a Tomcat server? Do I export it as a WAR file? Do I need to deploy the libraries I used as well or are they packaged...

AbstractMethodError using UriBuilder on JAX-RS

java,maven,jersey,jax-rs
I am trying to build a REST webservice using an asynchronous response. I have looked around this error on the web, however, none of the solutions have worked for me. I am not sure on how to go about it. This is the code for the REST service, it has...

Jersey REST service not consuming JSON

rest,jersey,response,jersey-client
I have a REST service and client. I am trying to invoke this service to consume a JSON directly and convert it to the object I need. But it's not working. I am getting the following error: A message body reader for Java class com.a.b.c.D, and Java type class com.a.b.c.D,...

Jersey @Path not working in Jetty+servlet

java,jersey,jetty
I am failing to get the combination of Jetty + servlet + Jersey working. Here are my steps: 1. pom.xml <packaging>war</packaging> ... <dependencies> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet-core</artifactId> <version>2.17</version> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId>...

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 {...

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 =...

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>."...

jersey - moxy returning appended json in class property

java,json,glassfish,jersey,moxy
I have a jersey client that makes a call to a 3rd party rest api and retrieves some JSON. {"A":1,"W":2,"List":[{"name":"John","amount":10.0}]} After that I need to append this JSON to my response class and give it back in the response. @XmlRootElement public class MyResponse { private JsonObject body; private String status;...

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...

send JSON response with two method's return values

java,json,jersey
I have this method to consume JSON string I am getting here two return values.The first from the insertData method and it is integer 201 or 208 and the second value from getStopRoute it is ArrayList. How can I return the both value in Jersey with JSON in this case?...

org.postgresql.util.PSQLException: ERROR: syntax error at or near “(”

java,sql,heroku,jersey
I have craeted a Web Application that can be deployed on Heroku by maven eclipse. Group Id: org.glassfish.jersey.archetypes Artifact Id: jersey-heroku-webapp version: 2.17 I tested the appication on the localhost and POSTMAN and it works fine. I pushed it to heroku to test it on servlet container but I am...

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 {...

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...

Pass Multiple parameters in a REST call

rest,jersey,jax-rs
My server code is as: @POST @Path("/getMapping") public ListResponse getMapping(Long id, String name, String clientName, String instanceName) { ListResponse response = null; try { response = new ListResponse(); List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName); response.setStatusCode(SUCCESS); response.setMappings(mappings); } catch (Exception e) { setResponseErrors(response, e); } return response; } I am...

Probleme with my Servlet and @FormDataParam Jersey

java,rest,jersey,multipartform-data,jersey-2.0
I have a problem with my web-services using Jersey. I have a form composed of two inputs, one of type "file" and one of type "text". The problem is that when I only use the input of type "file", everything works fine, but when I add the second one, of...

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...

MessageBodyWriter not found for media type={application/xml, q=1000} - Jersy + Jaxb

rest,jaxb,jersey,jax-rs
I am writing a RESTful web service with Jersy. I want to return a custom object in XML form to consumer. The error I am getting is - MessageBodyWriter not found for media type={application/xml, q=1000}, type=class com.test.ws.Employee, genericType=class com.test.ws.Employee. Below is the code: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"...

Will Java Annotations make the performace slow because of reflection?

java,reflection,annotations,jersey
If we use Java annotations will the reflection apis be called everytime to analyze those annotations? Wont that make the execution slow? By everytime I mean whenever that flow is executed. Example Case: IN Jersey we use the annotations @Get which is used everytime there is a get request on...

Couldn't get JSON response from Java Jersey app using Tomcat or GlassFish server

eclipse,tomcat,java-ee,glassfish,jersey
I have problem with my Java Jersey app. I'm writing an app with this tutorial: http://programmerguru.com/android-tutorial/android-restful-webservice-tutorial-how-to-create-restful-webservice-in-java-part-2/ My app is almost the same as in this example expect fact that I'm using Maven to import .jar files. I also have some changes in db. I run this db on wamp server...

Setting Http Status Code and customized status message and returning JSON output using Jersey in RESTful Service

json,web-services,rest,jersey
I have implemented a RESTful service using Jersey. I am able to return the desired output in JSON format. But, I also need to set Http Status Code and my customized status message. Status code and status message should not be part of the JSON output. I tried following links:...

JSON-Request to Jersey causes “400 Bad Request”

json,rest,jersey
I have a jersey server example, that works fine with XML, but does not work with JSON. import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlRootElement; @Path("JsonExample") public class JsonExample { @XmlRootElement public static class Input { public String text; } @POST @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public String test(Input i) {...

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:...

I can not connect my database on Heroku

java,sql,heroku,jdbc,jersey
I have craeted a Web Application that can be deployed on Heroku by maven eclipse. Group Id: org.glassfish.jersey.archetypes Artifact Id: jersey-heroku-webapp version: 2.17 then I followed this guide(1.5) to push it to Heroku. https://jersey.java.net/documentation/latest/getting-started.html#heroku-webapp I can not access my apple class from the http link- like this: https://salty-refuge-2027.herokuapp.com/apple and I...

Jersey is not following 302 redirects

java,rest,jersey
I am connecting to a server which first goes to an auth login page and then redirects. ClientConfig config = new DefaultClientConfig(); config.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); Client client = Client.create(config); client.setFollowRedirects(true); WebResource service = client.resource(UriBuilder.fromUri(url).build()); String output = service.path(resource) .path(model) .path(id) .accept(MediaType.APPLICATION_JSON) .get(String.class); This is throwing an exception: Exception in thread "ThreadJob"...

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...

Jersey Sub-Resource Locators Error

json,grails,jersey
I'm trying to get the JSR-311 plugin working with Grails 2.3.7. I'm using version 0.10, because I think 0.11 requires Grails 2.4. I've used the generate-resource command to create an end point for my domain class Product. Two resource classes are created, ProductCollectionResource and ProductResource. I've tweaked them a bit,...

POST to Jersey REST service getting error 415 Unsupported Media Type

java,json,rest,tomcat,jersey
I am using a JAX-RS web application with Jersey and Tomcat. Get requests are fine however when I try to post JSON I get an HTTP status 415 - Unsupported Media Type. Here is my simple HelloWorld.java: package service; import javax.ws.rs.*; @Path("hello") public class HelloWorld { @GET @Produces("text/plain") public String...

@JsonInclude(JsonInclude.Include.NON_NULL does not work for double

java,json,jersey,jackson
I am trying to retieve {"status":201} in the case of route!=0 but I am getting {"status":201,"distance":0.0} how can I reach that with @JsonInclude or Jackson also without "distance":0.0? SDBean bean = new SDBean(); if (routeD != 0) { // Insert the data into the bus table bean.status = db.insertData(macD, routeD,...

How to implement JAX-RS RESTful service in JSF framework

jsf,servlets,jersey,jax-rs
In my lab I was asked to create a simple website using JSF framework and use REST as well. I did some research on those two. It turns out that for REST I have to use JAX-RS framework with Jersey. I was wondering how can I integrate these two frameworks,...

How to upload binary file(Photos etc ) with Meta Data using REST

rest,jersey,media-type
One way of doing is to convert the binary data to Base64 and send it along with meta data as MediaType.APPLICATION_JSON. The problem with this is client has to convert the binary data into Base64 before sending. I also tried sending using MediaType.APPLICATION_OCTET_STREAM format through REST. This works fine for...

MultiPartFeature with javax.ws.rs.core.Application

java,web-services,rest,jersey,tomcat7
I'm trying to upload a file using Jersey but I'm facing a lot of trouble. I saw that i have to configure MultiPartFeature to make things happen but I couldn't make it work. I understand that i have to enable multipart feature on jersey but that's the problem. I tried...