com.recursivechaos.clearent.service.ClearentService.java Source code

Java tutorial

Introduction

Here is the source code for com.recursivechaos.clearent.service.ClearentService.java

Source

/**
 * Created by Andrew Bell 2/1/2016
 * www.recursivechaos.com
 * andrew@recursivechaos.com
 * Licensed under MIT License 2016. See license.txt for details.
 */

package com.recursivechaos.clearent.service;

import com.recursivechaos.clearent.config.GatewayProperties;
import com.recursivechaos.clearent.domain.GatewayException;
import com.recursivechaos.clearent.domain.Response;
import com.recursivechaos.clearent.domain.Transaction;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

import static org.slf4j.LoggerFactory.getLogger;

@Service
public class ClearentService {

    private static final Logger logger = getLogger(ClearentService.class);

    @Autowired
    GatewayProperties gatewayProperties;

    public Transaction postTransaction(Transaction transaction) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Response> responseEntity;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("api-key", gatewayProperties.getKey());
        HttpEntity<String> request = new HttpEntity<>(transaction.toString(), headers);
        try {
            responseEntity = restTemplate.postForEntity(gatewayProperties.getUrl() + "/transactions", request,
                    Response.class);
        } catch (HttpClientErrorException he) {
            logger.error("Gateway Request Failed: {}", he.getLocalizedMessage());
            logger.error(he.getResponseBodyAsString());
            throw new GatewayException(he.getLocalizedMessage());
        }
        assert responseEntity != null;
        return responseEntity.getBody().getPayload().getTransaction();
    }
}