FAQ Database Discussion Community


How to get instance of javax.ws.rs.core.UriInfo

java,unit-testing,jax-rs,jersey-2.0,grizzly
Is there any implementation of javax.ws.rs.core.UriInfo which I can use to create an instance quickly for testing. This interface is long, I just need to test something. I don't want to waste time on whole implementation of this interface. UPDATE: I want to write a unit test for a function...

How to get the requested contenttype of a REST-Request?

java,rest,jaxb,jax-rs
Using JAXB for implementing a REST-Webservice, we have several methods that are producing output. The class that contains all of these methods is annotated with @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }). If a request goes the happy-path (no errors occur), we return the POJO's in our methods and JAXB dynamically marshalls these...

MultiException when custom jersey param throws exception

java,jax-rs,jersey-2.0,dropwizard
NOTE: All code to reproduce this problem is available at https://gist.github.com/SrikanthRao/c9fc35e6fe22a74ab40c http://localhost:8080/date/bean?date=2014-13-23 (using BeanParam) produces "{"code":500,"message":"There was an error processing your request. It has been logged (ID 48be9aa43bd49547)."}" without adding MultiExceptionMapper to jersey. If I add MultiExceptionMapper to jersey, the above url results in "Date is either not in YYYY-MM-DD...

@Context object not injected when unit testing resteasy

java,unit-testing,jboss,jax-rs,resteasy
I'm trying to register a @Provider which would inject Locale object into the @Context so that I can reuse it in my REST resources. Following the article http://bill.burkecentral.com/2011/03/09/adding-objects-that-are-context-injectable/ I managed to get the provider running @Provider public class LocaleProvider implements ContainerRequestFilter { public static final String DEFAULT_LANGUAGE_CODE_VALUE = "en-US"; @Context...

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

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

Reading from a JDBC Blob after leaving the Spring transaction

jax-rs,blob,spring-transactions
I have the following schematic implementation of a JAX-RS service endpoint: @GET @Path("...") @Transactional public Response download() { java.sql.Blob blob = findBlob(...); return Response.ok(blob.getBinaryStream()).build(); } Invoking the JAX-RS endpoint will fetch a Blob from the database (through JPA) and stream the result back to the HTTP client. The purpose of...

Comparing if two list of strings are equal using hashcode?

java,java-ee,collections,jax-rs
I am writing a Java/JEE client server application. I have a requirement were the files present in the server should match with the files present in the client. I am only trying to validating if there is an exact match to the file names and number of files in a...

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

JAX-RS service response is returning double fields without decimal places

java,json,web-services,jax-rs
I'm working on a JAX-RS web service that returns a POJO as a JSON. The POJO contains double and integer fields. The problem is whenever the double fields are whole numbers(eg - 3.0, 22.0 etc), the corresponding fields in the returned JSON does not contain the decimal point. The decimal...

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

Jax-RS unable to authenticate to proxy

java,jax-rs,resteasy,squid
My company has a proxy proxy=myProxy port=myProxyPort username=me password=myPassword I try to access the outside world by using simple java.net functions and it worked! System.setProperty("http.proxyHost", myProxy); System.setProperty("http.proxyPort", myProxyPort); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(me,myPasssword.toCharArray()); }}); URL u = new URL("http://www.google.com"); HttpURLConnection con = (HttpURLConnection)...

rest jax-rs : server error

java,web-services,rest,jax-rs
I'm creating a little webservice with JAX-RS and I cannot access to my GET request http://localhost:8080/MyProject/resources/agenda I just want my list of my activities in XML format. Here is my code package com.project.test; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import javax.ws.rs.DefaultValue; import javax.ws.rs.PathParam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import...

How can I add a session/login servlet to get a session object for a Spring - Apache CXF backend?

spring,spring-mvc,servlets,cxf,jax-rs
I have a whole lot of REST webservices developed with CXF and managed in a spring application container, and I have been tasked with creating a servlet that will create a session object that will store attributes which will be read within the Jax-RS services. I have tried just adding...

JavaEE Web JAX-RS: how to match Query params

java,filter,jax-rs
JAX-RS allows to match PathParams using regex like this: @GET @Path("/users/{username : [a-zA-Z][a-zA-Z_0-9]}") public Response getUserByUserName(@PathParam("username") String username) { ... } But does it allow to match QueryParams as well somehow?...

Restlet how to decode secret in HTTP basic authentication

java,rest,base64,jax-rs,restlet
I have the following class handling one of my routes: public class HotelsSrv extends ServerResource implements HotelsListResource { private String hotelId; @Override protected void doInit() throws ResourceException { super.doInit(); String str; String secret = getRequest().getChallengeResponse().getSecret().toString(); byte[] bytes = new BASE64Decoder().decodeBuffer(secret) str = new String(bytes); System.out.println("user: "+getRequest().getChallengeResponse().getIdentifier()); System.out.println("password: "+str); } I...

Calling a RESTEasy Client Proxy interface, how can I specify which Content-type the endpoint will consume?

java,jax-rs,resteasy,tika
I want to PUT, via binary, to an endpoint that can consume one of many possible mimetypes. Specifically, I am communicating with an Apache Tika server, which could take, say, a PDF or a Word .docx file. I've set up a client proxy interface that I can hardcode, say, the...

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

Setting response header using interceptor?

java,java-ee,jax-rs,resteasy,interceptor
I'm writing jax-rs end points. For some set of end points (existing code), I want to set an extra response header which was actually generated in @AroundInvoke interceptor and set to HttpServletRequest attribute. In @AroundInvoke I'm able to access HttpServletRequest using @Inject. But it seems I cannot access HttpServletResponse in...

how to see actual body sent from restassured

jax-rs,wildfly,rest-assured
I have created a jax-rs rest api and tested it with rest-assured. All tests are green. Now I am trying to create an html/js front end for it. My problem is I do not know how my json objects should look like to be accepted by my rest api. Thanks...

How can I negotiate which post method will be called?

api,rest,jax-rs,resteasy
I am trying to implement a Post method with different method signatures. How can I do that, I was trying to do it with MessageBodyReader but it seems to call only one type of post that is ObjectMapper if i have one post method with signature ObjectMapper as param. @POST...

Limit output payload response in CXF JAX-RS based service

java,spring,rest,cxf,jax-rs
I have multiple jax-rs services built using cxf/spring. I want to control the output payload response size of all services. For simplicity sake, let's say none of api's in any of the services should ever return a JSON response payload more than 500 characters and I want to control this...

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 make a jax-rs end point accept any type of http request?

http,jax-rs,resteasy
The title says it all. Is there any request type annotation to do that? Or is it enough to annotate the method with all the required types like @POST, @GET?...

How to set javax.ws.rs.Path annotation value from properties [duplicate]

java,web-services,jax-rs,jax-ws
This question already has an answer here: jaxrs variable @Path 1 answer I want to set javax.ws.rs.Path annotation value from properties file. The purpose is not to make it configurable, rather the purpose is to separate the value from code. The following code works: private final String path="my_path"; @GET...

restlet post getFirstValue always returns null

java,rest,jax-rs,restlet
I am using postman client to send RES request to this restless router: public Representation createAgent(Representation entity) { Form form = new Form(entity); String user = form.getFirstValue("user"); String password = form.getFirstValue("password"); System.out.println("user: "+ user); System.out.println("password: "+ password); System.out.println("form: "+ form.toString()); return (agent.save(getUser(),getPassword())) ? new StringRepresentation("user "+ user +" created", MediaType.TEXT_PLAIN)...

Java Jersey PathParams Checking and NotFoundException custom message

java,rest,exception-handling,jax-rs,jersey-2.0
I am using Jersey for rest API, JerseyTests to unit test. I have been following what seems to be conventional practice over the internet for PathParams checking and Exception Handling, but I don't quite understand what I am doing wrong here: RoomApplicationResource.java @Path("demandes") public class RoomApplicationResource { @GET @Path("/{email}/{requestNumber}") public...

Roadblock using generics in jax-rs rest services using jpa

java,jpa,jax-rs
I am writing a rest service that exposes a relational database. I have three layers in the application: Persistence layer (the JPA entities) EJB layer Rest layer For each entity, the methods that I am implementing are: add, update, findAll, findById. I am using Java generics in both the Rest...

Eclipse JAX-RS (REST Web Services) 2.0 requires Java 1.6 or newer

eclipse,spring,web-services,jax-rs
i'm new to web service and i'm trying to do a project using jax-rs rest and spring in eclipse. I use java 1.8 but eclipse shows me an error that jax-rs 2.0 requires java 1.6 or newer error and my project won't work This is the project explorer and error's...

database access using jersey RESTful API

java,mysql,jax-rs
How to access database using jersey RESTful JAX-RS api?? This is hello.java my jersey server side import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/hello") public class Hello { // This method is called if HTML and XML is not requested @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey...

Unable to consume Jersey Webservice

java,web-services,jax-rs,jax-ws,jersey-2.0
I try to consume Jersey-2 webservice using postman. below my webservice @Path("UserService") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class UserService { @POST @Path("/getUser") public Utilisateur getUser(@FormParam("identitifiant")String identifiant,@FormParam("password") String password) { UtilUtilisateur myUser = null; try { myUser = requestUser(identifiant, password); } catch (Exception t) { log(t); } return myUser; } Below my web.xml...

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

JAX-RS @FormParam one time for all methods

java,web-services,java-ee,jax-rs,java-ee-6
I am developing Java "JAX-RS" Web Services for books and contents. There will be 100s of URLs something similar ... https://api.example.com/v1.3/book1/chapter/1 https://api.example.com/v1.3/book1/chapter/2 ... https://api.example.com/v1.3/book1/chapterN To fetch the chapter content user needed to POST authToken, which I validate in server and return content or error. The sample code ... @Path("/book1") public...

How to get the response header in a RestEasy client?

java,rest,jax-rs,resteasy
i´m implementing a Restful service using Jax-RS 2.0 (Resteasy 3.0.7.Final) and share the interface between client and service. The return value is void because ClientResponse is deprecated since RestEasy introduced JAX-RS 2.0 in version 3+. To return the location of the new created object i inject the response, using the...

Jersey JAX-RS 3 level nested object has null value

jaxb,jersey,jax-rs,jersey-2.0
I have the below JSON code that needs to be parsed. I'm using the corresponding JAX-RS models. The problem is that the paymillClient object is null. If I add currency as a string inside the PaymillSubscription object, it returns EUR value, not null. So there appears to be a problem...

How to test a Java RESTful web service with curl - problems with PUT verb

java,rest,curl,jersey,jax-rs
I'm trying my first Java RESTful web service and probably I don't have clear some mechanisms. Here an example of my code: @Path(Paths.USERS) public class UserService { private static final String OK_MESSAGE_USERSERVICE_PUT = Messages.OK_MESSAGE_USERSERVICE_PUT; private Client esClient = ElasticSearch.getClient(); @GET @Produces(MediaType.APPLICATION_JSON) public String get(@QueryParam(QParams.ID) String id) { // TODO Authentication...

Access iriInfo in called Method

java,jax-rs,uri
This code works to access the uriInfo: @Path("/testing") public class Testing { @javax.ws.rs.core.Context UriInfo uriInfo; @POST @Path("/test2") @Produces(MediaType.TEXT_PLAIN) public Response test2( @FormParam("sessionId") String sessionId ) { String currentUserId = Utils.setup(sessionId); String accessPath = uriInfo.getAbsolutePath().toASCIIString(); System.out.println("The client used this URI to reach this resource method: " + uriInfo.getAbsolutePath().toASCIIString()); // Utils.test3("print this");...

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 log request body in JAX-RS client

logging,jax-rs,servlet-filters
I need to see my request body with a client JAX-RS request in order to verify that the serialization works correct and reuse the request for test clients like Postman. I know it's possible to activate logging with Jersey using for example resource.addFilter(new com.sun.jersey.api.client.filter.LoggingFilter());. However, I don't use Jersey or...

Resource not invoked after Jersery Request Filter

spring,jersey,jax-rs,jax-ws,servlet-filters
I have a two SpringServlets defined, one of which directs to a custom filter @WebServlet(urlPatterns = { "/" }, initParams = { @WebInitParam(name = "com.sun.jersey.config.property.packages", value = "com.x.y.resource"), @WebInitParam(name = "com.sun.jersey.api.json.POJOMappingFeature", value = "true") }) public class JerseyServlet extends SpringServlet { } @WebServlet(name = "secure", urlPatterns = "/secure/*", initParams =...

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

Jax-rs http header range

rest,http-headers,jax-rs,resteasy
I want to use the http header 'Range' in a Jax-rs application, can I define a unit for this? for example, number of records. What I want to implement is to limit the number of records returned in the response to the maximum value of the 'Range'...

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

Best way redirect REST service request on glassfish + JAX-RS to https URL?

rest,glassfish,jax-rs
I have implemented a REST service on glassfish4 + JAX-RS. Now I want use a https connection for authentication. The URI for http is http://myhost/myapp/services/rest/myservice and for https is https://myhost_2/myapp/services/rest/myservice. I want prevent the usage of http://myhost/myapp/services/rest/myservice. I think one way is redirect a request over http://myhost in the REST...

Simple JavaEE HTML GET/POST application

java,java-ee,intellij-idea,glassfish,jax-rs
I'm just starting out with JavaEE (I'm decently fluent in JavaSE) and am having trouble wrapping my brain around all the new things that are required to make even the simplest of applications. Right now I am trying to use JAX-RS annotations to generate a simple "Hello World" html page...

Unsupported Content-type:application/json in java webservice call

java,java-ee,jax-rs,jax-ws
I am able to set content type using cxf library but I don't know how to set Authorization header. Whenever I set user name and password then it set Authorization header and encode whole value and add Basic. I don't want to do this. I want to add Authorization header...

JAX-RS service throwing a 404 HTTPException but client receiving a HTTP 500 code

java,jax-rs
I have a RESTful resource, which calls a EJB to make a query. If there is no result from the query, the EJB throws a EntityNotFoundException. In the catch block, it will be thrown a javax.xml.ws.http.HTTPException with code 404. @Stateless @Path("naturezas") public class NaturezasResource { @GET @Path("list/{code}") @Produces(MediaType.APPLICATION_JSON) public String...

Jax-RS overloading methods/paths order of execution

regex,api,rest,jax-rs
I am writing an API for my app, and I am confused about how Jax-RS deals with certain scenarios For example, I define two paths: @Path("user/{name : [a-zA-Z]+}") and @Path("user/me") The first path that I specified clearly encompasses the second path since the regular expression includes all letters a-z. However,...

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

(Java) if statement optimization

java,rest,annotations,jax-rs,sonarqube
Need to optimize this code : import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; ... private String valueParam(Annotation a) { String value = ""; if (a.annotationType() == QueryParam.class) { value = ((QueryParam) a).value(); } else if (a.annotationType() == PathParam.class) {...

JAX RS get list of objects

java,json,jax-rs
Trying to play with JAX RS i want to implement CRUD operations with my data. First of all i want to get list of objects in json formate. @Path("/users") public class ListUsersRestController { @GET @Produces("application/json") public List<User> getUsers(){ List<User> users = new ArrayList<>(); users.add(new User("Dean", "Winchester")); users.add(new User("Sam", "Winchester")); users.add(new...

How to define model to unmarshall post data without root element name

spring,rest,jaxb,cxf,jax-rs
I have a REST API which gets following in post request body to create that data in back end: { "key": "mykey30", "value": "my long value" } and this is how I defined my model: @XmlRootElement public class Entity { private String key; private String value; } and this is...

How to write single JAX-RS resource for variable number of path parameters

java,rest,jax-rs,apache-wink
I have been writing a JAX-RS based ReST application using Apache Wink and I understood the concept of association between path params to resource handle class. Here I see that, We can define paths using @Path annotation and corresponding resource which will get called based on HTTP Method.. Now I...

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

Passing parameters to a url

java,javascript,jsp,jax-rs
I'm calling a jsp page through an jax-rs endpoint as below. public String logout(@Context HttpServletRequest request,@DefaultValue("Empty Details") @QueryParam("logoutNotification") String logoutNotification, @QueryParam("id_token_hint") String id_token_hint) { Response response= Response.status(200).entity(logoutNotification).build(); if(response.getEntity().toString().equals("True")){ return "<html><head><script>\n" +...

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

Request-scoped context field injections into RESTEasy singletons

jax-rs,resteasy
While trying to embed RESTEasy with singleton resources in OSGi (using something similar to resteasy-osgi-bundle), to my surprise field-injected @Context UriInfo was available and valid on each request. Digging deeper I found proxy magic and ThreadLocal in ResteasyProviderFactory. All well and good, but I cannot find any reference to such...

How to set username and password using Rest easy client builder?

java,http,http-headers,jax-rs,resteasy
I have a url which needs authentication (like a browser pop up appears asking username and password.) Generally, we can use the following format to achieve this: http://username:[email protected] Using Rest easy client builder Client client = ClientBuilder.newClient(); WebTarget target = client.target('http://url.com'); How to achieve it without having to construct the...

JAX-RS / JAXB : equals()

java,xml,web-services,jaxb,jax-rs
I'm creating a little webservice with JAX-RS and I cannot access to my GET request http://localhost:8080/MyProject/resources/agenda/{jour} Here is my code : package com.project.test; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import javax.ws.rs.DefaultValue; import javax.ws.rs.PathParam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.xml.bind.annotation.*; @XmlRootElement(name = "activite") @XmlAccessorType(XmlAccessType.FIELD)...

How to configure Jersey (javax.ws.rs.*) to reuse ssl sessions

java,ssl,jax-rs,jersey-2.0,keep-alive
I have written a test client that sends requests over TLS using the Jersey library. I am having a hard time trying to figure out how to configure/code the Jersey client such that it reuses the SSL sessions so that I could make my tests faster. The Jersey client by...

Is it okay to use same resource name for both get and post rest api

rest,jax-rs,restful-url,restful-architecture
Sometime back I developed a Restful service in Java with only 1 GET resource. It was accessed like this: GET http://localhost:8080/my-project/customers/transactions This GET request returns all the customer transactions. Now, I have another project request where they want to insert customer transactions in a different schema in same database. I...

HTTP 415 Unsupported Media Type

java,web-services,maven,jax-rs
I have created a sample web service to make a post call. I am using Jersey JAX-RS, and Maven. web.xml <servlet> <servlet-name>provider-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>org.is.ws.provider.rest.ProviderAggregateApplication</param-value> </init-param> <init-param>...

Getting Unsupported Media Type when trying to access POST Json consumer endpoint developed using Jersey

java,json,jersey,jax-rs,postman
I am getting this error when I try to execute my POST webservice methods: I am using Postman to send the request: My entity is below: @Entity @XmlRootElement @Table(name = "bandeiras") public class BandeiraCartao extends EntidadeBase { private static final long serialVersionUID = 5944226798248177637L; @XmlElement @Column(length = 60, nullable =...

Creating a cookie inside a jax-rs endpoint

java,cookies,jax-rs,endpoint
I have a jax-rs endpoint. The purpose of the endpoint is to authorize a user. I need to login details inside a cookie. Below I have mentioned the related part of my code. public Response authorize(@Context HttpServletRequest request) throws URISyntaxException { if (authnResult.isAuthenticated()) { //TODO create a cookie to maintain...

JAX-RS: performing an action after sending the response to the browser

java-ee,jax-rs
My objective is to perform an action after the RestFul service returns the response. I have the method below, but not sure when to do the action as once the method returns I have no control. Any ideas? @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/somepath") public javax.ws.rs.core.Response someMethod (final RequestObject req) { //...

In which container do JAX-RS web services run?

java,rest,tomcat,java-ee,jax-rs
As of my understanding java EE application servers have mainly two types of containers. Namely web container and EJB container. I managed to run a JAX-RS application which used Jersey as its implementation, in Tomcat. As I know Tomcat is only a web container. In order to run the web...

Inject @ViewScope cdi bean into JAX-RS resource

jsf,jsf-2,jax-rs,cdi,omnifaces
I'm using MyFaces Apache 2.0.3 JSF, WAS 8.0.0.10 Currently I'm trying to inject an @ViewScope cdi bean, @ViewScope in JSF 2.0 provided by OmniFaces's library. But I get an error: WebBeans context with scope type annotation @ViewScoped does not exist within current thread. When I try to inject an @SessionScope...

JAX-RS Custom JSON representation of primitive Resource return type

java,java-ee,jax-rs
Suppose we have a service with the following contract: public interface CategoryService { public int createNew(String languageCode, String name, String descriptionMarkdown, Integer parentCategoryID, String createdByUserName) throws ServiceException; }; How do I map the int return type to produce a JSON value like the following? PS: I know that the createNew...

Is Tomcat a JAX-RS aware Servlet Container

java,rest,tomcat,web,jax-rs
From the textbook "RESTful Java with JAX-RS" we can read: If our application server is JAX-RS-aware or, in other words, is tightly integrated with JAX-R declare our ShoppingApplication class as a servlet: <?xml version="1.0"?> <web-app> <servlet> <servlet-name>Rest</servlet-name> <servlet-class> com.restfully.shop.services.ShoppingApplication </servlet-class> </servlet> <servlet-mapping> <servlet-name>Rest</servlet-name> <url-pattern>/*</url-pattern>...

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

Using web proxy with Java 8 JAX-RS RESTEasy clients

eclipse,jax-rs,resteasy,http-proxy
I can't seem to get JAX-RS clients to use a web proxy on Java 8. I'm using RESTEasy 3.0.10.Final, and running from inside Eclipse 4.4.2 on Windows 7 Professional 64-bit. I set up a FreeProxy server on localhost running at 192.168.1.123:3128. I turn logs on and telnet to 192.168.1.123 3128...

Dependency Injection in jersey 2.17

java,jax-rs,cdi,jersey-2.0
I have a resource class @Path("/rest") public class DemoResourceController { @Inject DemoService demoService; @Path("/get/demo") @GET @Produces(APPLICATION_JSON) public Response getDemoLists() { List<String> demoList=demoService.getDemoList(); return Response.ok(demoList).build(); } I tried the answers in the post Dependency injection with Jersey 2.0 if i use compile group: "org.glassfish.jersey.ext.cdi" , name: "jersey-cdi1x" , version: "2.17" compile...

Cannot find symbol PathParam in Jersey

java,maven,jersey,jax-rs
Here's my code @Path("/users/{id}") public class MyResource { @GET @Produces(MediaType.TEXT_PLAIN) public String getId(@PathParam("id") String id) { return "Getting Messages for User : " + id; } } All i get is ..MyResource.java:[17,29] error: cannot find symbol So far i have checked both this https://confluence.atlassian.com/display/CLOVERKB/Maven+2+plugin+fails+with+cannot+find+symbol+exception+when+defining+two+locations+for+source+files & this maven "cannot find symbol"...

Jersey 2 POST and PUT parameter is null

java,jax-rs,jersey-2.0
I have a problem with my jersey rest service when method is PUT or POST. The problem is that parameter is null. I test with angularjs and jersey-test-framework with same result, the parameter is null. I thought the problem was due to the header "Content-Type" but I add this in...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

grails,groovy,jax-rs
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Javascript inside a java code

java,javascript,jax-rs
I need to write a jax-rs endpoint which returns a javascript function. I know that we can write java codes inside javascript. But I don't know weather we can write a javascript code inside a java code. But my supervisor asked me to write it. Any help is appreciated. Thanks...

Preventing infinite recursion in JAX-RS on JPA Entity Serialization (JSON) (without using Jackson annotations)

java,jpa,jackson,jax-rs,resteasy
I have an Entity as follows: @XmlRootElement @Entity @Table(name="CATEGORY") @Access(AccessType.FIELD) @Cacheable @NamedQueries({ @NamedQuery(name="category.countAllDeleted", query="SELECT COUNT(c) FROM Category c WHERE c.deletionTimestamp IS NOT NULL"), @NamedQuery(name="category.findAllNonDeleted", query="SELECT c from Category c WHERE c.deletionTimestamp IS NULL"), @NamedQuery(name="category.findByCategoryName", query="SELECT c FROM Category c JOIN c.descriptions cd WHERE LOWER(TRIM(cd.name)) LIKE ?1") }) public class Category...

JAX-RS: Jersey + Genson = MessageBodyProviderNotFoundException

java,glassfish,jersey,jax-rs,genson
I am developing RESTful web service using JAX-RS (Jersey) and Glassfish as server. I implemented simple method that returns list of entites and when I attempting to access it server drops 500 error with org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json. I tried to add Genson lib to my project...

Netbeans 8.0.2 project with Jersey and Jackson

java,json,jersey,jackson,jax-rs
I have a Netbeans project in 8.0.2. For various reasons, I am not using Maven. I have some REST resource methods that return Map and some that return a complex POJO. These are to be converted to JSON. From reading around, I gather that the Moxy default plugin cannot stream...

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

HATEOAS Link using UriBuilder

java,rest,jax-rs,hateoas
I have a REST service defined as below: @Path("/v1/employee/") EmployeeService { @Path("/designation/") public void listDesignation() { } } My goal is to generate the relative URL "v1/employee/designation/". If I use UriBuilder.fromResource(EmployeeService.class), it gives me "/v1/employee/" And if i use UriBuilder.fromMethod(EmployeeService.class, "listDesignation"), it gives me "/designation" Does anyone know how I...

Cannot access services after adding corsfilter in resteasy

java,jax-rs,resteasy
I cannot access any of my services after adding corsfilter to my ApplicationPath this is the example import java.util.HashSet; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import org.jboss.resteasy.plugins.interceptors.CorsFilter; @ApplicationPath("/") public class JaxRsActivator extends Application { private Set<Object> singletons = new HashSet<Object>(); private Set<Class<?>> classes = new HashSet<Class<?>>(); public JaxRsActivator() { CorsFilter...

load on startup and Jersey

java,tomcat,servlets,jersey,jax-rs
Possibly duplicate of Servlet not loading on startup, however Im not allowed yet to comment, so I have to start a new question for this... Same setting, having a servlet using Jersey and Tomcat, using load-on-startup for loading the container. However, due to the thread mentioned above, I understand that...

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

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

JAX-RS service always replies with 415 Unsupported Media Type error to POST requests

java,json,rest,jax-rs
I know (quite) similar questions was asked numerous times, but solutions to them didn't work for me. I'm creating a REST service with JAX-RS and Jersey 2 which consumes json beans from post requests, it looks like this: @Path("auth") public class AuthService { @Inject private AuthenticationManager authenticationManager; @POST @Path("login") @Consumes(MediaType.APPLICATION_JSON)...

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

JAX-RS and @Produces ability to match on regex

jax-rs
I'm writing a Restful web service that requires versioning. The way I want to go about this is using the Media type in the header to do this. Example of request: Accept: application/vnd.test.books.v1+xml I would have an endpoint of @GET @Path("/test") @Produces("application/vnd.test.books.v1+xml") public Response getA(){ ... } I would also...

JAXRS 2.0 Client: FOLLOW_REDIRECTS property doesn't work

java,rest,jax-rs,jersey-client
I'm trying to get autoredirects to work in Jersey Client 2.0. Here is my code: ClientConfig cc = new ClientConfig().property(ClientProperties.FOLLOW_REDIRECTS, true); Client c = ClientBuilder.newClient(cc); WebTarget wt = c.target("some_path"); SystemInfo info = wt.request(MediaType.APPLICATION_XML_TYPE).get(SystemInfo.class); Server sends HTTP 302 with an another URL in Location header as expected. I assume that according...

How are Jersey @Consumes endpoints matched?

java,rest,jersey,jax-rs,jersey-2.0
I am designing a RESTful endpoint to receive files. I would like to it to accept POSTing as both plain file/stream and multipart. Is there a rule how are endpoints matched by the servlet container? Would the code below work reliably, or is this implementation specific? Can I get away...

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

JAX-WS @WebService on RESTful web-service endpoint

java,jax-rs,jax-ws,ejb-3.0
Some time ago in one of the projects I found @WebService annotations on some of the jersey root(@Path) resource classes. As far as I understood at the time it was some legacy code or simply a misused JAX-WS annotation. Recently I stumbled upon this post in which mixing JAX-RS service...

Use header in addition to method to route request to annotated method

java,rest,jax-rs
I wonder if it's possible with JAX-RS to route a request using an header in addition to the HTTP method. In fact, I can't find out the way to do that. I thought about something like that where x-header is an header: @Path("/contacts/") public class MyResource { @POST @Header("x-header:content1") public...

Ignoring incoming json elements in jax-rs

json,jaxb,jax-rs
I'm wondering where to put the @JsonIgnoreProperties(ignoreUnknown = true) in a Java REST API. I have the following class: import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.ObjectMapper; @JsonIgnoreProperties(ignoreUnknown = true) public class QueuePayload { private String message; private String id; public String getId() { return this.id; } public String getMessage() { return this.message; }...

Document @ApiOperation with long detailed description

jax-rs,swagger,swagger-ui
While documenting an operation using @ApiOperation, there is the notes atribute for a long description of the operation. But putting a long description in the annotation makes it cumbersome and difficult to mantain. Is there a more elegant option to reference an external file or something?...

How to configure wildfly to use https with ClientBuilder in resteasy?

java,ssl,jax-rs,resteasy,wildfly
This is the first time every I got the requirement to connect to https url. Within no time, I came to know that I need SSLContext to be passed. I also came to know that I need to configure in standalone.xml to get it done. Any pointers towards the solution/link,...

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

JavaEE Web JAX-RS: can i use instance variables inside it's class?

java,thread-safety,jax-rs
I'm looking for thread-safe Servlet alternative and I've found JAX-RS technology. So can i use instance variables inside it's class like this (is it thread safe): @Path("helloworld") public class HelloWorldResource { private String msg; @GET public void doSmth() { this.msg = "test"; } } ?...

Polymorphism in RESTFul server

java,rest,jersey,jax-rs
I have 3 classes. A is abstract class, B and C extends A. I want to be able to get a JSON in a POST (A) and then to decide what type it is and to convert to the correct type. in other words to use only one end point...