Why can't i access JAX-RS api? - jax-rs

I have a task from a company, that send me a virtual machine with everything set up. The task is that i have to create an API to retrieve Person details from the database and display it.
The problem is that when i run the application, the server returns an index.html with hello world text in it. However, when i try to change the index.html, it does not change in the browser, but when i do request through postman, i get the "updated" index.html.
What i also realised that i cannot access the API that i have created, to check if i can access APIs in the first place.
The path where the index.html returns is "http://hocalhost:8080/tutorial-applicans/"
My Service is PersonService.java:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Stateless
#Path("person")
public class PersonService{
#PersistenceContext(unitName = "de.erknrw_tutorial-applicants_pu")
private EntityManager em;
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String sayHello(){
return "Hello World!!!"
}
}
I am trying to get "Hello World!!!", but my path is wrong, when i tried "http://hocalhost:8080/tutorial-applicans/person/hello".
Might be worth mentioning that there is also a JAXRSConfiguration.java file:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Applications;
#ApplicationPath(JAXRSConfiguration.RESTROOT)
public class JAXRSConfiguration extends Application{
public static final String RESTROOT = "webresources";
}
How do access the sayHello()? How does the path look like?
Thanks in advance

When deploying on a webapp, the JAX-RS application is configured as a Servlet. So, you have to add the application path prior to the path of the resource.
The endpoint would be:
http://[server]:[port]/[context path]/[application path]/[resource path]/[operation path]
In your case:
http://hocalhost:8080/tutorial-applicans/webresources/person/hello

Related

How to handle a GET request for REST API request which is having a body with QAF Webservice

I am using QAF Webservice support for API automation. I have a case where a GET request has a body present. If I pass the request as either using properties file or xml file, on executing I am getting 404 not found response. If the GET request does not have a body present, it works fine in that scenario without any issues. But not with GET request having a body. Upon debugging, found that jersey client API at the end changes the request from GET to POST if a GET request has a body. Please let me know on how to handle this scenario using QAF WebService.
Thanks,
You can use apache HttpClient that will allow to have body with get request. In order to use apache HttpClient, you need to provide implementation of RestClientFactory and register using property rest.client.impl.
Here is the sample code from the qaf users group.
package qaf.example.tests;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import com.qmetry.qaf.automation.ws.rest.RestClientFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandler;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.ApacheHttpClientHandler;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
/**
* #author chirag
*
*/
public class ApacheClientProvider extends RestClientFactory {
#Override
protected Client createClient() {
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setConnectionTimeout(5000);
connectionManager.getParams().setSoTimeout(1000);
connectionManager.getParams().setDefaultMaxConnectionsPerHost(10);
HttpClient httpClient = new HttpClient(connectionManager);
ApacheHttpClientHandler clientHandler = new ApacheHttpClientHandler(httpClient);
ClientHandler root = new ApacheHttpClient(clientHandler );
ClientConfig config = new DefaultApacheHttpClientConfig();
Client client = new Client(root, config);
return client;
}
}
In order to use it, register your class using rest.client.impl property, in above case:
rest.client.impl=qaf.example.tests.ApacheClientProvider

Jackson annotations quarkus resteasy client

I have a client package where I have defined my REST clients, containing the following interface and models:
#Path("/")
#RegisterRestClient(configKey = "some-api")
public interface SomeRestClient {
#POST
#Path("/oauth/token")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
OAuthResult getOAuthToken(OAuthRequest oAuthRequest);
}
and OAuthRequest class:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
public class OAuthRequest {
private String email;
private String password;
#JsonProperty("grant_type")
private String grantType;
#JsonProperty("client_id")
private String clientId;
#JsonProperty("client_secret")
private String clientSecret;
}
I import this package into my main service package, but quarkus does not seem to pick up the Jackson annotations. The properties of the request are serialized using camel case, when they should be in snake case.
#Inject
#RestClient
private SomeRestClient someRestClient;
OAuthRequest oAuthRequest = new OAuthRequest();
//set fields
OAuthResult oAuthResult = someRestClient.getOAuthToken(oAuthRequest);
EDIT:
I am using the quarkus-rest-client-jackson and the quarkus-rest-client dependencies, no jsonb dependency anywhere.
I have tried to narrow the problem down: I have moved the client / request classes to my main package, and I have removed the lombok annotations and made my fields which have Jackson annotations public. Still the same problem...
Could anyone point me in the right direction of what I am doing wrong?
Reasteasy is used for your reste endpoint not to access a remote REST service.
To access a remote REST service the REST client is used.
The REST client comes with Jackson support of you use the quarkus-rest-client-jackson dependency not the JSON-B one.

JAX-RS not responding (404)

I have a very basic JAX-WS-RS that I'm trying to get working and am getting frustrated. And would love some help. --thanks.
my environment is Eclipse 2018-09 (fresh "dynamic web-app"), java 8u191, tomcat 8.5
my "basic" code (running in the app named: webservice) won't respond at all to calls to /webservice/steve. only a 404.
I'm including JAR: /WEB-INF/lib/javax.ws.rs-api-2.1.1.jar
code:
import javax.ws.rs.*;
#Path("/")
public class ServletTest {
#GET
#Path("/steve")
#Produces("text/plain")
public String getSteve() {return "Steve";}
}

Provide authorisation using apache shiro for Rest service method in java application

in my simple web application, i have two web service method. one is storeName()and another one is viewAllNames() methods.
Admin role can be access to both methods. But user role should be access viewAllNames() method.
I am going to use Apache shiro, maven with web based project and rest service. Provide authorization only for those two methods.
My actual rest url is :
http://localhost:8080/SimpleRest/simpleservice/store/jackreobert --> admin only
http://localhost:8080/SimpleRest/simpleservice/viewall/ --> user only
How to configure shiro.ini, web.xml and annotaion/xml.
For shiro approach, do i need pass any other information into web service url, how to achieve this.
SimpleService.java
package com.simple.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.json.JSONException;
#Path("/simpleservice")
public class SimpleService {
#Path("/store/{name}")
#GET
#Produces("application/json")
public Response storeName(#PathParam("name") String name) throws JSONException {
/**
* Here insert logic
*/
String result = "Given name: " + name + " successfully stored";
return Respo}nse.status(200).entity(result).build();
}
#Path("/viewall")
#GET
#Produces("application/json")
public Response viewAllNames() throws JSONException {
/**
* Here retrieve logic
*/
String result = "All names are taken";
return Response.status(200).entity(result).build();
}}
Thanks for reading for my post.
Help me,
Thanks in advance.
My suggestion is to use Permissions. Protect your application resources with permissions. Assign permissions to roles and assign Roles to Users.
As of Shiro 1.4.0-RC2 there is official JAX-RS support, take a look at the sample.

Swagger api listing is empty

Recently I have configure swagger with one of my project. Its using jersey2 and JAX-WS on tomcat for restful API. I have used following manual to configure
https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5
${basepath}/swagger.json response with following
{"swagger":"2.0","info":{"version":"1.0.0","title":""},"host":"localhost:8080","basePath":"/myapi","schemes":["http"]}
Unfortounately it does not contain any api which is under my resource package.
I have tried with the answer of following question
swagger - empty listing with no API
But it didn't help either.
The above answer using com.wordnik.swagger.* package(s)
But with the manual I got io.swagger.* package(s), which doesn't have
JaxrsApiReader class
My assumption is swagger couldn't scan my api list from Resource package.
But could not figure out which configuration or which code snippet I have missed.
Any help?....
It looks like you forgot to mark the rest endpoints with #Api
I had the same issue, I used a different approach that worked for me, by adding information only in my Application class. In case you have one, that might help you:
public class MyApi extends Application {
public MyApi() {
super();
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("MyApi");
beanConfig.setVersion("0.0.1");
beanConfig.setSchemes(new String[]{"http", "https"});
beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/mypath");
//putting only the path to my api unblocked me, I removed "io.swagger.resources"
beanConfig.setResourcePackage("system.organization.api");
beanConfig.setScan(true);
beanConfig.setPrettyPrint(true);
}
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<>();
s.add(MyApis);
//for swagger
s.add(ApiListingResource.class);
s.add(SwaggerSerializers.class);
return s;
}
}
Then, the links of classes with #API annotation appeared in swagger.json
Mostly done with the same manual you used: https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5