MicroProfile Rest Client con Jmoordb
Crear microservicios con Microprofile es realmente fácil. en esta ocasión mostrare una aplicación simple que utiliza MongoDB como base de datos y Jmoordb.
Creamos un proyecto Web con Maven y con PayaraMicro. (En mi caso utilizo Apache NetBeans)
Editar el archivo pom.xml
Agregar el repositorio
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Agregar las dependencias
<dependency>
<groupId>com.github.avbravo</groupId>
<artifactId>jmoordb</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.github.avbravo</groupId>
<artifactId>jmoordbutils</artifactId>
<version>1.39</version>
</dependency>
Crearemos una entidad, un repository y un endpoint y establecemos la conexión a la base datos.
Recordamos que tenemos una base de datos MongoDB
Establecemos al conexión
@ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
try {
JmoordbConnection jmc = new JmoordbConnection.Builder()
.withSecurity(false)
.withDatabase("mydatabase")
.withHost("")
.withPort(0)
.withUsername("")
.withPassword("")
.build();
} catch (Exception e) {
System.out.println("Error " + e.getLocalizedMessage());
}
return resources;
}
}
Ahora creamos la entidad
El código es muy simple:
public class Country {
@Id
private String id;
private String name;
//constructor
//set/get
}
Luego creamos CountryRepository
@Stateless
public class CountryRepository extends Repository<Country> {
public CountryRepository(){
super(Country.class,"restclient","country");
}
}
Crear la clase CountryServices
@Path("/message")
public class CountryResources {
@Inject
CountryRepository countryRepository;
// <editor-fold defaultstate="collapsed" desc="MicroprofileConfig() ">
@Inject
@ConfigProperty(name = "message")
private String message;
// </editor-fold>
@GET
@Path("/text")
public String getHello() {
return message;
}
@GET
@Path("/first")
@Produces(MediaType.APPLICATION_JSON)
public Country first() {
return countryRepository.findAll().get(0);
}
@GET
@Path("/findall")
@Produces(MediaType.APPLICATION_JSON)
public List<Country> findAll() {
return countryRepository.findAll();
}
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Country country) {
try {
if (countryRepository.save(country)) {
return Response.status(201).entity("Ok").build();
} else {
return Response.status(400).entity("error " + countryRepository.getException().getLocalizedMessage()).build();
}
} catch (Exception e) {
return Response.status(400).entity("Error!!" + e.getLocalizedMessage()).build();
}
}
// <editor-fold defaultstate="collapsed" desc="@Path("/update")">
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(Country country) {
try {
if (countryRepository.update(country)) {
return Response.status(201).entity("Ok").build();
}
return Response.status(400).entity("error " + countryRepository.getException().getLocalizedMessage()).build();
} catch (Exception e) {
return Response.status(400).entity("Error!!" + e.getLocalizedMessage()).build();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="@Path("/delete")">
@DELETE
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) {
try {
Document doc = new Document("id", id);
if (countryRepository.delete(doc)) {
return Response.status(201).entity("Ok").build();
}
return Response.status(400).entity("error " + countryRepository.getException().getLocalizedMessage()).build();
} catch (Exception e) {
return Response.status(400).entity("Ocurrio un error!!" + e.getLocalizedMessage()).build();
}
}
// </editor-fold>
// // <editor-fold defaultstate="collapsed" desc="@Path("/search/{idcountry }")">
@GET
@Path("/search/{id}")
@Produces(MediaType.APPLICATION_JSON)
//@RolesAllowed({"admin"})
public Country findById(@PathParam("id") String id) {
Country country = new Country();
try {
country.setId(id);
Optional<Country> optional = countryRepository.findById(country);
if (optional.isPresent()) {
country = optional.get();
}
} catch (Exception e) {
System.out.println("findById) " + e.getLocalizedMessage());
}
return country;
}
//// </editor-fold>
}
Crear un proyecto Web con Maven y PayaraMicro desde NetBeans
Creamos la entidad Country
public class Country {
@Id
private String id;
private String name;
//constructor
//set/get
}
Crear la clase RestClient
Creamos la interface con los metodos del Endopoint
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.avbravo.restclient.client;
import com.avbravo.restclient.entity.Country;
import java.util.Base64;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
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.eclipse.microprofile.rest.client.annotation.ClientHeaderParam;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
/**
*
* @author avbravo
*/
@RegisterRestClient(baseUri = "http://localhost:8080/microprofilerestclientserver/resources")
@Path("/message")
//@ClientHeaderParam(name = "Authorization", value = "{lookupAuth}")
public interface CountryClient {
default String lookupAuth() {
return "Basic " +
// Base64.getEncoder().encodeToString("user:pass".getBytes());
Base64.getEncoder().encodeToString("E$g3t1.q4@n5:s7_$4wnT1den4=/pana1e1".getBytes());
}
@GET
@Path("/text")
public String getHello();
@GET
@Path("/first")
@Produces(MediaType.APPLICATION_JSON)
public Country first();
@GET
@Path("/findall")
@Produces(MediaType.APPLICATION_JSON)
public List<Country> findAll();
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Country country );
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(Country country );
@DELETE
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) ;
@GET
@Path("/search/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Country findById(@PathParam("id") String id);
}
Crear la clase CountryServices
@Path("/message")
@ApplicationScoped
public class CountryServices {
@Inject
@RestClient
CountryClient service;
@GET
@Path("/text")
public String getHello() {
return service.getHello();
}
@GET
@Path("/first")
@Produces(MediaType.APPLICATION_JSON)
public Country first() {
return service.first();
}
@GET
@Path("/findall")
@Produces(MediaType.APPLICATION_JSON)
public List<Country> findAll() {
return service.findAll();
}
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Country country ){
return service.add(country);
}
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(Country country ){
return service.update(country);
}
@DELETE
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) {
return service.delete(id);
}
@GET
@Path("/search/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Country findById(@PathParam("id") String id){
return service.findById(id);
}
}
Implementando en un Controller
Realizamos la inyección del services y procedemos a invocar los métodos correspondientes.
@Named
@ViewScoped
public class CountryController implements Serializable {
// <editor-fold defaultstate="collapsed" desc="Microprofile Rest Client">
@Inject
CountryServices countryServices;
// </editor-fold>
public CountryController() {
}
// <editor-fold defaultstate="collapsed" desc=" init">
@PostConstruct
public void init() {
countryList = countryServices.findAll();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="clear()">
public String clear() {
message = "";
country = new Country();
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="String prepareAdd()">
public String prepareAdd() {
message = "";
country = new Country();
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="String getHello()">
public String getHello() {
try {
message = countryServices.getHello();
} catch (Exception e) {
JsfUtil.errorDialog("getHello(", e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="String first()">
public String first() {
try {
country = countryServices.first();
} catch (Exception e) {
JsfUtil.errorDialog("first()", e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="String findAll()">
public String findAll() {
try {
countryList = countryServices.findAll();
} catch (Exception e) {
JsfUtil.errorDialog("findAll()", e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="save()">
public void add() {
try {
Response response = countryServices.add(countrySelected);
if (response.getStatus() == 400) {
JsfUtil.errorMessage("No se pudo guardar");
} else {
JsfUtil.successMessage("Guardado exitosamente");
findAll();
PrimeFaces.current().executeScript("PF('countryDialog').hide()");
PrimeFaces.current().ajax().update("form:growl", "form:countryDataTable");
}
} catch (Exception e) {
JsfUtil.errorDialog("add()", e.getLocalizedMessage());
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="update()">
public void update() {
try {
Response response = countryServices.update(countrySelected);
if (response.getStatus() == 400) {
JsfUtil.errorMessage("No se pudo Editar");
} else {
JsfUtil.successMessage("Editado exitosamente");
findAll();
PrimeFaces.current().executeScript("PF('countryDialog').hide()");
PrimeFaces.current().ajax().update("form:growl", "form:countryDataTable");
}
} catch (Exception e) {
JsfUtil.errorDialog("update()", e.getLocalizedMessage());
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="delete()">
public void delete() {
try {
Response response = countryServices.delete(countrySelected.getId());
if (response.getStatus() == 400) {
JsfUtil.errorMessage("No se pudo eliminar");
} else {
JsfUtil.successMessage("Eliminado exitosamente");
findAll();
PrimeFaces.current().executeScript("PF('countryDialog').hide()");
PrimeFaces.current().ajax().update("form:growl", "form:countryDataTable");
}
} catch (Exception e) {
JsfUtil.errorDialog("update()", e.getLocalizedMessage());
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" search">
public String search() {
try {
country = countryServices.findById(id);
if (country == null || country.getId() == null) {
JsfUtil.warningMessage("No lo encontro...");
} else {
JsfUtil.successMessage("Name =" + country.getName());
message = country.getName();
}
} catch (Exception e) {
JsfUtil.errorDialog("findAll()", e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="openNew()">
public void openNew() {
found = false;
this.countrySelected = new Country();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="void prepareQuery()">
public String prepareQuery() {
found = true;
return "";
}
// </editor-fold>
Comments