I have an object with state and non-serializable fields, like threads, and I would to invoke functions on it like one would do it through RMI but through http. I don't want to scale and I am in an isolated network. I am currently using Jetty, like this:
public class ObjectHandler extends AbstractHandler {
MyStatefulObject obj;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String action = request.getParameter("action");
switch (action) {
case "method1":
obj.method1(request.getParameter("some-parameter"));
break;
case "method2":
obj.method2(request.getParameter("some-other-parameter"));
break;
}
baseRequest.setHandled(true);
}
}
which is kind of weird. I would like to use something like Servlets, and use the different methods to tell apart the action to do, or use JAX-RS to use the calling url to tell apart the action to do. But both of those methods are stateless, that is, I cannot pass an object to a servlet, and, at least with jersey, the construction was made with the class, not with and instance of it, so I could not control the construction of the MyStatefulObject object. So, is there a library for, let's say, annotate an object and pass it to a server instance and start listening to requests? I would like to make something like this:
#Path("/")
public class MyStatefulObject {
MyStatefulObject(Parameter param1, Param) {
//some building stuff
}
#POST
#Path("/path1")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
void method1(Parameter param) {}
#POST
#Path("/path2")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
Object method2(Parameter param) {
return new Object();
}
}
while outside I would have:
Server server = new Server(8081);
server.setHandler(new MyStatefulObject(param));
server.start();
server.join();
Is there a library that makes me able to do that? as I say before, I don't want to scale (this is running in a small network) and there is no security concerns. I just want to "publish" an object.
In the end, Jersey does allow stateful objects to be published, using the ResourceConfig class with an object (as opposed with a Class, which is the use I found more frequently). Funny cause in this question they want to do the exact opposite. We simply register an object in the ResourceConfig.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.net.URI;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.jetty.JettyHttpContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import javax.inject.Singleton;
#Path("calculator")
public class Calculator {
int i = -1;
public Calculator(int i) {
this.i = i;
}
#GET
#Path("increment")
#Produces(MediaType.APPLICATION_JSON)
public String increment() {
i = i + 1;
return "" + i;
}
public static void main(String[] args) throws Exception {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(new Calculator(10));
Server server = JettyHttpContainerFactory.createServer(new URI("http://localhost:8080"), resourceConfig);
server.start();
}
}
Related
I need create a rest client to access a URI that can receive 0 or n query params.
Example:
https://xpto?page=0&size=10&brand=abc&color=blue or
https://xpto?page=0&size=10&brand=abc or
https://xpto?page=0&size=10 or
https://xpto
how could i do this here?
#RegisterRestClient
public interface BarService {
#GET
#Path("/xpto")
Response get(#QueryParam ...);
}
Please refer to How to send a query params map using RESTEasy proxy client, similar issue is being discussed.
You can define your client similar to below:
#RegisterRestClient
public interface BarService {
#GET
#Path("/xpto")
Response get(Map<String, String> queryParamMap);
}
And you can define ClientRequestFilter for converting the Map to Query Parameters:
import java.io.IOException;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.Provider;
#Provider
public class QueryParamBuildingFilter implements ClientRequestFilter {
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (requestContext.getEntity() instanceof Map && requestContext.getMethod().equals(HttpMethod.GET)) {
UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
Map allParam = (Map)requestContext.getEntity();
for (Object key : allParam.keySet()) {
uriBuilder.queryParam(key.toString(), allParam.get(key));
}
requestContext.setUri(uriBuilder.build());
requestContext.setEntity(null);
}
}
}
Is there with Spring (boot) a way to check if a REST request contains a parameter not explicitly declared by the called REST method?
With the required flag we can force the client to include a certain parameter in the request. I am looking for a similar way to disallow the client to send a parameter that is not explicity mentioned in the declaration of the controller method:
#RequestMapping("/hello")
public String hello(#RequestParam(value = "name") String name) {
//throw an exception if a REST client calls this method and
// sends a parameter with a name other than "name"
//otherwise run this method's logic
}
For example calling
curl "localhost:8080/hello?name=world&city=London"
should result in a 4xx answer.
One option would be to explicitly check for unexpected parameters:
#RequestMapping("/hello")
public String hello(#RequestParam Map<String,String> allRequestParams) {
//throw an exception if allRequestParams contains a key that we cannot process here
//otherwise run this method's logic
}
But is it also possible to achieve the same result while keeping the same convenient #RequestParam usage as in the first example?
EDIT: Sorry, I do not see any connection to this question. The other question is about annotation processing at runtime. My question is about the behaviour of Spring's REST engine. Am I missing something?
EDIT: Based on the answers, I have written this HandlerInterceptor:
#Component
public class TooManyParamatersHandlerInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod m = (HandlerMethod) handler;
if (m.getMethod().getName().equals("error")) {
return true;
}
List<String> allowedParameters = Stream.of(m.getMethodParameters())
.flatMap(p -> Stream.of(p.getParameterAnnotation(RequestParam.class)))
.filter(Objects::nonNull)
.map(RequestParam::name).collect(Collectors.toList());
ArrayList<String> actualParameters = Collections.list(request.getParameterNames());
actualParameters.removeAll(allowedParameters);
if (!actualParameters.isEmpty()) {
throw new org.springframework.web.bind.ServletRequestBindingException(
"unexpected parameter: " + actualParameters);
}
return true;
}
}
In this case you required HandlerInterceptor or HandlerInterceptorAdapter, override the preHandle method
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//request param validation validation
return true; //or throw exception
}
ServletRequest.getParameterMap() returns a map of key-values of the request parameters.
You can do it by ContainerRequestFilter feature which is added from JavaEE 7 that lets you access the resource class and resource method matched by the current request and make you to do your desire action when that have not been matched.
You can read more here :
https://docs.oracle.com/javaee/7/api/javax/ws/rs/container/ResourceInfo.html
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
#Provider
public class RequestParamFilter implements ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Set<String> acceptedParamList = new HashSet<String>();
Method method = resourceInfo.getResourceMethod();
for (Annotation[] annos : method.getParameterAnnotations()) {
for (Annotation anno : annos) {
if (anno instanceof QueryParam) {
acceptedParamList.add(((QueryParam) anno).value());
}
}
}
MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters();
for (String param : queryParams .keySet()) {
if (!acceptedParamList.contains(param)) {
requestContext.abortWith(Response.status(Status.BAD_REQUEST).entity("Unexpected paramter found : "+param).build());
}
}
}
}
P.N : Filters are cost in your application speed most of the times, Specially if you have complex chains in it!
I recommend to use it in this case (and similar cases) because of most of the those requests should not be reached to the server application at all.
I hope this helps you and Happy coding! =)
As far as I know, you cannot simply disallow parameters using Spring. Honestly, this issue is rather questionable and unnecessary and I think it's an antipattern.
However, Spring provides with each mapping the HttpServletRequest and HttpServletResponse objects to the controller method signature. Use the method HttpServletRequest::getParameterMap to receive the Map of the passed parameters for the further iteration and validation.
#RequestMapping("/hello")
public String hello(RequestParam(value = "name") String name, HttpServletRequest request, HttpServletResponse response) {
final Map<String, String[]> parameterMap = request.getParameterMap();
// logics
}
Passing those object to only to the #RequestMapping("/hello") allows performing the validation only to the selected mapping. If you want to define this behavior globally, I suggest you use HandlerInterceptor::preHandle as answered here.
If you make the hello parameter required=true, then you can just check the size of the Map whether is equal to 1 or not.
I am working on Rest web services and client using CXF 3.1.2 , and i have few clarification as below,
Service:
import javax.jws.WebService;
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;
public class GenServiceImpl {
#GET
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
#Path("/agentLogin/{ext}")
public String agentLogin(#PathParam("ext") Integer ext) {
return "EventAgentLoggedIn";
}
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes({"application/xml", MediaType.TEXT_PLAIN})
#Path("/agentLogout")
public String agentLogout(String ext) {
return "EventAgentLoggedOut";
}
}
Client:
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.client.WebClient;
public class TestClient {
static final String REST_URI = "http://localhost:8080/RestfulSample/Restful";
public static void main(String[] args) {
WebClient client = WebClient.create(REST_URI);
//Get
client.path("agentLogin").path(new Integer(1234)).accept(MediaType.TEXT_PLAIN);
String agentLoginResponse = client.get(String.class);
System.out.println(agentLoginResponse);
client.reset();
//Post
client.path("agentLogout").accept(MediaType.TEXT_PLAIN);
Response agentLogoutResponse = client.post("10245");
System.out.println(agentLogoutResponse.readEntity(String.class));
client.reset();
}
Clarifications:
In my above example - In service class Post method(agentLogout) , i am getting error if i replace #Consumes({"application/xml", MediaType.TEXT_PLAIN})
with
#Consumes(MediaType.TEXT_PLAIN) whereas it works fine in Get method(agentLogin), may i know why it is so?
It is right to use client.reset(); - Here i am trying to use single WebClient to access all my methods.
Could you please let me know what i tried in my example is best practice ? and it will be appreciated if you could correct me here
Thanks,
Here are the clarifications.
Set content type to text/plain while posting. And you can set in your servers side class #Consumes(MediaType.TEXT_PLAIN)
client.replaceHeader("Content-Type",MediaType.TEXT_PLAIN);
Yes you can use rest method, here is java doc
When reusing the same WebClient instance for multiple invocations,
one may want to reset its state with the help of the reset() method,
for example, when the Accept header value needs to be changed and the
current URI needs to be reset to the baseURI (as an alternative to a
back(true) call). The resetQuery() method may be used to reset the
query values only. Both options are available for proxies too.
I would prefer to use proxy and access REST more like OOPS.
You could create interface for the above server class(Generally I careate REST definition as interface and then implement the interface( more like SOAP way)), which could be auto generated using WADLToJava maven plugin from WADL.
Here is sample interface for above server side rest class
public interface GenService {
#GET
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
#Path("/agentLogin/{ext}")
public String agentLogin(#PathParam("ext") Integer ext);
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
#Path("/agentLogout")
public String agentLogout(String ext);
}
Since you are not using spring , I will create a singleton class
public class CxfRestSingleton {
public static GenService obj;
public static GenService getInstance() {
if (obj == null) {
obj = JAXRSClientFactory.create("http://localhost:8080/RestfulSample/Restful", GenService.class);
}
return obj;
}
}
And you can access the rest using below code.
public static void main( String[] args )
{
System.out.println( CxfRestSingleton.getInstance().agentLogin(12345));
}
RESTEasy provides the Server-side Mock Framework for mocking server requests. Is there an equivalent for unit testing the client framework?
Is InMemoryClientExecutor intended for this purpose? I'm having trouble finding documentation and examples of how this class should be used.
Looks like InMemoryClientExecutor may be used for client-side mocking. Looking in the source, it internally uses the same classes as the server-side mock framework, namely, MockHttpRequest and MockHttpResponse.
InMemoryClientExecutor gives you the ability to override createResponse for mocking responses and also has a constructor which takes a Dispatcher, if you want to customize and intercept calls that way.
Here's a quick and dirty snippet leveraging the client framework example,
import javax.ws.rs.*;
import javax.ws.rs.core.Response.*;
import org.jboss.resteasy.client.*;
import org.jboss.resteasy.client.core.*;
import org.jboss.resteasy.client.core.executors.*;
import org.jboss.resteasy.mock.*;
import org.jboss.resteasy.plugins.providers.*;
import org.jboss.resteasy.spi.*;
public class InMemoryClientExecutorExample {
public interface SimpleClient {
#GET
#Path("basic")
#Produces("text/plain")
String getBasic();
#PUT
#Path("basic")
#Consumes("text/plain")
void putBasic(String body);
#GET
#Path("queryParam")
#Produces("text/plain")
String getQueryParam(#QueryParam("param")String param);
#GET
#Path("matrixParam")
#Produces("text/plain")
String getMatrixParam(#MatrixParam("param")String param);
#GET
#Path("uriParam/{param}")
#Produces("text/plain")
int getUriParam(#PathParam("param")int param);
}
public static void main(String[] args) {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
ClientExecutor executor = new InMemoryClientExecutor() {
#Override
protected BaseClientResponse<?> createResponse(ClientRequest request, MockHttpResponse mockResponse) {
try {
System.out.println("Client requesting " + request.getHttpMethod() + " on " + request.getUri());
}
catch(Exception ex) {
ex.printStackTrace();
}
mockResponse.setStatus(Status.OK.getStatusCode());
return super.createResponse(request, mockResponse);
}
};
SimpleClient client = ProxyFactory.create(SimpleClient.class, "http://localhost:8081", executor);
client.putBasic("hello world");
}
}
I am using the Jersey client to run some integration tests against my service. However, one of my calls sends a redirect. I am expecting to get a redirect but when Jersey Client gets the redirect it errors out with a com.sun.jersey.api.client.UniformInterfaceException. Is there some way to make it accept the response with the redirect and just let me know what it got?
You can catch UniformInterfaceException which provides response field containing all the details.
You could additionally write some hamcrest matchers to express your expectations:
import static javax.ws.rs.core.Response.Status.*;
import static org.junit.rules.ExpectedException.*;
import javax.ws.rs.core.Response.Status;
import org.hamcrest.*;
import org.junit.*;
import org.junit.rules.ExpectedException;
import com.sun.jersey.api.client.*;
public class MyResourceShould {
#Rule
public ExpectedException unsuccessfulResponse = none();
private WebResource resource;
#Before
public void setUp() {
Client client = Client.create();
client.setFollowRedirects(false);
resource = client.resource("http://example.com");
}
#Test
public void reportMovedPermanently() {
unsuccessfulResponse.expect(statusCode(MOVED_PERMANENTLY));
resource.path("redirecting").get(String.class);
}
public static Matcher<UniformInterfaceException> statusCode(Status status) {
return new UniformInterfaceExceptionResponseStatusMatcher(status);
}
}
class UniformInterfaceExceptionResponseStatusMatcher extends TypeSafeMatcher<UniformInterfaceException> {
private final int statusCode;
public UniformInterfaceExceptionResponseStatusMatcher(Status status) {
this.statusCode = status.getStatusCode();
}
public void describeTo(Description description) {
description.appendText("response with status ").appendValue(statusCode);
}
#Override
protected boolean matchesSafely(UniformInterfaceException exception) {
return exception.getResponse().getStatus() == statusCode;
}
}
Also note that follow redirects (in setUp method) should be set to false in order to get UniformInterfaceException instead of following redirect (if one is specified in Location header).