1

I have a rest webservice java class implemented in a project called pmtv2, and i want to call it from an other class in an other project called sigac as you can see in the picture.enter image description here

here it is the WService class included in a package in pmtv2

package cat.diba.jee.pmtv2.ws.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarExpedientManager;
import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarTramitManager;
import cat.diba.jee.pmtv2.ws.rest.message.RestMessage;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaExpedient;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaRealitzarTramit;
import cat.diba.jee.pmtv2.ws.rest.utils.TokenUtils;

/**
 * The Class PmtRestWsService.
 */
@Path("/tramitacio")
public class PmtRestWsService {

    /**
     * The Constant CLASS_ID.
     */
    private static final String CLASS_ID = PmtRestWsService.class.getName();

    /**
     * Log de la classe.
     */
    private static final Log LOG = LogFactory.getLog(CLASS_ID);

    /**
     * The Constant PARAM_SESSION.
     */
    private static final String PARAM_SESSION = "session";

    /**
     * The Constant PARAM_TOKEN.
     */
    private static final String PARAM_TOKEN = "token";

    /**
     * The Constant PARAM_USERNAME.
     */
    private static final String PARAM_USERNAME = "username";

    /**
     * The Constant PARAM_TRAMITS.
     */
    private static final String PARAM_TRAMITS = "tramits";

    /**
     * The constants PARAM_EXPEDIENTS
     */
    private static final String PARAM_EXPEDIENTS = "expedients";

    /**
     * Realitzar tramit.
     *
     * @param params the params
     * @return the pmt expedient
     */
    @POST
    @Path("/realitzarTramit")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/json,application/xml")
    public RespostaRealitzarTramit realitzarTramit(String params) {
        LOG.debug("Parametres = " + params);

        RealitzarTramitManager manager = new RealitzarTramitManager();
        RespostaRealitzarTramit resposta = new RespostaRealitzarTramit();

        JSONObject jsonObject = new JSONObject(params);
        try {
            if (validarParametresEntrada(jsonObject)) {
                String session = jsonObject.getString(PARAM_SESSION);
                String token = jsonObject.getString(PARAM_TOKEN);
                if (TokenUtils.validarToken(session, token)) {
                    resposta = manager.realitzarTramits(jsonObject, jsonObject.getString(PARAM_USERNAME));
                } else {
                    //Token no validat
                    resposta.setTramitOK(false);
                    resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
                }
            } else {
                //Paràmetres invàlids
                resposta.setTramitOK(false);
                resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_PARAMETRES_ENTRADA.getMessage());
            }
        } catch (Exception e) {
            // Errors als paràmetres d'entrada
            LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
            resposta.setTramitOK(false);
            resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_NO_CONTROLAT.getMessage());
            return resposta;
        }
        return resposta;
    }

    /**
     * Realitzar tramit.
     *
     * @param params the params
     * @return the pmt expedient
     */
    @POST
    @Path("/expedient")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/json,application/xml")
    public RespostaExpedient realitzarExpedient(String params) {
        LOG.debug("Parametres = " + params);

        RealitzarExpedientManager manager = new RealitzarExpedientManager();
        RespostaExpedient resposta = new RespostaExpedient();

        JSONObject jsonObject = new JSONObject(params);
        try {
            if (validarParametresEntradaExpedient(jsonObject)) {
                String session = jsonObject.getString(PARAM_SESSION);
                String token = jsonObject.getString(PARAM_TOKEN);
                if (TokenUtils.validarToken(session, token)) {
                    resposta = manager.realitzarExpedients(jsonObject, jsonObject.getString(PARAM_USERNAME));
                } else {
                    //Token no validat
                    resposta.setExpedientOK(false);
                    resposta.setCodiError(901);
                    resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
                }
            } else {
                //Paràmetres invàlids
                resposta.setExpedientOK(false);
                resposta.setCodiError(902);
                resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_PARAMETRES_ENTRADA.getMessage());
            }
        } catch (Exception e) {
            // Errors als paràmetres d'entrada
            LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
            resposta.setExpedientOK(false);
            resposta.setCodiError(998);
            resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_NO_CONTROLAT.getMessage());
            return resposta;
        }
        return resposta;
    }

    /**
     * validacio de entrada de expedients
     * 
     * @param jsonObject
     * @return
     */
    private boolean validarParametresEntradaExpedient(JSONObject jsonObject) {
        LOG.debug("validarPeticio(jsonObject) - Inici");

        boolean result = true;
        try {
            jsonObject.getJSONArray(PARAM_EXPEDIENTS);
            jsonObject.getString(PARAM_USERNAME);
            jsonObject.getString(PARAM_SESSION);
            jsonObject.getString(PARAM_TOKEN);
        } catch (Exception e) {
            result = false;
        }

        LOG.debug("validarParametresEntrada(jsonObject) - Fi");
        return result;
    }

    /**
     * Validar parametres entrada.
     *
     * @param jsonObject the json object
     * @return true, if successful
     */
    private boolean validarParametresEntrada(final JSONObject jsonObject) {
        LOG.debug("validarPeticio(jsonObject) - Inici");

        boolean result = true;
        try {
            jsonObject.getJSONArray(PARAM_TRAMITS);
            jsonObject.getString(PARAM_USERNAME);
            jsonObject.getString(PARAM_SESSION);
            jsonObject.getString(PARAM_TOKEN);
        } catch (Exception e) {
            result = false;
        }

        LOG.debug("validarParametresEntrada(jsonObject) - Fi");
        return result;
    }
}

is there any way to do it ??

rainman
  • 2,151
  • 6
  • 25
  • 39

4 Answers4

1

you should have an application server, you can use tomcat on localhost, and from the other project you just send à Request on your rest url : localhost[portNumber]/[yourRestService]

you can see this : How to send HTTP request in java?

Community
  • 1
  • 1
1

JAX-RS Client API

You can try the JAX-RS Client API, which provides a high-level API for accessing any REST resources. The Client API is defined in the javax.ws.rs.client package.

To access a REST resource using the Client API, you need the following steps:

  1. Obtain an instance of the javax.ws.rs.client.Client interface.
  2. Configure the Client instance with a target.
  3. Create a request based on the target.
  4. Invoke the request.

Example

Try the following to access your webservice (just change the URI paths according to your needs):

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080")
                         .path("pmtv2")
                         .path("api")
                         .path("tramitacio")
                         .path("realitzarTramit");

RespostaExpedient response = target.request(MediaType.APPLICATION_JSON)
                                   .post(Entity.json(data)), RespostaExpedient.class);

More information

You will need an implementation of the JAX-RS Client API, such as Jersey or RESTEasy.

cassiomolin
  • 101,346
  • 24
  • 214
  • 283
0

You can do a http getrequest to your webservice with required paramters. For that you will need to add httpclient jar in your project.

For httpget request to work you must deploy your webservice on application server like tomcat or jboss or glassfish.

//Creating http client
    HttpClient client = HttpClientBuilder.create().build();


    HttpGet request = new HttpGet("localhost:8080/pmtv2/tramitacio/realitzarTramit?params="+params); // call to your webservice with required parameters

    // add request header
    request.addHeader("User-Agent", USER_AGENT);
    HttpResponse response = client.execute(request);

//receiving response
    System.out.println("Response Code : " 
                + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
kirti
  • 3,979
  • 4
  • 25
  • 53
0

Publish the aplication in an aplication server (Tomcat?), obtain a URL where it is published and use some code like this to call it:

HttpURLConnection huc = (HttpURLConnection) url.openConnection();
URL url = new URL(desturl);
huc.setRequestMethod("GET");
byte[] postData = null; 
int postDataLength; 
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.connect();
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();
jordi
  • 1,058
  • 12
  • 27