com.opensky.osis.BraintreeConnector.java Source code

Java tutorial

Introduction

Here is the source code for com.opensky.osis.BraintreeConnector.java

Source

/**
 * Mule Development Kit
 * Copyright 2010-2011 (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This file was automatically generated by the Mule Development Kit
 */
package com.opensky.osis;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.Validate;
import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.Module;
import org.mule.api.annotations.Processor;
import org.mule.api.annotations.param.Default;
import org.mule.api.annotations.param.Optional;
import org.mule.transformer.simple.BeanToMap;
import org.mule.util.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.Environment;
import com.braintreegateway.Result;
import com.braintreegateway.Transaction;
import com.braintreegateway.Transaction.Type;
import com.braintreegateway.TransactionCloneRequest;
import com.braintreegateway.TransactionRequest;
import com.braintreegateway.exceptions.BraintreeException;

/**
 * Cloud Connector
 *
 * @author MuleSoft, Inc.
 */
@Module(name = "braintree", schemaVersion = "2.0")
public class BraintreeConnector {
    private transient final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * The environment
     */
    @Configurable
    @Optional
    @Default(value = "SANDBOX")
    private String env;

    /**
     * The merchant id
     */
    @Configurable
    @Optional
    private String merchantId;

    /**
     * The public key
     */
    @Configurable
    @Optional
    private String publicKey;

    /**
     * The private key
     */
    @Configurable
    @Optional
    private String privateKey;

    /**
     * The request factory
     */
    @Configurable
    @Optional
    private BraintreeRequestFactory requestFactory;

    /**
     * The gateway
     */
    @Configurable
    @Optional
    private BraintreeGateway gateway;

    protected BraintreeRequestFactory getRequestFactory() {
        if (null == requestFactory) {
            requestFactory = new DefaultBraintreeRequestFactoryImpl();
        }

        return requestFactory;
    }

    protected BraintreeGateway getGateway() {
        if (null == gateway) {
            Environment env2Use = Environment.valueOf(this.env.toUpperCase());
            gateway = new BraintreeGateway(env2Use, this.merchantId, this.publicKey, this.privateKey);
        }

        return gateway;
    }

    /**
     * Clone a transaction
     * 
     * TODO Should amount be optional?
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:clone-transaction}
     *
     * @param originalTxId The original transaction id
     * @param amount The new amount to auth for
     * @param settle to settle or not
     * @return The transaction
     */
    @Processor
    public Result cloneTransaction(String originalTxId, BigDecimal amount,
            @Optional @Default(value = "false") Boolean settle) {
        log.info("Cloning transaction {} with amount {} settle {}", new Object[] { originalTxId, amount, settle });

        Validate.notNull(originalTxId, "Original transaction id must not be null");
        Validate.notNull(amount, "amount should not be null");
        Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");

        TransactionCloneRequest txCloneReq = getRequestFactory().transactionCloneRequest().amount(amount).options()
                .submitForSettlement(settle).done();
        try {
            return getGateway().transaction().cloneTransaction(originalTxId, txCloneReq);
        } catch (BraintreeException e) {
            return new ExceptionResult(e.getClass().getCanonicalName());
        }
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:retrieve-transaction}
     * 
     * @param txId The transaction id
     * @return The transaction
     */
    @Processor
    public Transaction retrieveTransaction(String txId) {
        Transaction res = getGateway().transaction().find(txId);

        return res;
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:settle}
     *
     * @param id The transaction id
     * @param amount the amount of the transaction
     * @return The transaction
     */
    @Processor
    public Result settle(String id, BigDecimal amount) {
        log.info("Settling transaction {} amount {}", id, amount);

        Validate.notNull(id, "token should not be null");
        Validate.notNull(amount, "amount should not be null");
        Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");

        try {
            Result<Transaction> res = getGateway().transaction().submitForSettlement(id, amount);
            return res;
        } catch (BraintreeException e) {
            return new ExceptionResult(e.getClass().getCanonicalName());
        }
    }

    /**     
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:capture}
     * 
     * @param id The id
     * @param amount The amount
     * @return the Result
     */
    @Processor
    public Result capture(String id, BigDecimal amount) {
        return settle(id, amount);
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:void-tx}
     *
     * @param id The transaction id
     * @return The transaction
     */
    @Processor
    public Result voidTx(String id) {
        log.info("Void transaction {}", id);

        Validate.notNull(id, "Transaction id must not be null");

        try {
            Result<Transaction> res = getGateway().transaction().voidTransaction(id);
            return res;
        } catch (BraintreeException e) {
            return new ExceptionResult(e.getClass().getCanonicalName());
        }
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:sale}
     *
     * @param token The payment method token
     * @param amount The transaction amount
     * @param orderId The order id
     * @param customerId The customer id
     * @param settle Flag to settle immediately or just auth
     * @return The Result
     */
    @Processor
    public Result sale(String token, BigDecimal amount, String orderId, String customerId,
            @Optional @Default(value = "false") Boolean settle) {
        log.info("Calling sale with token: {} amount: {} orderId: {} customerId: {} settle: {}",
                new Object[] { token, amount, orderId, customerId, settle });

        Validate.notNull(token, "token should not be null");
        Validate.notNull(amount, "amount should not be null");
        Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");
        Validate.notNull(orderId, "orderId should not be null");
        Validate.notNull(customerId, "customerId should not be null");

        try {
            TransactionRequest request = getRequestFactory().transactionRequest().amount(amount).type(Type.SALE)
                    .orderId(orderId).customerId(customerId).paymentMethodToken(token).options()
                    .submitForSettlement(settle).done();

            Result<Transaction> res = getGateway().transaction().sale(request);
            return res;
        } catch (BraintreeException e) {
            return new ExceptionResult(e.getClass().getCanonicalName());
        }
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:auth}
     *
     * @param token the token
     * @param amount the amount
     * @param orderId the order id
     * @param customerId the customer id
     * @return the Result
     */
    @Processor
    public Result auth(String token, BigDecimal amount, String orderId, String customerId) {
        return sale(token, amount, orderId, customerId, false);
    }

    /**
     * Custom processor
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:auth-capture}
     *
     * @param token the token
     * @param amount the amount
     * @param orderId the order id
     * @param customerId the customer id
     * @return the Result
     */
    @Processor
    public Result authCapture(String token, BigDecimal amount, String orderId, String customerId) {
        return sale(token, amount, orderId, customerId, true);
    }

    /**
     * Refund the given transaction
     *
     * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:refund}
     * 
     * @param txId Transaction id
     * @param amount The amount
     * @return The result
     */
    @Processor
    public Result refund(String txId, @Optional BigDecimal amount) {
        log.info("Refunding tx {} by {}", txId, amount);
        Result<Transaction> result;
        if (null == amount) {
            result = getGateway().transaction().refund(txId);
        } else {
            Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");
            result = getGateway().transaction().refund(txId, amount);
        }

        log.debug("Refund {}", result);

        return result;
    }

    public void setMerchantId(String merchantId) {
        this.merchantId = merchantId;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public void setEnv(String env) {
        this.env = env;
    }

    public void setGateway(BraintreeGateway gateway) {
        this.gateway = gateway;
    }

    public void setRequestFactory(BraintreeRequestFactory factory) {
        this.requestFactory = factory;
    }
}

class ExceptionResult extends Result<Throwable> {
    private String msg;

    public ExceptionResult(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMessage() {
        return this.msg;
    }

    @Override
    public boolean isSuccess() {
        return false;
    }
}