Panagiotis Triantafyllou

optimize campaigns, new campaign keys

......@@ -3,15 +3,15 @@
# The app uuid the warply sdk need to connect to the engage server
# dev f83dfde1145e4c2da69793abb2f579af
# prod 0086a2088301440792091b9f814c2267
Uuid=0086a2088301440792091b9f814c2267
Uuid=f83dfde1145e4c2da69793abb2f579af
# If we need to see logs in Logcat
Debug=false
Debug=true
# Production or Development environment of the engage server
# Production: https://engage.warp.ly
# Development: https://engage-stage.warp.ly
BaseURL=https://engage.warp.ly
BaseURL=https://engage-stage.warp.ly
# For Verify Ticket request
VerifyURL=/partners/cosmote/verify
......@@ -39,7 +39,7 @@ PushIcon=ic_notify
SendPackages=false
# The app language
Language=el
Language=en
# The merchant id for some requests
MerchantId=20113
......
......@@ -36,7 +36,7 @@ public class SplashActivity extends BaseActivity {
public void onWarplyReady() {
if (!WarplyDBHelper.getInstance(SplashActivity.this).isTableNotEmpty("auth")) {
WarplyManager.getCosmoteUser(new WarplyCosmoteUserRequest()
.setGuid("6010490808"), //6012049321, 6012049322, 6012049323, 7000000831 history, 7000000826, 7000000831 shared coupons, prod 6006552990, prod 6005892749, live 3000184910,prod 7000070282
.setGuid("7000000831"), //6012049321, 6012049322, 6012049323, 7000000831 history, 7000000826, 7000000831 shared coupons, prod 6006552990, prod 6005892749, live 3000184910,prod 7000070282
mLoginReceiver);
} else {
startNextActivity();
......
......@@ -65,6 +65,7 @@ dependencies {
api 'com.github.siyamed:android-shape-imageview:0.9.3'
implementation 'org.greenrobot:eventbus:3.3.1'
api 'org.apmem.tools:layouts:1.10'
api 'com.google.guava:guava:30.1-android'
//------------------------------ Firebase -----------------------------//
api platform('com.google.firebase:firebase-bom:29.0.3')
......
......@@ -50,9 +50,8 @@ public class BaseFragmentActivity extends FragmentActivity implements Navigation
mBottomNavigationView = findViewById(R.id.bt_tabs);
// WarplyManager.getUserCouponsWithCouponsets(new WarplyUserCouponsRequest(), mUserCouponsReceiver);
WarplyManager.getUserCouponsWithCouponsets(mUserCouponsReceiver);
WarplyManager.getCampaigns(new WarplyGetCampaignsRequest().setLanguage("en"), mCampaignsCallback);
WarplyManager.getCampaigns(mCampaignsCallback);
WarplyManager.getUnifiedCouponsDeals(mUnifiedCallback);
}
......@@ -123,7 +122,7 @@ public class BaseFragmentActivity extends FragmentActivity implements Navigation
private final CallbackReceiver<ArrayList<Campaign>> mCampaignsCallback = new CallbackReceiver<ArrayList<Campaign>>() {
@Override
public void onSuccess(ArrayList<Campaign> result) {
Toast.makeText(BaseFragmentActivity.this, "Campaigns Success", Toast.LENGTH_SHORT).show();
Toast.makeText(BaseFragmentActivity.this, "Campaigns Success " + String.valueOf(result.size()), Toast.LENGTH_SHORT).show();
}
@Override
......
......@@ -74,6 +74,8 @@ public class Campaign implements Parcelable, Serializable {
private static final String CAMPAIGN_TYPE_SETTINGS = "campaign_type_settings";
private static final String BANNER_IMAGE = "Banner_img";
private static final String BANNER_TITLE = "Banner_title";
private static final String CATEGORY_ID = "category_id";
private static final String COUPON_AVAILABILITY = "coupon_availability";
/* Member variables of the Campaign object */
......@@ -103,7 +105,8 @@ public class Campaign implements Parcelable, Serializable {
private String campaignTypeSettings;
private String bannerImage;
private String bannerTitle;
private UnifiedCampaignModel unifiedCampaign;
private String categoryId;
private Integer couponAvailability;
/**
* Basic constructor used to create an object from a String, representing a
......@@ -143,7 +146,8 @@ public class Campaign implements Parcelable, Serializable {
this.campaignTypeSettings = "";
this.bannerImage = "";
this.bannerTitle = "";
this.unifiedCampaign = new UnifiedCampaignModel();
this.couponAvailability = null;
this.categoryId = "";
}
/**
......@@ -204,6 +208,8 @@ public class Campaign implements Parcelable, Serializable {
} else {
this.actions = null;
}
this.categoryId = json.optString(CATEGORY_ID);
this.couponAvailability = json.optInt(COUPON_AVAILABILITY);
}
public Campaign(Parcel source) {
......@@ -231,6 +237,8 @@ public class Campaign implements Parcelable, Serializable {
this.actions = source.readArrayList(CampaignAction.class.getClassLoader());
this.busId = source.readString();
this.campaignTypeSettings = source.readString();
this.categoryId = source.readString();
this.couponAvailability = source.readInt();
}
@Override
......@@ -259,6 +267,8 @@ public class Campaign implements Parcelable, Serializable {
dest.writeList(this.actions);
dest.writeString(this.busId);
dest.writeString(this.campaignTypeSettings);
dest.writeInt(this.couponAvailability);
dest.writeString(this.categoryId);
}
/**
......@@ -293,6 +303,8 @@ public class Campaign implements Parcelable, Serializable {
jObj.putOpt(DISPLAY_TYPE, this.displayType);
jObj.put(BUS_ID, this.busId);
jObj.put(CAMPAIGN_TYPE_SETTINGS, this.campaignTypeSettings);
jObj.putOpt(COUPON_AVAILABILITY, this.couponAvailability);
jObj.putOpt(CATEGORY_ID, this.categoryId);
} catch (JSONException e) {
if (WarpConstants.DEBUG) {
e.printStackTrace();
......@@ -366,6 +378,23 @@ public class Campaign implements Parcelable, Serializable {
// Getters
// ================================================================================
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public Integer getCouponAvailability() {
return couponAvailability;
}
public void setCouponAvailability(Integer couponAvailability) {
this.couponAvailability = couponAvailability;
}
/**
* @return The loyalty action of the Campaign, used if custom actions are
* implemented
......@@ -630,14 +659,6 @@ public class Campaign implements Parcelable, Serializable {
this.bannerTitle = bannerTitle;
}
public UnifiedCampaignModel getUnifiedCampaign() {
return unifiedCampaign;
}
public void setUnifiedCampaign(UnifiedCampaignModel unifiedCampaign) {
this.unifiedCampaign = unifiedCampaign;
}
@Override
public int describeContents() {
return 0;
......
......@@ -79,6 +79,21 @@ public class NewCampaignList extends ArrayList<NewCampaign> {
}
}
public NewCampaignList(JSONObject campaignListJSONObject) {
campaignListJSONObject = campaignListJSONObject.optJSONObject(JSON_KEY_CONTEXT);
if (campaignListJSONObject == null)
return;
JSONObject jsonObject = campaignListJSONObject.optJSONObject(JSON_KEY_MAPP);
if(jsonObject == null)
return;;
JSONArray jArray = jsonObject.optJSONArray(JSON_KEY_MAPP_VALUE);
if (jArray != null) {
for (int i = 0, lim = jArray.length(); i < lim; ++i) {
add(new NewCampaign(jArray.optJSONObject(i)));
}
}
}
@NonNull
public String getRequestSignature() {
return mRequestSignature;
......
......@@ -89,20 +89,31 @@ public interface ApiService {
@Header(WarpConstants.HEADER_SIGNATURE) String signature);
@Headers("Content-Type: application/json")
@POST("/api/mobile/v2/{appUuid}/context/")
Call<ResponseBody> getCampaigns(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature);
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> sendTelematicsData(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
Call<ResponseBody> getCampaignsPersonalized(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> cancelUnifiedCoupon(@Path("appUuid") String appUuid,
Call<ResponseBody> sendTelematicsData(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
......@@ -114,19 +125,19 @@ public interface ApiService {
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> getTelematicsHistoy(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
Call<ResponseBody> cancelUnifiedCoupon(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> getTripMetrics(@Path("appUuid") String appUuid,
Call<ResponseBody> getTelematicsHistoy(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
......@@ -138,7 +149,7 @@ public interface ApiService {
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> rateTrip(@Path("appUuid") String appUuid,
Call<ResponseBody> getTripMetrics(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
......@@ -148,6 +159,18 @@ public interface ApiService {
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> rateTrip(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
// ===========================================================
// Getter & Setter
// ===========================================================
......
......@@ -34,6 +34,7 @@ import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.ArrayMap;
......@@ -41,6 +42,13 @@ import androidx.annotation.NonNull;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
......@@ -52,6 +60,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
......@@ -90,6 +99,7 @@ import ly.warp.sdk.io.models.LoyaltySDKDynatraceEventModel;
import ly.warp.sdk.io.models.Merchant;
import ly.warp.sdk.io.models.MerchantCategoriesList;
import ly.warp.sdk.io.models.MerchantList;
import ly.warp.sdk.io.models.NewCampaign;
import ly.warp.sdk.io.models.PacingDetails;
import ly.warp.sdk.io.models.PointsList;
import ly.warp.sdk.io.models.ProductList;
......@@ -150,7 +160,6 @@ import ly.warp.sdk.io.request.WarplyVerifyTicketRequest;
import ly.warp.sdk.io.volley.ApiClient;
import ly.warp.sdk.io.volley.ApiService;
import ly.warp.sdk.services.EventCampaignService;
import ly.warp.sdk.services.EventCouponsService;
import ly.warp.sdk.services.EventUnifiedCouponsService;
import ly.warp.sdk.services.WarplyHealthService;
import ly.warp.sdk.utils.WarpJSONParser;
......@@ -1519,57 +1528,15 @@ public class WarplyManager {
}
}
if (camp.getOfferCategory().equals("questionnaire")) {
// if (WarplyManagerHelper.getConsumerInternal() != null) {
// JSONObject profMetadata = WarpJSONParser.getJSONFromString(WarplyManagerHelper.getConsumerInternal().getProfileMetadata());
// if (profMetadata != null) {
// if (!profMetadata.has("answered")) {
// try {
// JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
// if (extraFields != null) {
// if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
// campaignLoyaltyList.add(camp);
// }
// }
// } catch (Exception exception) {
// campaignLoyaltyList.add(camp);
// }
// }
// } else {
// try {
// JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
// if (extraFields != null) {
// if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
// campaignLoyaltyList.add(camp);
// }
// }
// } catch (Exception exception) {
// campaignLoyaltyList.add(camp);
// }
// }
// } else {
// try {
// JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
// if (extraFields != null) {
// if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
// campaignLoyaltyList.add(camp);
// }
// }
// } catch (Exception exception) {
// campaignLoyaltyList.add(camp);
// }
// }
} else {
try {
JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
if (extraFields != null) {
if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
campaignLoyaltyList.add(camp);
}
try {
JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
if (extraFields != null) {
if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
campaignLoyaltyList.add(camp);
}
} catch (Exception exception) {
campaignLoyaltyList.add(camp);
}
} catch (Exception exception) {
campaignLoyaltyList.add(camp);
}
}
WarplyManagerHelper.setCarouselList(campaignCarouselList);
......@@ -1598,6 +1565,441 @@ public class WarplyManager {
request.getSignature()));
}
private static ArrayList<Campaign> mergeCampaignResults(ArrayList<Campaign> resultCampaigns, ArrayList<Campaign> resultPersonalizedCampaigns) {
ArrayList<Campaign> newCampaignList = new ArrayList<Campaign>();
ArrayList<Campaign> campaignLoyaltyList = new ArrayList<>();
newCampaignList.clear();
if (resultCampaigns != null && resultCampaigns.size() > 0)
newCampaignList.addAll(resultCampaigns);
if (resultPersonalizedCampaigns != null && resultPersonalizedCampaigns.size() > 0)
newCampaignList.addAll(resultPersonalizedCampaigns);
if (newCampaignList != null && newCampaignList.size() > 0) {
Collections.sort(newCampaignList, (obj1, obj2) -> Integer.compare(obj1.getSorting(), obj2.getSorting()));
WarplyManagerHelper.setCampaignList(newCampaignList);
campaignLoyaltyList.clear();
ArrayList<Campaign> campaignCarouselList = new ArrayList<>();
campaignCarouselList.clear();
for (Campaign camp : newCampaignList) {
JSONObject campMetadata = WarpJSONParser.getJSONFromString(camp.getExtraFields());
if (campMetadata != null) {
if (campMetadata.has("carousel")) {
campaignCarouselList.add(camp);
}
}
try {
JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
if (extraFields != null) {
if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
campaignLoyaltyList.add(camp);
}
}
} catch (Exception exception) {
campaignLoyaltyList.add(camp);
}
}
WarplyManagerHelper.setCarouselList(campaignCarouselList);
Set<Campaign> set = new LinkedHashSet<>(campaignLoyaltyList);
campaignLoyaltyList.clear();
campaignLoyaltyList.addAll(set);
}
return campaignLoyaltyList;
}
public static void getCampaigns(final CallbackReceiver<ArrayList<Campaign>> receiver) {
WarpUtils.log("************* WARPLY Get Campaigns Request ********************");
WarpUtils.log("[WARP Trace] WARPLY Get Campaigns Request is active");
WarpUtils.log("**************************************************");
ApiService service = ApiClient.getRetrofitInstance().create(ApiService.class);
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
ListenableFuture<ArrayList<Campaign>> futureCampaigns = getCampaignsRetro(service);
ListenableFuture<ArrayList<Campaign>> futurePersonalizedCampaigns = getCampaignsPersonalizedRetro(service);
ListenableFuture<List<ArrayList<Campaign>>> allResultsFuture = Futures.allAsList(futureCampaigns, futurePersonalizedCampaigns);
ListenableFuture<ArrayList<Campaign>> mergedResultFuture = Futures.transformAsync(
allResultsFuture,
results -> {
ArrayList<Campaign> resultCampaigns = results.get(0);
ArrayList<Campaign> resultPersonalizedCampaigns = results.get(1);
return executorService.submit(() -> mergeCampaignResults(resultCampaigns, resultPersonalizedCampaigns));
},
executorService
);
Futures.addCallback(mergedResultFuture, new FutureCallback<ArrayList<Campaign>>() {
@Override
public void onSuccess(ArrayList<Campaign> mergedResult) {
executorService.shutdownNow();
new Handler(Looper.getMainLooper()).post(() -> receiver.onSuccess(mergedResult));
}
@Override
public void onFailure(Throwable throwable) {
receiver.onFailure(2);
}
}, executorService);
// getCampaignsRetro(service, new CallbackReceiver<ArrayList<Campaign>>() {
// @Override
// public void onSuccess(ArrayList<Campaign> result) {
// getCampaignsPersonalizedRetro(service, new CallbackReceiver<ArrayList<Campaign>>() {
// @Override
// public void onSuccess(ArrayList<Campaign> resultPersonalized) {
// final ExecutorService executorShops = Executors.newFixedThreadPool(1);
// executorShops.submit(() -> {
// ArrayList<Campaign> newCampaignList = new ArrayList<Campaign>();
// newCampaignList.clear();
// newCampaignList.addAll(result);
// newCampaignList.addAll(resultPersonalized);
// Collections.sort(newCampaignList, (obj1, obj2) -> Integer.compare(obj1.getSorting(), obj2.getSorting()));
// WarplyManagerHelper.setCampaignList(newCampaignList);
// ArrayList<Campaign> campaignLoyaltyList = new ArrayList<>();
// campaignLoyaltyList.clear();
// ArrayList<Campaign> campaignCarouselList = new ArrayList<>();
// campaignCarouselList.clear();
// for (Campaign camp : newCampaignList) {
// JSONObject campMetadata = WarpJSONParser.getJSONFromString(camp.getExtraFields());
// if (campMetadata != null) {
// if (campMetadata.has("carousel")) {
// campaignCarouselList.add(camp);
// }
// }
//
// try {
// JSONObject extraFields = WarpJSONParser.getJSONFromString(camp.getExtraFields());
// if (extraFields != null) {
// if (extraFields.length() == 0 || !(extraFields.has("ccms_offer") || extraFields.has("type"))) {
// campaignLoyaltyList.add(camp);
// }
// }
// } catch (Exception exception) {
// campaignLoyaltyList.add(camp);
// }
// }
// WarplyManagerHelper.setCarouselList(campaignCarouselList);
//
// Set<Campaign> set = new LinkedHashSet<>(campaignLoyaltyList);
// campaignLoyaltyList.clear();
// campaignLoyaltyList.addAll(set);
// executorShops.shutdownNow();
// new Handler(Looper.getMainLooper()).post(() -> receiver.onSuccess(campaignLoyaltyList));//resultPersonalized
// });
// }
//
// @Override
// public void onFailure(int errorCode) {
// receiver.onFailure(errorCode);
// }
// });
// }
//
// @Override
// public void onFailure(int errorCode) {
// receiver.onFailure(errorCode);
// }
// });
}
private static /*void*/ ListenableFuture<ArrayList<Campaign>> getCampaignsRetro(ApiService service/*, final CallbackReceiver<ArrayList<Campaign>> receiver*/) {
SettableFuture<ArrayList<Campaign>> future = SettableFuture.create();
String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
String webId = WarpUtils.getWebId(Warply.getWarplyContext());
Map<String, Object> jsonParamsCampaigns = new ArrayMap<>();
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("action", "retrieve");
jsonParams.put("filters", new JSONObject());
jsonParams.put("language", WarplyProperty.getLanguage(Warply.getWarplyContext()));
jsonParamsCampaigns.put("campaigns", jsonParams);
RequestBody campaignsRequest = RequestBody.create(MediaType.get("application/json; charset=utf-8"), (new JSONObject(jsonParamsCampaigns)).toString());
Call<ResponseBody> campaignsCall = service.getCampaigns(
WarplyProperty.getAppUuid(Warply.getWarplyContext()),
campaignsRequest,
timeStamp,
"android:" + Warply.getWarplyContext().getPackageName(),
new WarplyDeviceInfoCollector(Warply.getWarplyContext()).getUniqueDeviceId(),
"mobile",
webId,
WarpUtils.produceSignature(apiKey + timeStamp)
);
campaignsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
if (response.code() == 200 && response.body() != null) {
JSONObject jobjCampaignsResponse = null;
try {
jobjCampaignsResponse = new JSONObject(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
if (jobjCampaignsResponse != null && jobjCampaignsResponse.has("status") && jobjCampaignsResponse.optString("status", "2").equals("1")) {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_success_campaigns_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
JSONArray jCampaignsBody = null;
try {
jCampaignsBody = jobjCampaignsResponse.optJSONObject("context").optJSONObject("MAPP_CAMPAIGNING").optJSONArray("campaigns");
} catch (Exception e) {
e.printStackTrace();
}
if (jCampaignsBody != null) {
ArrayList<NewCampaign> tempCampaigns = new ArrayList<>();
ArrayList<Campaign> mCampaignsList = new ArrayList<>();
final ExecutorService executorShops = Executors.newFixedThreadPool(1);
JSONArray finalCampaignsJBody = jCampaignsBody;
executorShops.submit(() -> {
for (int i = 0; i < finalCampaignsJBody.length(); ++i) {
tempCampaigns.add(new NewCampaign(finalCampaignsJBody.optJSONObject(i)));
}
for (NewCampaign newCamp : tempCampaigns) {
Campaign camp = new Campaign();
camp.setIndexUrl(newCamp.getIndexUrl());
camp.setLogoUrl(newCamp.getLogoUrl());
camp.setMessage(newCamp.getMessage());
camp.setOfferCategory(newCamp.getCommunicationCategory());
camp.setSessionUUID(newCamp.getCommunicationUUID());
camp.setTitle(newCamp.getTitle());
camp.setSubtitle(newCamp.getSubtitle());
camp.setSorting(newCamp.getSorting());
camp.setNew(newCamp.getIsNew());
camp.setType(newCamp.getCampaignType());
try {
camp.setExtraFields(newCamp.getExtraFields().toString());
if (!TextUtils.isEmpty(newCamp.getExtraFields().toString())) {
JSONObject extraFieldsResp = WarpJSONParser.getJSONFromString(newCamp.getExtraFields().toString());
if (extraFieldsResp != null) {
if (extraFieldsResp.has("Banner_title")) {
camp.setBannerTitle(extraFieldsResp.optString("Banner_title", ""));
}
if (extraFieldsResp.has("Banner_img")) {
camp.setBannerImage(extraFieldsResp.optString("Banner_img", ""));
}
}
} else {
camp.setBannerImage("");
camp.setBannerTitle("");
}
} catch (NullPointerException e) {
camp.setExtraFields("");
camp.setBannerImage("");
camp.setBannerTitle("");
e.printStackTrace();
}
try {
camp.setCampaignTypeSettings(newCamp.getSettings().toString());
} catch (NullPointerException e) {
camp.setCampaignTypeSettings("");
e.printStackTrace();
}
mCampaignsList.add(camp);
}
executorShops.shutdownNow();
// receiver.onSuccess(mCampaignsList);
future.set(mCampaignsList);
});
}
} else {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(2);
future.set(new ArrayList<Campaign>());
}
} else {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(response.code());
future.set(new ArrayList<Campaign>());
}
}
@Override
public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(2);
future.set(new ArrayList<Campaign>());
}
});
return future;
}
private static /*void*/ ListenableFuture<ArrayList<Campaign>> getCampaignsPersonalizedRetro(ApiService service/*, final CallbackReceiver<ArrayList<Campaign>> receiver*/) {
SettableFuture<ArrayList<Campaign>> future = SettableFuture.create();
String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
String webId = WarpUtils.getWebId(Warply.getWarplyContext());
Map<String, Object> jsonParamsCampaigns = new ArrayMap<>();
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("action", "retrieve");
jsonParams.put("language", WarplyProperty.getLanguage(Warply.getWarplyContext()));
jsonParamsCampaigns.put("campaigns", jsonParams);
RequestBody campaignsPersonalizedRequest = RequestBody.create(MediaType.get("application/json; charset=utf-8"), (new JSONObject(jsonParamsCampaigns)).toString());
Call<ResponseBody> campaignsPersonalizedCall = service.getCampaignsPersonalized(
WarplyProperty.getAppUuid(Warply.getWarplyContext()),
campaignsPersonalizedRequest,
timeStamp,
"android:" + Warply.getWarplyContext().getPackageName(),
new WarplyDeviceInfoCollector(Warply.getWarplyContext()).getUniqueDeviceId(),
"mobile",
webId,
WarpUtils.produceSignature(apiKey + timeStamp),
"Bearer " + WarplyDBHelper.getInstance(Warply.getWarplyContext()).getAuthValue("access_token")
);
campaignsPersonalizedCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
if (response.code() == 200 && response.body() != null) {
JSONObject jobjCampaignsResponse = null;
try {
jobjCampaignsResponse = new JSONObject(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
if (jobjCampaignsResponse != null && jobjCampaignsResponse.has("status") && jobjCampaignsResponse.optString("status", "2").equals("1")) {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_success_campaigns_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
JSONArray jCampaignsBody = null;
try {
jCampaignsBody = jobjCampaignsResponse.optJSONObject("context").optJSONObject("MAPP_CAMPAIGNING").optJSONArray("campaigns");
} catch (Exception e) {
e.printStackTrace();
}
if (jCampaignsBody != null) {
ArrayList<NewCampaign> tempCampaigns = new ArrayList<>();
ArrayList<Campaign> mCampaignsList = new ArrayList<>();
final ExecutorService executorShops = Executors.newFixedThreadPool(1);
JSONArray finalCampaignsJBody = jCampaignsBody;
executorShops.submit(() -> {
for (int i = 0; i < finalCampaignsJBody.length(); ++i) {
tempCampaigns.add(new NewCampaign(finalCampaignsJBody.optJSONObject(i)));
}
for (NewCampaign newCamp : tempCampaigns) {
Campaign camp = new Campaign();
camp.setIndexUrl(newCamp.getIndexUrl());
camp.setLogoUrl(newCamp.getLogoUrl());
camp.setMessage(newCamp.getMessage());
camp.setOfferCategory(newCamp.getCommunicationCategory());
camp.setSessionUUID(newCamp.getCommunicationUUID());
camp.setTitle(newCamp.getTitle());
camp.setSubtitle(newCamp.getSubtitle());
camp.setSorting(newCamp.getSorting());
camp.setNew(newCamp.getIsNew());
camp.setType(newCamp.getCampaignType());
try {
camp.setExtraFields(newCamp.getExtraFields().toString());
if (!TextUtils.isEmpty(newCamp.getExtraFields().toString())) {
JSONObject extraFieldsResp = WarpJSONParser.getJSONFromString(newCamp.getExtraFields().toString());
if (extraFieldsResp != null) {
if (extraFieldsResp.has("Banner_title")) {
camp.setBannerTitle(extraFieldsResp.optString("Banner_title", ""));
}
if (extraFieldsResp.has("Banner_img")) {
camp.setBannerImage(extraFieldsResp.optString("Banner_img", ""));
}
}
} else {
camp.setBannerImage("");
camp.setBannerTitle("");
}
} catch (NullPointerException e) {
camp.setExtraFields("");
camp.setBannerImage("");
camp.setBannerTitle("");
e.printStackTrace();
}
try {
camp.setCampaignTypeSettings(newCamp.getSettings().toString());
} catch (NullPointerException e) {
camp.setCampaignTypeSettings("");
e.printStackTrace();
}
mCampaignsList.add(camp);
}
executorShops.shutdownNow();
// receiver.onSuccess(mCampaignsList);
future.set(mCampaignsList);
});
}
} else {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_personalized_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(2);
future.set(new ArrayList<Campaign>());
}
} else if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
getCampaignsPersonalizedRetro(service/*, receiver*/);
else {
// receiver.onFailure(status);
future.set(new ArrayList<Campaign>());
}
}
@Override
public void onFailure(int errorCode) {
// receiver.onFailure(errorCode);
future.set(new ArrayList<Campaign>());
}
});
} else {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_personalized_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(response.code());
future.set(new ArrayList<Campaign>());
}
}
@Override
public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_campaigns_personalized_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
// receiver.onFailure(2);
future.set(new ArrayList<Campaign>());
}
});
return future;
}
public static void getCampaignsPersonalized(WarplyGetCampaignsRequest request, final CallbackReceiver<ArrayList<Campaign>> receiver) {
WarpUtils.log("************* WARPLY Get Campaigns Request ********************");
WarpUtils.log("[WARP Trace] WARPLY Get Campaigns Request is active");
......@@ -3037,7 +3439,25 @@ public class WarplyManager {
couponsetsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
getCouponsetsRetro(service, isFiltered, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......@@ -3107,7 +3527,25 @@ public class WarplyManager {
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
sendTelematicsData(service, accelerationTimestamps, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......@@ -3145,7 +3583,25 @@ public class WarplyManager {
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
cancelUnifiedCoupon(service, transactionID, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......@@ -3182,7 +3638,25 @@ public class WarplyManager {
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
getTelematicsHistory(service, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......@@ -3220,7 +3694,25 @@ public class WarplyManager {
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
getTripMetrics(service, tripId, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......@@ -3259,7 +3751,25 @@ public class WarplyManager {
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
if (response.code() == 401) {
refreshToken(new WarplyRefreshTokenRequest(), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1)
rateTrip(service, tripId, isPositive, callback);
else
callback.onFailure(call, new Throwable());
}
@Override
public void onFailure(int errorCode) {
callback.onFailure(call, new Throwable());
}
});
} else {
callback.onResponse(call, response);
}
}
@Override
......