Menu
  • HOME
  • TAGS

JAX-RS and @Produces ability to match on regex

jax-rs

You must explicitly list all the MIME types a method @Produces: @Produces(value = {"application/vnd.test.books.v2+xml", "application/vnd.test.books.v3+xml", "application/vnd.test.books.v4+xml"}) ...

JAX-WS @WebService on RESTful web-service endpoint

java,jax-rs,jax-ws,ejb-3.0

Exposing a JAX-RS bean as the methods of a SOAP WS using @WebService may be technically possible. It will not lead to a good API design. Consider some very common JAX-RS methods: @GET @Path("/foos") @Produces("application/json") public Response getFoos() { // get all Foos List<Foo> foos = ...; return Response.ok(foos).build(); }...

Reading from a JDBC Blob after leaving the Spring transaction

jax-rs,blob,spring-transactions

I've spent some time now debugging the code, and all my assumptions in the question are more or less correct. The @Transactional annotation works as expected, the transaction (both the Spring and the DB transactions) are commited immediately after returning from the download method, the physical DB connection is returned...

Cannot find symbol PathParam in Jersey

java,maven,jersey,jax-rs

I was looking at your pom.xml in your link, and it looks like you are using a Maven archetype that I am familiar with. The code you've posted is the only class provided by the archetype. Only difference is, your addition of the @PathParam (and the change of path). In...

How to log request body in JAX-RS client

logging,jax-rs,servlet-filters

JAX-RS 2.0 (which it looks like you're using), has the ClientRequestFitler. You can register it with the Client or even the WebTarget. From the filter method, you can get the entity, and do your logging public class LoggingFilter implements ClientRequestFilter { private static final Logger LOG = Logger.getLogger(LoggingFilter.class.getName()); @Override public...

Cannot access services after adding corsfilter in resteasy

java,jax-rs,resteasy

Once you override the getSingeletons() or getClasses() and return a non-empty set in either of them, you disable the automatic registering through classpath scanning. Since you have done so, your resources are no longer registered. You can see one way to overcome that problem, in this answer, which uses a...

JAX RS get list of objects

java,json,jax-rs

The problem is here: @XmlRootElement public class User { ... } Your User class now is an inner class of ListUsersRestController and it seems that JAXB fails to marshall inner classes (because they are more like an instance member of ListUsersRestController than a real class). Either externalize it to be...

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

java,rest,jaxb,jax-rs

You could... Inject with @HeaderParam("Accept") public Response doSomething(@HeaderParam("Accept") String accept) { // you may need to parse it as the value is not always as // simple as application/json } You could... Inject HttpHeaders, where you have a couple options public Response doSomething(@Context HttpHeaders headers) { String accept = headers.getHeaderString(HttpHeaders.ACCEPT);...

Ignoring incoming json elements in jax-rs

json,jaxb,jax-rs

Problem seems to be the server uses Jackson 1.x (codehaus). You are trying to use Jackson 2.x annotations (fasterxml). They don't interact. You can tell by the exception that it's a codehaus exception, meaning the older Jackson is actual used. You can look in the server an try and find...

database access using jersey RESTful API

java,mysql,jax-rs

REST is a acces layer if you look at the specification. So to acces a database you should probebely need to use JPA implmentation like Hibernate, for that you need a implementation depending on the vendor of your database.

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

java,hibernate,jersey,jax-rs

In this case we generally send a 404. The URL is the identifier for the resource. If part of the URL is used as an identifier for determining the resource, then the appropriate reply for a resource not being found by that identifier, is a 404 Not Found. Generally, personally...

Document @ApiOperation with long detailed description

jax-rs,swagger,swagger-ui

There isn't right now, no. At best, I could recommend using a string constant as an input to the @ApiOperation and keep it elsewhere to avoid the clutter. Another option would be to use the externalDocs if you're on swagger-core 1.5.

JEE can't run JAX-RS WebService skeleton app

java,maven,glassfish,jersey,jax-rs

Glassfish 4 uses Jersey 2.x. You should change the dependency and web.xml configuration accordingly. For the dependency, you can use <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>${jersey2.version}</version> <scope>provided</scope> </dependency> And configuration <servlet> <servlet-name>jersey-serlvet</servlet-name>...

Jax-rs http header range

rest,http-headers,jax-rs,resteasy

For parsing more complex Parameters you can implement a ParamConverter: @Provider public class RangeHeaderConverter implements ParamConverter<RangeHeader> { @Override public RangeHeader fromString(String value) { return RangeHeader.fromValue(value); } @Override public String toString(RangeHeader value) { return value.toString(); } } The implementation of your RangeHeader might look like this: public class RangeHeader { public...

Jersey JUnit Test: @WebListener ServletContextListener not invoked

java,rest,junit,jersey,jax-rs

The JerseyTest needs to be set up to run in a Servlet environment, as mentioned here. Here are the good parts: @Override protected TestContainerFactory getTestContainerFactory() { return new GrizzlyWebTestContainerFactory(); } @Override protected DeploymentContext configureDeployment() { ResourceConfig config = new ResourceConfig(SessionResource.class); return ServletDeploymentContext.forServlet(new ServletContainer(config)) .addListener(AppContextListener.class) .build(); } See the APIs for...

(Java) if statement optimization

java,rest,annotations,jax-rs,sonarqube

If reflection is an option, you can always do something like public class Test { @PathParam("path") public Response doSomething() { return null; } public static void main(String[] args) throws Exception { Method method = Test.class.getMethod("doSomething"); Annotation annotation = method.getAnnotations()[0]; System.out.println(getValue(annotation)); } private static String getValue(Annotation annotation) throws Exception { Class<?>...

Setting response header using interceptor?

java,java-ee,jax-rs,resteasy,interceptor

With JaxRS 2 (which comes with javaEE 7) you can use a ContainerResponseFilter see also public class PoweredByResponseFilter implements ContainerResponseFilter { @Inject HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String name = "X-My-Header"; String value = "";// some data from request responseContext.getHeaders().add(name, value); } }...

Java Jersey PathParams Checking and NotFoundException custom message

java,rest,exception-handling,jax-rs,jersey-2.0

Question 1 Yes. The problem is your use of == to compare Strings. You should instead be using String.equals(). See How do I compare Strings in Java? if ("[email protected]".equals(email) || "wrong".equals(requestNumber)) { throw new NoRoomApplicationFoundException("bad request"); } Question 2: This question seems to be related to your first question. But...

Exception in the allocation for the servlet

java,angularjs,rest,jersey,jax-rs

There are so many things wrong on so many levels There is no such word as "Authentification". It's "Authentication" :-) @ApplicationPath should be used on the application configuration class, not on your resource classes. For example @ApplicationPath("/rest") public class AppConfig extends PackagesConfig { public AppConfig() { super("the.packages.to.scan.for.resources.and.provders"); } } With...

rest jax-rs : server error

java,web-services,rest,jax-rs

The only problem I faced was this exception ...IllegalAnnotationsException... Activite does not have a no-arg default constructor. To fix it I simply added a no-arg constructor in the Activite class. Also, you may not face this problem with your GET request, but with POST request, when you try and send...

how to see actual body sent from restassured

jax-rs,wildfly,rest-assured

I'm not a RestAssured used, so I can't answer your question directly, but here are some ideas that may help you out. I don't know what serializer RestAssured uses under the hood, but Resteasy on Wildfly uses Jackson by default. I would get familiar with this library. For less trivial...

Comparing if two list of strings are equal using hashcode?

java,java-ee,collections,jax-rs

Is this approach correct? The approach is correct, but the proposed implementation is not (IMO). I assume that "summing with 31" means something like this int hash = 0; for (String name : names) hash = hash * 31 + name.hashCode(); Java hashcode values are 32 bit quantities. If...

AbstractMethodError using UriBuilder on JAX-RS

java,maven,jersey,jax-rs

AbstractMethodError are thrown when an application tries to call an abstract method. uri is an abstract method in UriBuilder, so you need an implementation of this. This method (with String parameter) is from version 2.0 of JAX-RS specification. You're trying to use JAX-RS 2.0 with Jersey 1.*. Instead, you need...

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

java,thread-safety,jax-rs

Resource scope will default to @RequestScope so a new instance of your resource will be created per request. From Chapter 3. JAX-RS Application, Resources and Sub-Resources @RequestScoped Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for...

Jersey JAX-RS 3 level nested object has null value

jaxb,jersey,jax-rs,jersey-2.0

Ok. I tried to run your code on your machine and also received null (note, that I'm using MOXy to unmarshall JSON). Then, I tried to experiment with it a little and found really funny things: 1. If you will remove all null-valued fields from your JSON, all works just...

Dropwizard: Passing custom type query parameter

java,rest,jersey,jax-rs,dropwizard

Take a look at the @QueryParam documentation, in regards to acceptable types to inject. (The same applies to all the other @XxxParam annotations also) Be a primitive type Have a constructor that accepts a single String argument Have a static method named valueOf or fromString that accepts a single String...

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

java,unit-testing,jax-rs,jersey-2.0,grizzly

You simply inject it with the @Context annotation, as a field or method parameter. @Path("resource") public class Resource { @Context UriInfo uriInfo; public Response doSomthing(@Context UriInfo uriInfo) { } } Other than your resource classes, it can also be injected into other providers, like ContainerRequestContext, ContextResolver, MessageBodyReader etc. EDIT Actually...

Dependency Injection in jersey 2.17

java,jax-rs,cdi,jersey-2.0

In your second attempt (without the cdi dependencies; using HK2) your binding is incorrect. It should be bind(Implementation).to(Contract) // - i.e. bind(DemoServiceImpl.class).to(DemoService.class); You have it the other way around. As far as testing, if you have the test in same package (in the test area of the project) you should...

How to get the response header in a RestEasy client?

java,rest,jax-rs,resteasy

The best solution i found was to use a Filter to process the incoming response header. public class HeaderFilter implements ClientResponseFilter { private Map<String, String> headers = new HashMap<>(); private List<String> headerFilter = new ArrayList<>(); public final void addHeaderFilter(final String header) { headerFilter.add(header); } public final void removeHeaderFilter(final String header)...

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

java-ee,jax-rs

You can't. Java doesn't work that way. Just trigger an @Asynchronous service call. It'll immediately "fire and forget" a separate thread. @EJB private SomeService someService; @POST @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @Path("/somepath") public Response someMethod(RequestObject request) { // ... someService.someAsyncMethod(); return Response.status(200).entity("response").build(); } @Stateless public class SomeService { @Asynchronous public void someAsyncMethod() {...

How can I negotiate which post method will be called?

api,rest,jax-rs,resteasy

I think i have done using two different MessageBodyReaders Object1MessageReader implements MessageBodyReader<Object1>{ } Object2MessageReader implements MessageBodyReader<Object2>{ } Class MyResource { postXML(Object1 obj) { ... } postJSON(Object2 obj) { ... } } ...

Passing parameters to a url

java,javascript,jsp,jax-rs

I dont have much knowledge on RESTful webservices. But in an url if you want to pass paramters it can done as <url URL>?par1=val1&par2=val2 If your code opens a new window then this will work. I hope so this would help you. Example: https://localhost:9443/carbon/authenticationendpoint/test.jsp?name=Joe&age=24...

JavaEE Web JAX-RS: how to match Query params

java,filter,jax-rs

You are not allowed to specify regex for QueryParams. As a workaround: just define your own Java data type that will serve as a representation of this query param and then convert this to String if you have to deal with Strings

Is Tomcat a JAX-RS aware Servlet Container

java,rest,tomcat,web,jax-rs

"Is Tomcat a JAX-RS aware Servlet container?" No. "How do you distinguish a servlet container JAX-RS aware from one wich is not JAX-RS aware?" The fact this it is only a Servlet container, should tell you that it is not "JAX-RS aware". JAX-RS is part of the Java EE...

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

java,web-services,jax-rs,jax-ws

I guess one cannot, since the value isn't available in the compile time.

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

java,rest,jax-rs,apache-wink

You can use a regex, like @Path("/college/{param: .*}"), then use List<PathSegment> as a method parameter. For example @GET @Path("/college/{params: .*}") public Response get(@PathParam("params") List<PathSegment> params) { StringBuilder builder = new StringBuilder(); for (PathSegment seg: params) { builder.append(seg.getPath()); } return Response.ok(builder.toString()).build(); } C:\>curl -v http://localhost:8080/college/blah/hello/world/cool Result: blahhelloworldcool But personally, I would...

HATEOAS Link using UriBuilder

java,rest,jax-rs,hateoas

You can use your UriBuilder#fromResource(Class), then chain a call to path(Class, String) (class, method name) or path(String) (actual path) or path(Method) (actual method if you have it).

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

java,jax-rs

javax.xml.ws.http.HTTPException is for JAX-WS. JAX-RS by default doesnt know how to handle it unless you write an ExceptionMapper for it. So the exception bubbles up to the container level, which just sends a generic internal server error response. Instead use WebApplicationException or one of its subclasses. Here a list of...

HTTP Status 415 - Unsupported Media Type when doing POST

spring,rest,java-ee,jersey,jax-rs

Yeah so as I suspected, the FormMultivaluedMapProvider (which handles MultivaluedMap reading for application/x-www-form-urlencoded Content-Type only allows for MultivaluedMap<String, String> or MultivaluedMap, not MultivaluedHashMap, as you have. Here is the source for the isReadable (which is called when the runtime looks for a MessageBodyReader to handle the combination of Java/Content-Type types....

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

rest,jax-rs,restful-url,restful-architecture

Restful when is used with HTTP depends in the resources(URL's) and rely the actions the HTTP verbs, it is common and good practice used this verbs to identify some operations over the resources you have: GET retrieve all or just one resource. POST is normally for create a new resource....

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

java,json,rest,jax-rs

From comment (just to have an answer... see comments for discussion) Artem Zhirkov: I explicitely registered JacksonJsonProvider with ResourceConfig and it solved the problem ...

JAXRS 2.0 Client: FOLLOW_REDIRECTS property doesn't work

java,rest,jax-rs,jersey-client

After some investigations I found that Jersey Client is not responsible for the problem. Its a general Java HttpURLConnection behaviour (or better to say security limitaion) if Location header of the response has some another scheme, than originated URL. So, if request redirects in some manner (response code 3xx) to...

Request-scoped context field injections into RESTEasy singletons

jax-rs,resteasy

It's not experimental. This behavior (for a set of common objects) is specified in the JAX-RS spec. There aren't any anchors in the spec page to link to a certain section, but where you should look is Chapter 5: Context. I'll post some snippet here. 5.1 Concurrency Context is specific...

EJB injection not working in different classes

java-ee,netbeans,jersey,ejb,jax-rs

You're creating an ActivityManager yourself, using new ActivityManager(). So the basic rules of Java apply: the constructor is called, and since it doesn't affect any value to activityfacade, this field is set to null. For dependency injection to happen, you can't create the objects yourself, but get them from the...

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

java,jpa,jackson,jax-rs,resteasy

Yes. Create a dedicated data structure, the representation data structure and map the JPA entity to the data structure. You're mixing concerns and this usually ends up badly. JPA entities are your API towards your data structure, REST representations are your API towards REST.

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

How our objects are serialized and deserialized to and from the response stream and request stream, is through MessageBodyWriters and MessageBodyReaders. What will happens is that a search will be done from the registry of providers, for one that can handle JSONObject and media type application/json. If one can't be...

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

eclipse,spring,web-services,jax-rs

Maven projects come with a bunch of plugins applied implicitly to the build. One of them being the maven-compiler-plugin. Unfortunately the Java version for the plugin defaults to 1.5. Most Maven project you see will override the Java version simply by declaring the plugin (in your pom.xml file) and configuring...

Using web proxy with Java 8 JAX-RS RESTEasy clients

eclipse,jax-rs,resteasy,http-proxy

The ResteasyClientBuilder provides a method to define the defaultProxy: ResteasyClient client = new ResteasyClientBuilder().defaultProxy("localhost", 8080, "http").build(); ...

Creating a cookie inside a jax-rs endpoint

java,cookies,jax-rs,endpoint

You can create a javax.ws.rs.core.NewCookie. There are a bunch of different constructors, just go through the API docs. Then you can add cookies through ResponseBuilder#cookie(NewCookie). So for example: @GET public Response getCookie() { NewCookie cookie = new NewCookie("Name", "Value", "path", "domain", "comment", 300, true, true); ResponseBuilder builder = Response.ok("Cool Stuff");...

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

java,rest,jersey,jax-rs

The interface was right all along I can't believe it was this easy: import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/service") @Produces("application/json") public interface ServiceInterface { @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first, @QueryParam("queryB") String second); } Notice anything different than the questions interface?? Nope. That's because that...

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 tried just adding a simple JEE servlet to collect the parameters and create the session object, but then I couldn't figure out how to inject that session object for use throughout the application. You could inject the current request object to your rest service and retrieve the...

Pass Multiple parameters in a REST call

rest,jersey,jax-rs

here is how I'll do it SERVER CODE 1.1 should have to use @FormParam in order to declare parameters in @FormDataParam 1.2 a POST is better if encrypted for that use @Consumes(MediaType.MULTIPART_FORM_DATA) you will have a server code like this : @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("/getMapping") public ListResponse getMapping(@FormParam("id")Long id, @FormParam("name") String...

restlet post getFirstValue always returns null

java,rest,jax-rs,restlet

In fact, if you look at the content type of the data you send within your request, this corresponds to a multipart content and not a URL-encoded form. The code you use within your server resource only applies to URL-encoded form (content-type application/x-www-form-urlencoded). So it's normal that you can get...

Find Jersey Parent Path

java,jersey,jax-rs

Get the base URI (which assuming is http://example.com/api) from UriInfo.getBaseUriBuilder(), then append the XxxResource path with builder.path(XxxResource.class). Then from the built URI, return Response.seeOther(uri).build();. Complete example: @Path("/v1/resource") public class Resource { @GET public Response getResource() { return Response.ok("Hello Redirects!").build(); } @POST @Path("/field") public Response getResource(@Context UriInfo uriInfo) { UriBuilder uriBuilder...

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

java,http,http-headers,jax-rs,resteasy

Looks like Basic Authentication. If that's the case, you just need to set the Authorization header to Basic base64encode(username:password) For example String credentials = "username:password" String base64encoded = Base64.getEncoder().encodeToString(credentials.getBytes()); Response response = target.request() .header(HttHeaders.AUTHORIZATION, "Basic " + base64Encoded).... The Base64 class I used is from Java 8. If you're not...

HTTP 415 Unsupported Media Type

java,web-services,maven,jax-rs

I deleted all my dependency code in pom.xml and added following code which has jersey-core, jersey-bundle, jersey-json <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-bundle</artifactId> <version>1.19</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.19</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId>...

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

java,json,web-services,jax-rs

Well, that's not how JAX-RS marshall your response, that's how JavaScript works. Try something like this in console: var a = 2.0; console.log(a); You will see 2 as an output. Should be part of ECMA specification, but I cannot find exact place. If you want, you could use toFixed method...

Resource not invoked after Jersery Request Filter

spring,jersey,jax-rs,jax-ws,servlet-filters

I have solved the problem, but I am not 100% sure if my solution is the correct way to do it. I have changed the annotation on the filtered serlvet to be @WebFilter, giving me @WebServlet(urlPatterns = { "/*" }, initParams = { @WebInitParam(name = "com.sun.jersey.config.property.packages", value = "com.x.y.resource"), @WebInitParam(name...

How are Jersey @Consumes endpoints matched?

java,rest,jersey,jax-rs,jersey-2.0

This is specified in the JAX-RS spec 3.7.2 Request Matching [...] Resource class/object is found and all resource and sub resource methods are put into set M [...] Identify the method that will handle the request: a. Filter M by removing members that do not meet the following criteria:     [...]...

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

java,jersey,jackson,jax-rs

Have you considered simply making Interface generic? Something like public abstract class SuperType {} public class SubType extends SuperType {} public interface Resource<T extends SuperType> { Response doSomething(T type); } @Path("resource") public class SubTypeResource implements Resource<SubType> { @POST @Override public Response doSomething(SubType type) { ... } } ...

@Context object not injected when unit testing resteasy

java,unit-testing,jboss,jax-rs,resteasy

I found a solution based on this answer. In my LocaleProvider instead of dispatcher.getDefaultContextObjects().put(Locale.class, locale); I needed to use ResteasyProviderFactory.pushContext(Locale.class, locale); Hope it helps someone :)...

Jersey: Can I add a cookie in ContainerResponseFilter?

cookies,jersey,jax-rs,servlet-filters

Yeah seems a bit odd that this is not allowed. Not sure why this is not allowed. I've tested both with Jersey and Resteasy. With Resteasy, all that happens is that the cookie is not set (no Exception). I'm thinking some operation sets the cookies as headers, and by the...

MultiException when custom jersey param throws exception

java,jax-rs,jersey-2.0,dropwizard

Question 1 According to dropwizard's core documentation, I see two possible implementations for input validation: through validation annotation you can add validation annotations to fields of your representation classes and validate them... This doesn't seem to be suitable for your case. In fact, there is no available annotation for LocalDateTime...

load on startup and Jersey

java,tomcat,servlets,jersey,jax-rs

Default behavior is to instantiate a new instance of the resource class per request. In which case there isn't an expected need to load on start up. If you want this behavior, then your resource class needs to be a singleton, meaning only one instance is created for the whole...

How to implement JAX-RS RESTful service in JSF framework

jsf,servlets,jersey,jax-rs

This concern is unnecessary. You can safely have multiple servlets in a single web application, as long as their URL patterns do not clash with each other. Usually, if that were the case, a bit sane servlet container would already throw an exception during webapp's startup. In your case, you've...

Simple JavaEE HTML GET/POST application

java,java-ee,intellij-idea,glassfish,jax-rs

You need to configure Jersey (the JAX-RS implementation in Glassfish) in your web.xml. You currently only have JSF configuration <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>the.package.where.your.resources.are</param-value> </init-param>...

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

rest,jaxb,jersey,jax-rs

I was able to resolve the issue myself. This was because of having conflicting jars included in build path. Here is the snap for jar files. ...

Access iriInfo in called Method

java,jax-rs,uri

Continuing with my comment.. into an answer Like I said, you can't just decide to inject it anywhere you want. The class being injected into needs to be managed by the JAX-RS runtime, as it's the one that will be doing the injecting. A resource class is managed, a filter...

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

either use new ValidateToken.validate(... or make your validate method static. this is actually what the error is stating: No signature of method: static ....ValidateToken.validate() is applicable for argument types: () values: []` ...

JAX-RS / JAXB : equals()

java,xml,web-services,jaxb,jax-rs

"I've read plugin on Equals() class is the only one solution." I guess "plugin on" means override. If not, then that's you it should mean. You need to override it, and describe how the objects will be determined equal. (It should also be noted, when override equals, you should...

How to make Jersey Unit test for Post method

java,rest,junit,jersey,jax-rs

@Path("hello") public static class HelloResource { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String doPost(Map<String, String> data) { return "Hello " + data.get("name") + "!"; } } @Override protected Application configure() { return new ResourceConfig(HelloResource.class); } @Test public void testPost() { Map<String, String> data = new HashMap<String, String>(); data.put("name", "popovitsj"); final String hello...

Unable to consume Jersey Webservice

java,web-services,jax-rs,jax-ws,jersey-2.0

Be sure to have all following dependencies in your project : -jersey-container-servlet-core -jersey-media-json-processing -jersey-media-json-jackson create a configuration class for your rest webservice, you can also load your package to be scan by jersey in those class, instead in web.xml import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; public class Application extends ResourceConfig {...

Roadblock using generics in jax-rs rest services using jpa

java,jpa,jax-rs

I'm thinking you can just do some reflection on the TClass to get the type of the id field (assuming that's the common name of the "id" field) and just conditionally set the PK to check . Something like public T findById(String id) throws Exception { Field idField = TClass.getDeclaredField("id");...

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

java,java-ee,jax-rs,jax-ws

I think you are trying to call is a RestFul Service, so that's why the server side always response with a different content type than you expected (json instead of soap/xml). Is your url endpoint based on http protocol? If yes, do you need send additional parameters to this url?...

Why does QueryParam return null

java,jersey,jax-rs

The problem is you are trying to write to the body of the request, with wr.write("enc="+encData);. @QueryParams should be in the query string. So this instead would work public static void main(String[] args) throws Exception { sendPost(".../encRead", "HelloWorld"); } protected static void sendPost(String url, String encData) throws Exception { String...

Limit output payload response in CXF JAX-RS based service

java,spring,rest,cxf,jax-rs

I resolved this partially using help from this answer. I say partially because I'm successfully able to control the payload, but the not the response status code. Ideally, if the response length is greater than 500 and I modify the message content, I would like to send a different response...

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

java,ssl,jax-rs,jersey-2.0,keep-alive

I use the Apache connector for this: HttpClientConnectionManager connManager = PoolingHttpClientConnectionManager(); ClientConfig clientConfig = new ClientConfig(); clientConfig.connectorProvider(new ApacheConnectorProvider()); clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager); Client client = ClientBuilder.newClient(clientConfig); You can configure the HttpClientConnectionManager to your needs depending on how many connections you want to keep in the pool, and for how long you want...

How to disable common name check in SSLContext in java?

java,ssl,jersey,jax-rs,ssl-certificate

If I'm understanding you correctly, I think you can accomplish what you are trying to do by implementing a HostnameVerifier, and just returning true in the verify method. You can set up the verifier on the ClientBuilder. For example Client client = ClientBuilder.newBuilder() .sslContext(sslContext) .hostnameVerifier(hostnameVerifier) .build(); ...

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

spring,rest,jaxb,cxf,jax-rs

You just need to configure the JSONProvider. The property for marshalling (to unwrap) is setDropRootElement(boolean) The property for unmarshalling (allowing unwrapped) is setSupportUnwrapped(boolean) With xml config, you might have something like <jaxrs:server [...] > [...] <jaxrs:providers> <bean class="org.apache.cxf.jaxrs.provider.json.JSONProvider"> <property name="dropRootElement" value="true"/> <property name="supportUnwrapped" value="true"/> </bean> </jaxrs:providers> </jaxrs:server>...

Javascript inside a java code

java,javascript,jax-rs

you can return a string from your code and you can declare html tags as the returning String. I will suggest a sample code. @GET @Path("/") @Produces("text/html") public String getStatus(@Context HttpServletRequest request) { return "<html><head><script>put your java script code here...</script></head></html>" } ...

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

rest,glassfish,jax-rs

you could answer requests to http with 301 (Moved permanently, telling the client to use the new location in future requests) pointing to the https equivalent in the location header of the response.

How to make a jax-rs end point accept any type of http request?

http,jax-rs,resteasy

Short answer: Yes, you can annotate a method with @OPTIONS, @HEAD, @GET, @POST, @PUT, @DELETE and the resource method should be called on all of these methods. Long answer: You should not! Every HTTP method has it's semantic. A @GET is a 'safe' method because it is intended for reading...

In which container do JAX-RS web services run?

java,rest,tomcat,java-ee,jax-rs

"Does tomcat uses another implementation of JAX-RS other than Jersey?" I don't know if you're asking if Tomcat has an implementation or if it is capable of running other implementations beside Jersey. The answer to the former is no. Vanilla Tomcat does not support JAX-RS out the box. It...

JAX-RS @FormParam one time for all methods

java,web-services,java-ee,jax-rs,java-ee-6

This will filter the required parameters before processing. import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(urlPatterns = {"/*"}, description = "Filters!") public class MyFilter implements Filter { private FilterConfig filterConfig; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)...

Jax-RS overloading methods/paths order of execution

regex,api,rest,jax-rs

This is in the spec in "Matching Requests to Resource Methods" Sort E using (1) the number of literal characters in each member as the primary key (descending order), (2) the number of capturing groups as a secondary key (descending order), (3) the number of capturing groups with non-default regular...

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

java,rest,curl,jersey,jax-rs

I would completely refactor this solution. First: Change the url scheme to make the id part of the URI path. This is a more RESTful approach @PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) public String update(@PathParam("id") String id) { Second: The request entity body should be the JSON. I don't see any reason for...

JAX-RS Custom JSON representation of primitive Resource return type

java,java-ee,jax-rs

Not sure if it's a good idea. Would be much better if you'll create new JAX-RS resource and designated entity-class to response with. Still, if you want to mix marshalling with model, you could write your own MessageBodyWriter. For example: @Produces("application/json") public class IntWriter implements MessageBodyWriter<Integer> { @Override public boolean...

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

java,ssl,jax-rs,resteasy,wildfly

"Do we have to generate keystores ourselves?" Yes. You need to generate one for the Server and a Trust store (which is just a key store, but we just call it a trust store to differentiate it). See SSL setup guide in the Wildfly documentation. It will show you...

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

java,jax-rs,resteasy,tika

You can add multiple MediaTypes as you already mentioned. If the server accepts more than one MediaType he has to negotiate with the client which one should be used. The client should send a Content-Type header like Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document. For adding a Content-Type header with the proxy framework you have...

How to get @interface parameter in jersey WriterInterceptor Implementation

java,annotations,jersey,jax-rs,interceptor

You can simply do AutoLogged annotation = resourceInfo.getResourceMethod().getAnnotation(AutoLogged.class); if (annotation != null) { boolean query = annotation.query(); } "and want to set parameter query" Not exactly sure what you mean hear, but if you mean you want to set the value at runtime, I'm not really sure the purpose and...

Jax-RS unable to authenticate to proxy

java,jax-rs,resteasy,squid

Wow, It really make me crazy this problem. I don't know how to solve it in an implementation independent way. Anyway, by now it worked like that: ResteasyClient client = new ResteasyClientBuilder().defaultProxy(myProxy, myProxyPort).build(); Credentials credentials = new UsernamePasswordCredentials(me, mypassword); ApacheHttpClient4Engine engine = (ApacheHttpClient4Engine)client.httpEngine(); HttpContext context = new BasicHttpContext(); engine.setHttpContext(context); CredentialsProvider...

Restlet how to decode secret in HTTP basic authentication

java,rest,base64,jax-rs,restlet

try this code public void authenticate(HttpServletRequest req) { String authhead = req.getHeader("Authorization"); if (authhead != null) { // *****Decode the authorisation String***** byte[] e = Base64.decode(authhead.substring(6)); String usernpass = new String(e); // *****Split the username from the password***** String user = usernpass.substring(0, usernpass.indexOf(":")); String password = usernpass.substring(usernpass.indexOf(":") + 1); //...