Search code examples
javajakarta-eecdiejb-3.0resteasy

Method @Produces return null when is inject


I have a problem with my method @Produces. When I inject ResteasyWebTarget target in my Api Request class, object target is null.

Can someone help me with this. CDI not working in my class...

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({TYPE, METHOD, PARAMETER, FIELD})
    public @interface ServiceProducer {

    }
public class ServiceProducerImpl implements Serializable {

    @Produces
    @ServiceProducer
    public ResteasyWebTarget getClient() {
        String patApi = "http://localhost:5000";
        try {
            ResteasyClient client = new ResteasyClientBuilder().build();
            ResteasyWebTarget target = client.target(UriBuilder.fromPath(patApi));
            return target;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
  @Path("/api-java")
  public interface IServices {

      @PUT
      @Path("/put")
      @Produces(MediaType.APPLICATION_JSON)
      @Consumes(MediaType.APPLICATION_JSON)
      Response putservice(ApiRequestModel api);
  }
public class ApiRequest {

    @Inject
    @ServiceProducer
    ResteasyWebTarget target;

    public void rest() {
        String patApi = "http://localhost:5000";
        try {

            IServices service = target.proxy(IServices.class);
            ApiRequestModel api = new ApiRequestModel(11, "22", 0);
            Response response = service.putservice(api);
            ApiResponseModel apiResponse = response.readEntity(ApiResponseModel.class);
            System.out.println("API-JAVA>> " + "CNPJ: " + apiResponse.getCnpj() + " ADQ: " + apiResponse.getAdq() + " BLOCKCODE: " + apiResponse.getBlockcode());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

Solution

  • Model Class

    public class ApiRequestModel {
    
        private int adq;
    
    
        private String cnpj;
    
    
        private int blockcode;
    
        public ApiRequestModel(int adq, String cnpj, int blockcode) {
            this.adq = adq;
            this.cnpj = cnpj;
            this.blockcode = blockcode;
        }
    
        public int getAdq() {
            return adq;
        }
    
        public void setAdq(int adq) {
            this.adq = adq;
        }
    
        public String getCnpj() {
            return cnpj;
        }
    
        public void setCnpj(String cnpj) {
            this.cnpj = cnpj;
        }
    
        public int getBlockcode() {
            return blockcode;
        }
    
        public void setBlockcode(int blockcode) {
            this.blockcode = blockcode;
        }
    }
    
    public class ApiResponseModel {
    
    
        private int adq;
    
    
        private String cnpj;
    
    
        private int blockcode;
    
        public ApiResponseModel( @JsonProperty("adq") int adq,  @JsonProperty("cnpj") String cnpj, @JsonProperty("blockcode") int blockcode) {
            this.adq = adq;
            this.cnpj = cnpj;
            this.blockcode = blockcode;
        }
    
        public int getAdq() {
            return adq;
        }
    
        public void setAdq(int adq) {
            this.adq = adq;
        }
    
        public String getCnpj() {
            return cnpj;
        }
    
        public void setCnpj(String cnpj) {
            this.cnpj = cnpj;
        }
    
        public int getBlockcode() {
            return blockcode;
        }
    
        public void setBlockcode(int blockcode) {
            this.blockcode = blockcode;
        }
    }
    

    Produces

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({TYPE, METHOD, PARAMETER, FIELD})
    public @interface ServiceProducer {
    
    }
    
    public class ServiceProducerImpl {
    
        @Produces
        @ServiceProducer
        public ResteasyWebTarget getClient() {
            String patApi = "http://localhost:5000";
            try {
                ResteasyClient client = new ResteasyClientBuilder().build();
                ResteasyWebTarget target = client.target(UriBuilder.fromPath(patApi));
                return target;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }
    

    Services interface

    @Path("/api-java")
    public interface IServices {
    
        @PUT
        @Path("/put")
        @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        Response putservice(ApiRequestModel api);
    }
    

    How inject Produces

    @ApplicationScoped
    public class ApiRequest {
    
        @Inject
        @ServiceProducer
        private ResteasyWebTarget target;
    
        public void rest() {
            try {
                IServices service = target.proxy(IServices.class);
                ApiRequestModel api = new ApiRequestModel(11, "22", 0);
                Response response = service.putservice(api);
                ApiResponseModel apiResponse = response.readEntity(ApiResponseModel.class);
                System.out.println("API-JAVA>> " + "CNPJ: " + apiResponse.getCnpj() + " ADQ: " + apiResponse.getAdq() + " BLOCKCODE: " + apiResponse.getBlockcode());
    
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
    
    }
    

    Init container

    public class Main {
    
        public static void main(String[] args) {
            Weld weld = new Weld();
    
            WeldContainer container = weld.initialize();
    
            container.select(ApiRequest.class).get().rest();
    
            container.shutdown();
        }
    }
    

    beans.xml path: resources/META-INF/beans.xml

    <beans xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_1.xsd">
    </beans>
    

    For this example: API Node.js + Express

    index.js

    const express = require('express');
    const morgan = require('morgan');
    const routes = require('./routes/customer.routes')
    
    const app = express();
    
    //Settings
    app.set('appName', 'API for Java');
    app.set('port', process.env.PORT || 5000);
    
    //Middlewares
    app.use(morgan('combine'));
    app.use(express.json())
    
    
    // Routes
    app.use('/api-java',routes);
    app.get('/login', (req, res) => res.send('Hello desde login'))
    
    
    // Start Server
    app.listen(app.get('port'), () => {
      console.log('Server running on port:', app.get('port'));
      console.log(app.get('appName'))
    }) 
    

    Routes

    customer.routes.js

    const express = require('express');
    const router = express.Router();
    
    router.get('/', (req, res) => res.send('GET Response'))
    
    router.put('/put', (req, res) => {
      const { adq, cnpj, blockcode } = req.body;
    
      console.log(req.body)
      res.json({
        adq : adq , cnpj, blockcode
      })
    })
    
    module.exports = router;