在websphere中集成市场和集成总线

时间:2017-06-21 17:05:46

标签: rest jira-rest-java-api flipkart-api

我们有以下要求

  1. 集成系统需要调用我们的服务
  2. 我们的服务需要调用FlipKart服务,在请求中附加令牌
  3. 将响应发送回Integration system
  4. 以上内容应该可以无缝地处理GET和PUT请求。

    我在eclipse中开发了一个REST项目,并且能够将GET和PUT响应恢复到Integration。

    然而几乎没有问题

    1. 在Get Requests中,我们明确设置标题并为appication / json生成注释。我们如何为所有类型的请求设置它?
    2. 在Post Response中,我们没有得到整个响应,我们无法在响应中设置应用程序类型(不确定如何!)
    3. 如果应用程序类型为pdf,img等,则所有这些请求都失败。
    4. 有人可以帮忙吗?

      到目前为止实施的代码:

       @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);
              }
          }
      

0 个答案:

没有答案