2

We have a requirement as below

  1. Integration System needs to call our service
  2. Our service needs to call FlipKart service appending the token in the request
  3. Get the response back to Integration system

The above should work seamlessly for both GET and PUT requests.

I had developed a REST-project in eclipse and was able to get the GET and PUT response back to Integration.

However have few problems

  1. In Get Requests, we are explicitly setting the headers and produces annotation to appication/json. How do we set it for all kind of requests?
  2. In Post Response, we do not get the entire response and we are not able to set the application type in the response (Not sure how!)
  3. All these requests are failing if the application type is pdf, img etc.

Can someone please help on the same?

Code implemented so far:

 @GET
    @Path("{pathvalue : (.+)?}")
    @Produces("{application/json;application/octet-stream}")
    public String getFlipKartResponse(@Context UriInfo uriInfo, @PathParam("pathvalue") String pathValue, @Context  HttpServletRequest request) throws ClassNotFoundException,IOException {
        String methodName = "getFlipKartResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }       
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();

        //if(null == flipkartUrl || flipkartUrl.isEmpty())
            flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
        String queryParam = new String();
        Iterator<String> iterator = queryParams.keySet().iterator();

        while (iterator.hasNext()) {
            String parameter = iterator.next();
            queryParam = queryParam.concat(parameter + ServiceConstants.EQUALS + queryParams.getFirst(parameter) + ServiceConstants.AMPERSAND);
        }
        String modifiedflipkartUrl = flipkartUrl.concat(pathValue).concat(ServiceConstants.QUESTION).concat(queryParam);
        if (modifiedflipkartUrl.endsWith(ServiceConstants.QUESTION) || modifiedflipkartUrl.endsWith(ServiceConstants.AMPERSAND)) {
            modifiedflipkartUrl = modifiedflipkartUrl.substring(0, modifiedflipkartUrl.length()-1);
        }

        LOGGER.log(Level.INFO, "Flipkart URL framed : "+ modifiedflipkartUrl);

        url = new URL(modifiedflipkartUrl);
        connection = (HttpsURLConnection) url.openConnection();
        setHeadersInConnectionObject(url, connection, request.getMethod());
        return handleInvalidToken(connection.getResponseCode(), request);
    }

    private String handleInvalidToken(int responseCode, HttpServletRequest request){
        try {
        if (connection.getResponseCode() == 401) {
               LOGGER.log(Level.INFO, "ResponseCode " + connection.getResponseCode());                 
               connection.disconnect(); 
               regenerateAccessToken();
               connection = (HttpsURLConnection) url.openConnection();
               setHeadersInConnectionObject(url, connection, request.getMethod());
               inputLine =  new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else if (connection.getResponseCode() == 200) {
               inputLine =  new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
               inputLine =  new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        String responseInputLine;
        String responseMessage = "";
        while (null != (responseInputLine = inputLine.readLine())) {
               responseMessage = responseMessage + responseInputLine;
        }
        inputLine.close();  
        connection.disconnect();
        return responseMessage;          
        } catch (Exception e) {
               LOGGER.log(Level.SEVERE,"Exception occured while calling service.Please try again after sometime : ", e);
               return this.handleErrorResponse("Exception occured while calling service.Please try again after sometime.");
        }
  }


    private void regenerateAccessToken() throws ClassNotFoundException, IOException, SQLException{
        TokenGenerator tokenGenerator = new TokenGenerator();
        accessToken= tokenGenerator.getAccessToken();
    }

    @POST
    @Path("{pathvalue : (.+)?}")
    @Produces({"application/json;application/octet-stream"})
    public String getFlipKartPostResponse(@Context UriInfo uriInfo, @PathParam("pathvalue") String pathValue,@Context  HttpServletRequest requestBody) throws ClassNotFoundException,IOException, SQLException {
        String methodName = "getFlipKartPostResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        //if(null == flipkartUrl || flipkartUrl.isEmpty())
            flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
        String modifiedflipkartUrl = flipkartUrl + pathValue;
        url = new URL(modifiedflipkartUrl);
        LOGGER.log(Level.INFO, "Flipkart URL framed : "+ flipkartUrl);

        connection = (HttpsURLConnection) url.openConnection();
        setHeadersInConnectionObject(url, connection, requestBody.getMethod());

        InputStream requestInputStream = requestBody.getInputStream();
        String reqBody = getStringFromInputStream(requestBody.getInputStream());

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(reqBody.getBytes());
        outputStream.flush();

        if(connection.getResponseCode() == 401) {
            connection.disconnect(); 
            regenerateAccessToken();
            connection = (HttpsURLConnection) url.openConnection();
            setHeadersInConnectionObject(url, connection, requestBody.getMethod());

            outputStream = connection.getOutputStream();
            outputStream.write(reqBody.getBytes());
            outputStream.flush();
        }
        String output = getStringFromInputStream (connection.getInputStream());
        connection.disconnect();

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }   
        return output;
    }



    private static String getStringFromInputStream(InputStream is) {
        String methodName = "getStringFromInputStream";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }   
        return sb.toString();

    }
    /**
     * Method to generate the access token
     * @return String - Access token
     * @throws IOException
     */
    private String getAccessToken() throws IOException {
        if (null != accessToken) {
            return accessToken;
        } else {
            url = getClass().getResource(ServiceConstants.ACCESS_TOKEN_CONFIG_PATH);
            file = new File(url.getPath());     
            reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), ServiceConstants.UTF_ENCODING));        
            accessToken = reader.readLine();
            reader.close();
            return accessToken;
        }
    }

    /**
     * Method to construct error response for exception scenario
     * @param errorMessage
     * @return
     */
    private String handleErrorResponse(String errorMessage) {
        String methodName = "handleErrorResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        JSONObject errorResponse = new JSONObject();
        JSONArray errorMsg = new JSONArray();
        errorResponse.put(ServiceConstants.STATUS, ServiceConstants.STATUS_FAILED);
        errorResponse.put(ServiceConstants.ERROR_MESSAGE, errorMessage);
        errorMsg.add(errorResponse);

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }       
        return errorResponse.toString();        
    }

    /**
     * Method to form the connection object 
     * @param url
     * @param connection
     * @param requestType
     * @throws IOException
     */
    private void setHeadersInConnectionObject(URL url, HttpsURLConnection connection, String requestType) throws IOException {
        String methodName = "setHeadersInConnectionObject";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        if (null == accessToken) {
            getAccessToken();
        }
        connection.setRequestMethod(requestType);
        connection.setRequestProperty(ServiceConstants.AUTHORIZATION, ServiceConstants.BEARER + accessToken);
        connection.setDoOutput(true);

        if (requestType.equals(ServiceConstants.REQUEST_TYPE_GET)) {            
            connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.ACCEPT_ALL);
            //connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
        }

        if (requestType.equals(ServiceConstants.REQUEST_TYPE_POST)) {
            connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);           
            connection.setRequestProperty(ServiceConstants.CONTENT_TYPE_HEADER, ServiceConstants.APPLICATION_JSON);
            //connection.setDoInput(true);
        }

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }
    }
arvind_cool
  • 293
  • 1
  • 13

0 Answers0