Consuming a REST API in DropWizard - java

I'm building an API in java using DropWizard. However, for certain resources I also need to consume other RESTful API's. These other API's do not require any authentication.
Can DropWizard be used to consume API's? Or what are some other ways to simply consume a RESTful API in a java application? Since I'm using DropWizard I already have Jackson.
So if the REST API is something like this:
[ {"id": "0",
"name" : "Joe"
]
I'd like to have an object like this List<Foo>

I suppose you can use a DropWizard's Jersey Client. According to the documentation, it does exactly what you are looking for.
http://www.dropwizard.io/1.0.3/docs/manual/client.html
I.e.:
public class ExampleConfiguration extends Configuration {
#Valid
#NotNull
private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration();
#JsonProperty("jerseyClient")
public JerseyClientConfiguration getJerseyClientConfiguration() {
return jerseyClient;
}
}
Then, in your service’s run method, create a new JerseyClientBuilder:
#Override
public void run(ExampleConfiguration config,
Environment environment) {
final Client client = new JerseyClientBuilder(environment).using(config.getJerseyClientConfiguration())
.build(getName());
environment.jersey().register(new ExternalServiceResource(client));
}

Related

Spring MVC/WebAPI equivalent of C# RoutePrefix

I'm used to developing in C# Web API where as well as routing attributes for individual endpoints I can also add a prefix for the controller, e,g,
[RoutePrefix("/MyController")]
However I'm developing in Java Spring Boot and although I can map individual endpoints, I can't find a way to add a prefix for all.
Is this possible?
On spring-boot you can use the #RequestMapping("/MyController") annotation at the class level.
#RequestMapping("/MyController")
public class MyController {
#GetMapping(value = "/helloWord") // this will become /MyController/helloWord
public String helloWorld() {
return "Hello World";
}
}

Can spring cloud functions get access to any spring managed component?

I'm working on a spring-cloud-function with Azure-functions.
Is it possible to use any spring managed components within the "handlers" (extending AzureSpringBootRequestHandler) ?
I tried to narrow this down with the sample project:
https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-samples/function-sample-azure
So the simplest example I could imagine is:
public class UppercaseHandler extends AzureSpringBootRequestHandler<String, String> {
private final UppercaseService uppercaseService;
#Autowired
public UppercaseHandler (UppercaseService uppercaseService){
this.uppercaseService = uppercaseService;
}
#FunctionName("uppercase")
public String execute(#HttpTrigger(name = "req", methods = {HttpMethod.GET,
HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
ExecutionContext context) {
return handleRequest(request.getBody().get(), context);
}
}
However it looks like this handler is not managed by spring and does not work with autowiring.
Would be great to get some help, thanks!
You are trying to use Spring auto-wiring in the Azure Function HTTP request handler (a very thin adapter specific to cloud provider) which is decoupled outside Spring function. That's why it's not working there. You should not have any business logic in the adapter. But if you use DI in any Spring controller/service it would work like in a regular Spring boot application.
You can check out this handy blog post Playing with Spring Cloud in Azure Functions.

Can we self-generate a client out of a Rest controller using annotation processing ? If we can then how I can proceed?

(https://github.com/aashrai/brahma-dao), similar to this DAO generator can we do annotation processing to generate a client for a rest controller ?
PS : I am using Spring Boot with gradle.
Domino-rest can do that, it generates a client from a jax-rs interface resource.
the generated client works in JVM, and will automatically map JSON responses/requests.
a short sample can look like this
the jax-rs interface
#RequestFactory
public interface MoviesService {
#Path("library/movies/:movieName")
#GET
Movie getMovieByName(String movieName);
#Path("library/movies")
#GET
List<Movie> listMovies();
#Path("library/movies/:name")
#PUT
void updateMovie(#RequestBody Movie movie);
}
and the generated client can be used like this
MoviesServiceFactory.INSTANCE
.getMovieByName("hulk")
.onSuccess(movie -> {
//do something on success
})
.onFailed(failedResponse -> {
//do something on error
})
.send();
there is lots of supported features and enough documentation to get you started.
please note that this is still under development and is still in SNAPSHOT.

Configuring Jersey 1.18.x server for JSON POJO mapping

Jersey 1.18.1 here. I have the following Jersey resource defined on my server:
#Path("/location")
#Produces(MediaType.APPLICATION_JSON)
public class LocationResourceImpl implements LocationResource {
private ObjectMapper mapper;
public LocationResourceImpl() {
super();
mapper = new ObjectMapper();
// TODO: Configure for JSON POJO mapping how?!?
}
#GET
#Path("address/{address_id}")
#Override
public Address getAddress(#PathParam("address_id") Long id) {
Address address;
address = new Address(
1L,
"19 ABC Dr",
"Suite 3",
"Testville",
"NY",
"US",
"12345");
return address;
}
}
My Address POJO is properly annotated with #JsonProperty annotations. I am trying to figure out how to configure my ObjectMapper instance so that the Address instance returned by getAddress(Long) returns my address as JSON.
Any ideas as to what I can do? It look like setSerializationConfig and setDeserializationConfig methods were added in Jersey 2.x, but upgrading isn't an option for me, as I'm using DropWizard 0.7.1, which depends on Jersey 1.18.x.
With Dropwizard, we don't need any special configuration for basic Jackson POJO mapping support. As explained in the Dropwizard User Guide: How it's Glued Together:
When your application starts up, it will spin up a Jetty HTTP server, see DefaultServerFactory. This server will have two handlers, one for your application port and the other for your admin port.
The application port has an HttpServlet as well, this is composed of DropwizardResourceConfig, which is an extension of Jersey’s resource configuration that performs scanning to find root resource and provider classes.
DropwizardResourceConfig is where the various ResourceMethodDispatchAdapter are registered to enable the following functionality:
Enables using Jackson to parse request entities into objects and generate response entities from objects, all while performing validation.

Different web service object after each call

I am new with Java EE and SOAP. I have tried to create a simple web service application and its client (environment: NetBeans 7.2.1 IDE, GlassFish Server 3.1, Java 1.6).
Web service code:
package simplews;
import javax.jws.*;
#WebService(serviceName = "SimpleWebService")
public class SimpleWebService {
String something = null;
#WebMethod(operationName = "setSomething")
#Oneway
public void setSomething(#WebParam(name = "smth") String smth) {
something = smth;
}
#WebMethod(operationName = "getSomething")
public String getSomething() {
return something;
}
}
Client application code:
package simpleclientapp;
import simplews.*;
public class SimpleClientApp {
public static void main(String[] args) {
SimpleWebService_Service service = new SimpleWebService_Service();
SimpleWebService port = service.getSimpleWebServicePort();
port.setSomething("trololo");
String smth = port.getSomething();
System.out.println(smth);
}
}
Unfortunately, the client application printed out null. After short investigation I have realised, that on the server side a new SimpleWebService object is created for each client call (sounds like stateless approach).
What is wrong here? Why the client port does not refer to the same WS object for each call?
Web services are stateless by nature. In order to keep state between requests, you have to persist the data (in a file,database etc.).
You're right, JAX-WS web services are stateless by default and you can't rely on something thatviolates this premise. Follow a different approach in storing such values. You can read this doc Java TM API for XML Web Services (JAX-WS) Stateful Web Service with JAX-WS RI, if you really want to follow the direction in your post.

Categories

Resources