io.branch.sdk.TitaniumDeferredDeepLinkingSDKModule.java Source code

Java tutorial

Introduction

Here is the source code for io.branch.sdk.TitaniumDeferredDeepLinkingSDKModule.java

Source

/**
* This file was auto-generated by the Titanium Module SDK helper for Android
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
*/
package io.branch.sdk;

import android.app.Activity;
import android.net.Uri;

import java.util.ArrayList;
import java.util.Iterator;

import io.branch.referral.Branch;
import io.branch.referral.BranchError;
import io.branch.referral.util.LinkProperties;

import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import org.appcelerator.kroll.KrollDict;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@Kroll.module(name = "TitaniumDeferredDeepLinkingSDK", id = "io.branch.sdk")
public class TitaniumDeferredDeepLinkingSDKModule extends KrollModule {

    // Standard Debugging variables
    private static final String LCAT = "TitaniumDeferredDeepLinkingSDKModule";
    private static final boolean DBG = TiConfig.LOGD;

    // You can define constants with @Kroll.constant, for example:
    // @Kroll.constant public static final String EXTERNAL_NAME = value;

    public TitaniumDeferredDeepLinkingSDKModule() {
        super();
    }

    @Kroll.onAppCreate
    public static void onAppCreate(TiApplication app) {
        Log.d(LCAT, "inside onAppCreate");
        // put module init code that needs to run when the application is created
    }

    // Test methods
    @Kroll.method
    public String example() {
        Log.d(LCAT, "example called");
        return "hello world";
    }

    @Kroll.getProperty
    public String getExampleProp() {
        Log.d(LCAT, "get example property");
        return "hello world";
    }

    @Kroll.setProperty
    public void setExampleProp(String value) {
        Log.d(LCAT, "set example property: " + value);
    }

    //----------- Methods ----------//
    // Public Methods
    @Kroll.method
    public void initSession() {
        Log.d(LCAT, "start init");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getAutoInstance(TiApplication.getInstance());

        instance.initSession(new SessionListener(), activity.getIntent().getData(), activity);
    }

    @Kroll.method
    public void initSessionWithData(String data) {
        Log.d(LCAT, "start init");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getAutoInstance(TiApplication.getInstance());

        if (data == null) {
            instance.initSession(new SessionListener(), activity.getIntent().getData(), activity);
        } else {
            Uri uri = Uri.parse(data);
            instance.initSession(new SessionListener(), uri, activity);
        }
    }

    @Kroll.method
    public void setDebug() {
        Log.d(LCAT, "start setDebug");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.setDebug();
    }

    @Kroll.method
    public KrollDict getLatestReferringParams() {
        Log.d(LCAT, "start getLatestReferringParams");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        JSONObject sessionParams = instance.getLatestReferringParams();
        if (sessionParams == null) {
            Log.d(LCAT, "return is null");
            return null;
        } else {
            Log.d(LCAT, "return is not null");
            Log.d(LCAT, sessionParams.toString());
        }

        return createSessionDict(sessionParams);
    }

    @Kroll.method
    public KrollDict getFirstReferringParams() {
        Log.d(LCAT, "start getFirstReferringParams");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        JSONObject installParams = instance.getFirstReferringParams();
        if (installParams == null) {
            Log.d(LCAT, "return is null");
            return null;
        } else {
            Log.d(LCAT, "return is not null");
            Log.d(LCAT, installParams.toString());
        }

        return createSessionDict(installParams);
    }

    @Kroll.method
    public void setIdentity(String identity) {
        Log.d(LCAT, "start setIdentity");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.setIdentity(identity);
    }

    @Kroll.method
    public void userCompletedAction(String action) {
        Log.d(LCAT, "start userCompletedAction");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.userCompletedAction(action);
    }

    @Kroll.method
    public void userCompletedActionWithAppstate(String action, JSONObject appState) {
        Log.d(LCAT, "start userCompletedAction with appState");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.userCompletedAction(action, appState);
    }

    @Kroll.method
    public void loadRewards() {
        Log.d(LCAT, "start loadRewards");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.loadRewards(new LoadRewardsListener());
    }

    @Kroll.method
    public void redeemRewards(int value) {
        Log.d(LCAT, "start redeemRewards");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.redeemRewards(value);
    }

    @Kroll.method
    public void getCreditHistory() {
        Log.d(LCAT, "start getCreditHistory");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.getCreditHistory(new CreditHistoryListener());
    }

    @Kroll.method
    public void logout() {
        Log.d(LCAT, "start logout");
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        instance.logout();
    }

    @Kroll.method
    public KrollDict getCredits() {
        Log.d(LCAT, "start getCredits");
        KrollDict response = new KrollDict();
        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        int credits = instance.getCredits();
        response.put("bucket", "default");
        response.put("credits", credits);

        return response;
    }

    @Kroll.method
    public KrollDict getCreditsForBucket(String bucket) {
        KrollDict response = new KrollDict();
        if (bucket == null) {
            Log.d(LCAT, "invalid bucket");
            response.put("message", "Invalid bucket");
            return response;
        }

        Log.d(LCAT, "start getCreditsForBucket" + bucket);

        final Activity activity = this.getActivity();
        final Branch instance = Branch.getInstance(activity);

        int credits = instance.getCreditsForBucket(bucket);
        response.put("bucket", bucket);
        response.put("credits", credits);

        return response;
    }

    // Private Methods
    private KrollDict createSessionDict(JSONObject data) {
        Log.d(LCAT, "start createSessionDict");
        KrollDict sessionDict = new KrollDict();
        Log.d(LCAT, "data: ");
        Log.d(LCAT, data.toString());

        sessionDict = parseJSONObject(data);
        return sessionDict;
    }

    private KrollDict parseJSONObject(JSONObject jsonObject) {
        Log.d(LCAT, "start parseJSONObject");
        KrollDict dict = new KrollDict();
        Iterator<?> keys = jsonObject.keys();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            Log.d(LCAT, "processing key: " + key);
            Log.d(LCAT, "key instance: " + jsonObject.opt(key).getClass().getName());
            if (jsonObject.opt(key) instanceof JSONObject) {
                Log.d(LCAT, "recursing...");
                JSONObject jsonObj;
                try {
                    jsonObj = jsonObject.getJSONObject(key);
                    KrollDict tempDict = new KrollDict();
                    tempDict = parseJSONObject(jsonObj);
                    dict.put(key, tempDict);
                } catch (JSONException exception) {
                    Log.d(LCAT, "invalid json passed");
                }
            } else if (jsonObject.opt(key) instanceof JSONArray) {
                Log.d(LCAT, "processing jsonarray...");
                try {
                    String[] stringArray = parseJSONArray(jsonObject.getJSONArray(key));
                    dict.put(key, stringArray);
                } catch (JSONException exception) {
                    Log.d(LCAT, "invalid jsonarray passed");
                }
            } else if (jsonObject.opt(key) == JSONObject.NULL) {
                Log.d(LCAT, "null object");
                dict.put(key, null);
            } else {
                Log.d(LCAT, "not recursing...");
                dict.put(key, jsonObject.opt(key));
            }
        }

        return dict;
    }

    private String[] parseJSONArray(JSONArray jsonArray) {
        Log.d(LCAT, "start parseJSONArray");
        ArrayList<Object> list = new ArrayList<Object>();
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    Object value = jsonArray.get(i);
                    if (value == JSONObject.NULL) {
                        Log.d(LCAT, "null object");
                        value = null;
                    }
                    list.add(value);
                } catch (JSONException exception) {
                    Log.d(LCAT, "invalid object");
                }
            }
        }

        String[] stringArray = list.toArray(new String[list.size()]);

        return stringArray;
    }

    //----------- Inner Classes: Listeners ----------//
    protected class SessionListener implements Branch.BranchReferralInitListener {
        // Listener that implements BranchReferralInitListener for initSession
        @Override
        public void onInitFinished(JSONObject referringParams, BranchError error) {
            Log.d(LCAT, "inside onInitFinished");
            TitaniumDeferredDeepLinkingSDKModule self = TitaniumDeferredDeepLinkingSDKModule.this;
            if (error == null) {
                // params are the deep linked params associated with the link that the user clicked -> was re-directed to this app
                // params will be empty if no data found

                if (referringParams == null) {
                    Log.d(LCAT, "return is null");
                    return;
                } else {
                    Log.d(LCAT, "return is not null");
                    Log.d(LCAT, referringParams.toString());
                }

                self.fireEvent("bio:initSession", createSessionDict(referringParams));
            } else {
                String errorMessage = error.getMessage();
                Log.d(LCAT, errorMessage);
                KrollDict response = new KrollDict();
                response.put("error", errorMessage);
                self.fireEvent("bio:initSession", response);
            }
        }
    }

    protected class LoadRewardsListener implements Branch.BranchReferralStateChangedListener {
        // Listener that implements BranchReferralStateChangedListener for loadRewards
        @Override
        public void onStateChanged(boolean changed, BranchError error) {
            // changed boolean will indicate if the balance changed from what is currently in memory
            Log.d(LCAT, "inside onStateChanged");
            TitaniumDeferredDeepLinkingSDKModule self = TitaniumDeferredDeepLinkingSDKModule.this;
            KrollDict response = new KrollDict();
            if (error == null) {
                // will return the balance of the current user's credits
                final Activity activity = self.getActivity();
                final Branch instance = Branch.getInstance(activity);
                int credits = instance.getCredits();
                response.put("credits", credits);
            } else {
                String errorMessage = error.getMessage();
                Log.d(LCAT, errorMessage);
                response.put("error", errorMessage);
            }
            self.fireEvent("bio:loadRewards", response);

        }
    }

    protected class CreditHistoryListener implements Branch.BranchListResponseListener {
        // Listener that implements BranchListResponseListener for getCreditHistory
        @Override
        public void onReceivingResponse(JSONArray list, BranchError error) {
            // changed boolean will indicate if the balance changed from what is currently in memory
            Log.d(LCAT, "inside onReceivingResponse");
            TitaniumDeferredDeepLinkingSDKModule self = TitaniumDeferredDeepLinkingSDKModule.this;
            if (error == null) {
                // show the list in your app
                ArrayList<KrollDict> data = new ArrayList<KrollDict>();
                if (list != null) {
                    int len = list.length();
                    for (int i = 0; i < len; i++) {
                        JSONObject jsonObject;
                        try {
                            jsonObject = list.getJSONObject(i);
                            KrollDict dict = parseJSONObject(jsonObject);
                            data.add(dict);
                        } catch (JSONException exception) {
                            Log.d(LCAT, "Invalid JSONObject passed");
                            return;
                        }
                    }
                }
                self.fireEvent("bio:getCreditHistory", data);
            } else {
                String errorMessage = error.getMessage();
                Log.d(LCAT, errorMessage);
                KrollDict response = new KrollDict();
                response.put("error", errorMessage);
                self.fireEvent("bio:getCreditHistory", response);
            }
        }
    }
}