-1

I want to develop the spring rest web service which accesses the external API when user sends request. User sends a json request and set of request headers to the web service and web service should authenticate the user and call the eternal API. External API response should be given to the user as the response body. This is what I want to happen basically.

//Authenticate to access API

public class HotelbedsAuthentication {

    final String hotelEndpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/";
    private String request;

    private static final String apiKey="enter given api key for free";
    private static final String secretKey="free key";
    private String signature=org.apache.commons.codec.digest.DigestUtils.sha256Hex(apiKey + secretKey + System.currentTimeMillis() / 1000);

    public HttpsURLConnection findHotels(){

        HttpsURLConnection connection = null;

        try{

        URL url = new URL(hotelEndpoint+getRequest());

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestProperty("X-Signature", signature);
        con.setRequestProperty("Api-Key", apiKey);
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setDoInput (true);

        connection=con;
        }catch(Exception error ){
            System.out.println("An error occured "+error);
        }
        return connection;
    }

    public String getRequest() {
        return request;
    }

    public void setRequest(String request) {
        this.request = request;
    }

}

//Rest Controller

public class FindHotelController {

    HotelbedsAuthentication token = new HotelbedsAuthentication();

@RequestMapping(value="hotels",method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public HotelAvailability findHotel(@RequestBody JSONObject request){

        HttpsURLConnection connection;

        File pathDir = new File("C:/Users/User/workspace/SpringRestSample/src/main/java");

        JCodeModel codeModel = new JCodeModel();
        JSONObject response= new JSONObject();

        HotelAvailability sample= new HotelAvailability();

        //String userRequest="{\"stay\": {\"checkIn\": \"2018-01-29\",\"checkOut\": \"2018-01-31\",\"shiftDays\": \"2\"},\"occupancies\": [{\"rooms\": 1,\"adults\": 2,\"children\": 1,\"paxes\": [{\"type\": \"AD\",\"age\": 30},{\"type\": \"AD\",\"age\": 30},{\"type\": \"CH\",\"age\": 8}]}],\"hotels\": {\"hotel\": [1067,1070,1075,135813,145214,1506,1508,1526,1533,1539,1550,161032,170542,182125,187939,212167,215417,228671,229318,23476]}}";

        try{
            token.setRequest("hotels");
            connection= token.findHotels();

            //Read request and embed to url
            OutputStream os = connection.getOutputStream();
            os.write(request.toString().getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(connection.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);
            response=jsonObject;

            GenerationConfig config = new DefaultGenerationConfig() {
              @Override
              public boolean isGenerateBuilders() {
                  return true;
              }
              public SourceType getSourceType(){
                  return SourceType.JSON;
              }
            };

            SchemaMapper mapper =new SchemaMapper(new RuleFactory(config, new GsonAnnotator(config), new SchemaStore()), new SchemaGenerator());
            mapper.generate(codeModel, "HotelAvailability","com.sample.model",response.toString());

            codeModel.build(pathDir);

            ObjectMapper objectMapper = new ObjectMapper();
            sample = objectMapper.readValue(response.toString(), HotelAvailability.class);

            in.close();
            connection.disconnect();

        }catch(Exception ex){
            System.out.println(ex);
        }
        System.out.println(sample);
        return sample;
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Amila Perera
  • 69
  • 2
  • 8
  • 2
    What have you tried so far. What you are trying to accomplish is pretty straight forward. – shazin Jan 04 '18 at 04:20
  • @shazin I tried with free given API. I can send request to the API directly via web service but I want to develop the middle layer which is the web service which servers the user when he sends request. His request should go to the external API via my web service with authentication done in web service – Amila Perera Jan 04 '18 at 05:05
  • You need to show what you have tried to accomplish this task. You can do it easily with Spring Web MVC, Spring Security and a RestTemplate. – shazin Jan 04 '18 at 05:14
  • 1
    [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236/18157) – Jim Garrison Jan 04 '18 at 05:27
  • Probably voted as not a question because it sounds a LOT like someone posting their homework assignment, and they have not tried even basic research before posting as this is an extremely common process there are huge numbers of examples of. – BrianC Jan 08 '18 at 20:36

1 Answers1

1

What you're looking for is an API Gateway or a simple router based on your requirements. If you need to make changes to the response, you need a Gateway. If you're looking to simply pass the request then you need a router.

There are many ways to do this, but as always, Spring has already built a tool for that. check out Zuul. This will allow you to integrate with an Authentication provider and then delegate requests to microservices.

Gateway https://www.intertech.com/Blog/spring-integration-tutorial-part-8-gateways/

OAuth Provider https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_authserver

Router https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html

Garry Taylor
  • 940
  • 8
  • 19