Android Open Source - RICurrencyConversion-Android Currency Conversion Task






From Project

Back to project page RICurrencyConversion-Android.

License

The source code is released under:

MIT License

If you think the Android project RICurrencyConversion-Android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package de.rocketinternet.currencyconversion;
/* ww w .  j av  a  2s  .  com*/
import android.app.Activity;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Asynchronous task to apply a money value conversion based on an input value, an origin currency
 * code and a target currency code.
 * The class allows to register a listener interface to be called with the converted output value
 * when the conversion has finished.
 */
public class CurrencyConversionTask extends AsyncTask<CurrencyConversionInput, Void, ConversionResult> {

    /**
     * Completion listener being called on finishing the conversion task
     */
    private OnCompleteListener<ConversionResult> _listener = null;

    /**
     * A temporary storage of the conversion output to bridge listener un-/registration
     */
    private ConversionResult _result = null;

    /**
     * Override default constructor to be private to restrict instantiation to convenience
     * constructor
     */
    private CurrencyConversionTask() {}


    /**
     * Convenience constructor to instantiate a conversion task. It takes an activity object to
     * dispatch the listener operation on the UI thread of the activity. Next it takes the listener
     * itself.
     *
     * @param activity <code>Activity</code> that the listener will be dispatched to
     * @param listener Listener to register.
     */
    public CurrencyConversionTask(Activity activity, OnCompleteListener<ConversionResult> listener) {
        this();
        register(activity, listener);
    }

    /**
     * Dedicated exception to the task used internally to resolve errors during the conversion task
     */
    public class ConversionException extends Exception {
        public ConversionException(String message) {
            super(message);
        }
    }

    /**
     * Interface for the completion listener. This is the thing that we'll call when things get
     * completed.
     *
     * @param <ConversionResult>
     */
    public interface OnCompleteListener<ConversionResult> {
        public void onComplete(ConversionResult result);
    }

    /* (non-Javadoc)
    * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
    */
    @Override
    protected void onPostExecute(ConversionResult result) {
        if(_listener != null) {
            _listener.onComplete(result);
        } else {
            // save the result so we can defer calling the completion
            // listener when (and if) it re-registers
            _result = result;
        }
    }

    /**
     * Register the listener to be notified with the conversion output when the task completes.
     *
     * @param listener the listener to call
     */
    public void register(Activity activity, OnCompleteListener<ConversionResult> listener) {
        _listener = listener;
        // see if we had a deferred result available
        if (_result != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    _listener.onComplete(_result);
                    _result = null;
                }
            });
        }
    }

    /**
     * Unregister the registered listener.
     */
    public void unregister() {
        _listener = null;
    }

    //private static String URL_FORMAT = "https://openexchangerates.org/api/convert/%f/%s/%s?app_id=%s";
    private static String URL_FORMAT = "https://finance.yahoo.com/d/quotes.csv?e=.csv&f=l1&s=%s%s=X";


    @Override
    protected ConversionResult doInBackground(CurrencyConversionInput... currencyConversionInputs) {
        Double value = 0.0;
        Error error = null;
        try {
            // Validate conversion operation input parameters
            if (currencyConversionInputs.length != 1) {
                String errMsgFormat = "Invalid amount of input parameters %d, expected 1";
                String errMsg = String.format(errMsgFormat, currencyConversionInputs.length);
                throw new ConversionException(errMsg);
            }
            CurrencyConversionInput input = currencyConversionInputs[0];
            value = input.getValue();
            String currencyCode = input.getCurrencyCode();
            if (currencyCode == null) {
                throw new ConversionException("Null currency code not allowed");
            }
            if (currencyCode.length() < 3) {
                String errMsgFormat = "Invalid currency code '%s', must have 3 characters";
                String errMsg = String.format(errMsgFormat, currencyCode);
                throw new ConversionException(errMsg);
            }
            String targetCurrencyCode = input.getTargetCurrencyCode();
            if (currencyCode == null) {
                throw new ConversionException("Null target currency code not allowed");
            }
            if (currencyCode.length() < 3) {
                String errMsgFormat = "Invalid target currency code '%s', must have 3 characters";
                String errMsg = String.format(errMsgFormat, currencyCode);
                throw new ConversionException(errMsg);
            }

            // Handle trivial value 0 without web service interaction
            if (value == 0.0f) {
                _result = new ConversionResult(value, error);
                return _result;
            }

            StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            String url = String.format(URL_FORMAT, currencyCode, targetCurrencyCode);
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse response = client.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } else {
                    String errMsgFormat = "Server responded with unexpected status code %d";
                    throw new Exception(String.format(errMsgFormat, statusCode));
                }
            } catch (Exception e) {
                String errMsgFormat = "Error when requesting conversion server: %s";
                String errMsg = String.format(errMsgFormat, e.getMessage());
                throw new ConversionException(errMsg);
            }
            // The desired output of the request is a string of the conversion result floating point
            // value with double precision
            String output = builder.toString();
            if (!output.matches("^[0-9]*[.][0-9]*$")) {
                throw new ConversionException(String.format("Invalid response format: %s", output));
            }
            // Parse the result and validate the retrieved value to be greater than zero
            Double rate = new Double(output);
            if (rate <= 0) {
                String errFormat = "Invalid rate %f, must be greater than zero";
                throw new ConversionException(String.format(errFormat, rate));
            }
            // Calculate the output value by multiplying the input value with the rate. Cast the
            // result to float precision.
            value = new Double(value * rate);
        } catch (ConversionException e) {
            error = new Error(e.getMessage());
        } finally {
            // Generate a conversion result container that holds the conversion result value and an
            // optional error, if occurred during conversion.
            _result = new ConversionResult(value, error);
        }
        return _result;
    }
}




Java Source Code List

de.rocketinternet.currencyconversion.ConversionResult.java
de.rocketinternet.currencyconversion.CurrencyConversionInput.java
de.rocketinternet.currencyconversion.CurrencyConversionTask.java
de.rocketinternet.currencyconversion.MyActivity.java