Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3637

How to return different status codes 400, 404, 500 when calling Rest API from the UI? [closed]

$
0
0

I am calling a REST API from UI. REST API then calls a SOAP API. I did the mapping between REST and SOAP. The issue is how to return status codes/status message to UI when calling the REST API.

  1. In case of input value wrong, the SOAP request returns a fault code. How to return 400 from SOAP (AckConfirmSoapClient) to the REST controller (AcknowledgementController)?
  2. In case SOAP API is down, how to return 500 from SOAP (AckConfirmSoapClient) to RESTcontroller (AcknowledgementController)?
  3. In case of any other issues, how to return 500 Internal Server Error?
  4. If everything is fine, then return HTTP status code OK?

My code work fine if everything is fine, REST API return status code OK.Please help where to make the change in REST controller or SOAP client class which catches the exception and returns status code 400, 404 and 500.

//AcknowledgementController.java. Calling RestAPI from UIpublic class AcknowledgementController {    @Autowired    AckConfirmSoapClient eConfirmSoapClient;    public AcknowledgementController(){      super();    }    @PostMapping("/acknowledgement")    public ResponseEntity<EConfirmResponse> postConfirmation(@Valid @RequestBody EConfirmRequest                                                                        eConfirmRequest) throws InterruptedException        {        try        {        EConfirmResponse eConfirmResponse = eConfirmSoapClient.callConfirm(eConfirmRequest);        return new ResponseEntity<>(eConfirmResponse, HttpStatus.OK);        }      catch (WebServiceException ex) {        if (eConfirmResponse != null && eConfirmResponse.getSystemErrors() != null && eConfirmResponse.getSystemErrors().size() > 0) {          return ResponseEntity.status(500).body(eConfirmResponse);        }        else        {          return new ResponseEntity<>(eConfirmResponse, HttpStatus.INTERNAL_SERVER_ERROR);        }      }     }  }______________________________//AckConfirmSoapClient. Calling SOAP API, return fault code in response in case of bad request @Servicepublic class AckConfirmSoapClient {  @Value("${eConfirm.url}")  private String eConformUrl;  @Autowired  @Qualifier("eConfirmWebServiceTemplate")  private WebServiceTemplate eConfirmWebServiceTemplate;  public EConfirmResponse callConfirm(EConfirmRequest eConfirmRequest) {    EConfirmResponse eConfirmResponse = new EConfirmResponse();    EConfirmResponseType eConfirmResponseType = null;    EConfirmRequestType eConfirmRequestType = EConfirmRequestMapper.mapRequestFromRestToSoap(eConfirmRequest);    WFContextType contextType = buildWfContext(eConfirmRequest);    try    {      eConfirmResponseType = marshaleConfirm(eConfirmRequestType, contextType);      if(eConfirmResponseType.getWFFaultList() == null) {        eConfirmResponse = eConfirmResponseMapper.mapResponseFromSoapToRest(eConfirmResponseType);      }      else      {        throw new CommonWebClientException(APP_ID_QF, null, null, null);      }    }    catch (SoapFaultClientException | WebServiceIOException | CommonWebClientException exp)    {      if (eConfirmResponseType.getWFFaultList() != null) {        eConfirmResponse = eConfirmResponseMapper.mapeConfirmErrorResponse(eConfirmResponseType);       } else {        throw new CommonWebClientException(APP_ID_QF, exp, null, null);      }   }   return eConfirmResponse;  }  public eConfirmResponseType marshaleConfirm(eConfirmRequestType eConfirmRequestType, WFContextType contextType) throws CommonWebClientException {    String response = Constants.EMPTY;    ObjectMapper mapper = new ObjectMapper();    eConfirmResponseType eConfirmResponseType = null;    //Get the response payload    JAXBElement<eConfirmResponseType> jaxbResponsePayload = getResponsePayload(eConfirmRequestType, contextType);    //Convert the response payload to string     try {      response = mapper.writeValueAsString(jaxbResponsePayload);    } catch (JsonProcessingException e) {      log.error("JsonProcessingException: ", e);    }    eConfirmResponseType = jaxbResponsePayload.getValue();    return eConfirmResponseType;  }  private JAXBElement<eConfirmResponseType> getResponsePayload(eConfirmRequestType eConfirmRequestType, WFContextType contextType) throws CommonWebClientException {      ObjectFactory eDeliveryConfirm = new ObjectFactory();      JAXBElement<eConfirmRequestType> jaxbeConfirmRequestType = eDeliveryConfirm.createEConfirmRequest(eConfirmRequestType);    try {    } catch (JAXBException e) {      log.error("JAXBException while JAXBUtil request marshalToXml: " + e);    }     //marshalSendAndReceive returns plain object (not JAXBElement)    Object response = eConfirmWebServiceTemplate.marshalSendAndReceive(eConformUrl, jaxbeConfirmRequestType,          getWebServiceMessageCallback(contextType));    ObjectMapper objectMapper = new ObjectMapper();    try {          LOGGER.info("mapped and marshalledToXml request payload for eConfirm SOAP call: " + objectMapper.writeValueAsString(response));      } catch (JsonProcessingException e) {          LOGGER.error("xml marshalling exception while calling JAXBUtil: ", e);      }      return  (JAXBElement<eConfirmResponseType>) response;  }  private WebServiceMessageCallback getWebServiceMessageCallback(WFContextType context) {    log.debug("Started getWebServiceMessageCallback");    return message -> {      SaajSoapMessage soapMessage = (SaajSoapMessage) message;      soapMessage.setSoapAction(IntegrationConstants.SOAP_ACTION_EIEP_EDELIVERY_CONFIRM);      SoapHeader soapHeader = soapMessage.getSoapHeader();      // create a marshaller      try {        setHeader(soapHeader, context);      } catch (JAXBException e) {        log.error("JAXBException while getWebServiceMessageCallback: " + e);      }      try {        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        message.writeTo(byteArrayOutputStream);        byteArrayOutputStream.close();      } catch (IOException ex) {        log.error("IOException while getWebServiceMessageCallback: " + ex);      }    };  }  private void setHeader(SoapHeader soapHeader, WFContextType wfContext) throws JAXBException, WebServiceException {    try {      JAXBContext context = JAXBContext.newInstance(WFContextType.class);      Marshaller marshaller = context.createMarshaller();      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);      JAXBElement<WFContextType> jaxbElementWFContext =        new JAXBElement<>(new QName(IntegrationConstants.QNAME_EIEP_MESSAGE_2007, IntegrationConstants.WF_CONTEXT_LOCAL_PART), WFContextType.class, wfContext);      log.info("mapped and marshalledToXml request headers to eConfirm SOAP call: " + JAXBUtil.marshalToXml(jaxbElementWFContext));      marshaller.marshal(jaxbElementWFContext, soapHeader.getResult());    }    catch (WebServiceException | JAXBException ex) {      log.error("IOException while getWebServiceMessageCallback: " + ex);    }  }  public WFContextType buildWfContext(EConfirmRequest eConfirmRequest) {    WFContextType wfContext = new WFContextType();    // unique id per message    String hostname = null;    try    {      hostname = getHostname();    }    catch (UnknownHostException e) {      LOGGER.error("UnknownHostException while buildWfContext: " + e);    }    wfContext.setMessageId(hostname + Constants.COLON + new UID());    // unique id per set of requests    SessionType session = new SessionType();    if (eConfirmRequest != null) {      session.setSessionId(eConfirmRequest.getContext().getSessionId());      // ID of the application creating the message      wfContext.setApplicationId(eConfirmRequest.getContext().getAplicationId());    }    // step count within the "session".  first message must be 1.    session.setSessionSequenceNumber(Constants.STRING_ONE);    wfContext.setSession(session);    wfContext.setCreationTimestamp(getCreationTimestamp());    wfContext.setHostName(hostname);    // identifies the server, instance, or queue of the message creator    wfContext.setInvokerId(wfContext.getHostName());    return wfContext;  }  private static String getHostname() throws UnknownHostException {    return InetAddress.getLocalHost().getHostName();  }  private XMLGregorianCalendar getCreationTimestamp() {    XMLGregorianCalendar creationTimestamp = null;    try {      creationTimestamp = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());    } catch (DatatypeConfigurationException e) { e);    }    return creationTimestamp;  }}------------------------------------------------------------______________//mapping response soap to restpublic class EConfirmResponseMapper {    private EConfirmResponseMapper() {      super();    }    public static EConfirmResponse mapResponseFromSoapToRest(EConfirmResponseType eConfirmResponseSoap) {        EConfirmResponse eConfirmResponse = new EConfirmResponse();      if(eConfirmResponseSoap == null){        return null;      }      eConfirmResponse.setUuid(eConfirmResponseSoap.getUUID());      return eConfirmResponse;    }    public static eConfirmResponse mapeConfirmErrorResponse(eConfirmResponseType eConfirmResponseSoap) throws CommonException {      eConfirmResponse eConfirmResponse = new eConfirmResponse();      if(eConfirmResponseSoap == null){        return null;      }      List<SystemError> eConfirmResponseSystemError = new ArrayList<>();      SystemError systemError = new SystemError();      if (eConfirmResponseSoap != null && eConfirmResponseSoap.getWFFaultList() != null) {        for (WFFaultType eiepSoapFaultList : eConfirmResponseSoap.getWFFaultList().getWFFault()) {          systemError.setCreatorApplicationId(Constants.APP_ID_QF);          systemError.setCode(eiepSoapFaultList.getSeverity().value());          systemError.setSubCode(Constants.EIEP_ERROR_CODE);          systemError.setMessage("FaultCode :" + eiepSoapFaultList.getFaultCode() +"," + Constants.SPACE +            eiepSoapFaultList.getFaultReasonText() + Constants.SPACE + eiepSoapFaultList.getTechnicalText());          eConfirmResponseSystemError.add(systemError);        }        eConfirmResponse.setSystemErrors(eConfirmResponseSystemError);      }      return eConfirmResponse;    }  }

Viewing all articles
Browse latest Browse all 3637

Trending Articles